commit
Reformat CDN
diff --git a/public/style.css b/public/style.css
index 638ff9c..3d1bc7c 100644
--- a/public/style.css
+++ b/public/style.css
@@ -272,12 +272,7 @@ header nav a[aria-current="page"] { color: var(--text); }
/* Pill buttons */
-.folderbar { margin-bottom: 1rem; }
-.folderbar:empty { margin-bottom: 0; }
-
-.folderbtn,
.btn,
-.row .copy,
.row .remove {
display: inline-flex;
gap: 0.4em;
@@ -294,16 +289,13 @@ header nav a[aria-current="page"] { color: var(--text); }
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
-.row .copy,
.row .remove {
padding: 0.15rem 0.7rem;
color: var(--muted);
font-size: 0.8rem;
}
-.folderbtn:hover,
.btn:hover:not(:disabled),
-.row .copy:hover,
.row .remove:hover {
border-color: rgb(235 69 158 / 40%);
box-shadow: 0 0 0 4px var(--accent-dim);
@@ -367,26 +359,28 @@ header nav a[aria-current="page"] { color: var(--text); }
color: var(--muted);
}
-/* Upload page */
+/* Upload panel (in a folder, signed in) */
-.field {
- display: block;
- margin: 0 0 1rem;
-}
+.uploader { margin-bottom: 1.5rem; }
+.uploader .listing { margin-bottom: 1rem; }
+.uploader .actions { margin-bottom: 0; }
-.field .label {
- display: block;
- margin-bottom: 0.3rem;
- color: var(--muted);
- font-size: 0.85rem;
+.uploader .sub {
+ flex: 1;
+ min-width: 12rem;
+ width: auto;
+ margin-bottom: 0;
+ padding: 0.35rem 0.9rem;
}
-.field .filter { margin-bottom: 0; }
-
.drop {
- display: block;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4em;
+ align-items: center;
+ justify-content: center;
margin-bottom: 1rem;
- padding: 2.5rem 1rem;
+ padding: 1.5rem 1rem;
border: 1px dashed var(--line);
border-radius: 1rem;
background: var(--raised);
@@ -404,6 +398,8 @@ header nav a[aria-current="page"] { color: var(--text); }
color: var(--text);
}
+.drop strong { color: var(--text); font-weight: 500; overflow-wrap: anywhere; }
+
.drop input {
position: absolute;
width: 1px;
@@ -543,9 +539,7 @@ footer img { border-radius: 50%; }
}
@media (prefers-reduced-motion: reduce) {
- .folderbtn,
.btn,
- .row .copy,
.row .remove,
.drop { transition: none; }
}
diff --git a/src/auth.ts b/src/auth.ts
index d41271f..875bd82 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -63,7 +63,7 @@ const cookieOpts = (maxAge: number) =>
/** Only same-site paths, so /login can't be used as an open redirect. */
function safeNext(raw: string | undefined): string {
- return raw && raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") ? raw : "/upload";
+ return raw && raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") ? raw : "/";
}
function redirectUri(c: AppContext): string {
diff --git a/src/main.ts b/src/main.ts
index 25f2d99..49e5412 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -5,7 +5,7 @@
// Order of business for a request:
//
// 1. CORS (allowlisted origins get Access-Control-Allow-Origin)
-// 2. Worker routes: sign-in, the upload page + API, the Genshin proxy
+// 2. Worker routes: sign-in, the upload API, the Genshin proxy
// 3. Static site files (the Svelte app from ./dist, styles, .well-known, …)
// 4. Otherwise the app shell, if the path is a folder or a file in R2:
// /img browses "img/", /img/foo.png previews that file (with link-embed
@@ -33,15 +33,10 @@ app.route("/", auth);
// --- upload -------------------------------------------------------------------------
-app.get("/upload", async (c) => {
- const session = await getSession(c);
- if (!session) {
- const url = new URL(c.req.url);
- return c.redirect(`/login?next=${encodeURIComponent(url.pathname + url.search)}`);
- }
- const res = await shell(c);
- res.headers.set("Cache-Control", "no-store");
- return res;
+// Uploads happen in the folder itself now; old /upload?folder= links land there.
+app.get("/upload", (c) => {
+ const folder = (c.req.query("folder") ?? "").replace(/^\/+|\/+$/g, "");
+ return c.redirect(`/${folder.split("/").map(encodeURIComponent).join("/")}`);
});
app.get("/api/me", async (c) => {
@@ -58,7 +53,7 @@ app.get("/api/files/*", async (c) => {
});
app.put("/api/files/*", async (c) => {
- // CSRF: the cookie is SameSite=Lax already, and uploads must come from this page.
+ // CSRF: the cookie is SameSite=Lax already, and uploads must come from this site.
if (c.req.header("Origin") !== new URL(c.req.url).origin) return c.json({ error: "Cross-site upload refused." }, 403);
const session = await getSession(c);
if (!session) return c.json({ error: "Signed out. Reload the page to sign in again." }, 401);
diff --git a/web/src/App.svelte b/web/src/App.svelte
index c5b26d0..f79ebef 100644
--- a/web/src/App.svelte
+++ b/web/src/App.svelte
@@ -7,19 +7,23 @@
import Licence from "./routes/Licence.svelte";
import NotFound from "./routes/NotFound.svelte";
import Preview from "./routes/Preview.svelte";
- import Upload from "./routes/Upload.svelte";
let listing = $state<Listing | null>(null);
let failed = $state(false);
- let canUpload = $state(false);
+ let me = $state<{ username: string } | null>(null);
- // The upload page fetches its own (fresh) copy.
- if (route.path !== "/upload") {
- fetchList()
- .then((l) => (listing = l))
+ // Fetched once whatever page the visit starts on, since in-app navigation
+ // never reloads. After an upload it's refetched fresh.
+ function load(fresh = false) {
+ fetchList(fresh)
+ .then((l) => {
+ listing = l;
+ failed = false;
+ })
.catch(() => (failed = true));
- fetchMe().then((me) => (canUpload = Boolean(me)));
}
+ load();
+ fetchMe().then((m) => (me = m));
// "/img/avatars/" → "img/avatars"; null if the path doesn't decode.
const path = $derived.by(() => {
@@ -36,18 +40,16 @@
);
</script>
-<Header />
+<Header {me} />
<main class="wrap">
- {#if route.path === "/upload"}
- <Upload />
- {:else if route.path === "/licence"}
+ {#if route.path === "/licence"}
<Licence />
{:else if path === null}
<NotFound />
{:else if file && listing}
<Preview {file} raw={listing.raw} />
{:else}
- <Browse prefix={path} {listing} {failed} {canUpload} />
+ <Browse prefix={path} {listing} {failed} canUpload={Boolean(me)} onuploaded={() => load(true)} />
{/if}
</main>
<Footer count={listing?.count} />
diff --git a/web/src/lib/Header.svelte b/web/src/lib/Header.svelte
index 354d91a..1bbf3f7 100644
--- a/web/src/lib/Header.svelte
+++ b/web/src/lib/Header.svelte
@@ -2,6 +2,8 @@
import { link, route } from "./router.svelte";
import { AVATAR, SITE_NAME } from "./site";
+ let { me }: { me: { username: string } | null } = $props();
+
const current = (path: string) => (route.path === path ? "page" : undefined);
</script>
@@ -15,9 +17,13 @@
</a>
<nav>
<a href="/" use:link aria-current={current("/")}>Files</a>
- <!-- Not use:link: the worker sends signed-out visitors to sign in first. -->
- <a href="/upload" aria-current={current("/upload")}>Upload</a>
<a href="/licence" use:link aria-current={current("/licence")}>Licence</a>
+ <!-- Not use:link: both go through the worker. Signing in comes back to this page. -->
+ {#if me}
+ <a href="/logout" title="Signed in as @{me.username}">Sign out</a>
+ {:else}
+ <a href="/login?next={encodeURIComponent(route.path)}">Sign in</a>
+ {/if}
<a href="https://doughmination.gay">doughmination.gay</a>
</nav>
</header>
diff --git a/web/src/lib/Uploader.svelte b/web/src/lib/Uploader.svelte
new file mode 100644
index 0000000..326d184
--- /dev/null
+++ b/web/src/lib/Uploader.svelte
@@ -0,0 +1,153 @@
+<script lang="ts">
+ // Upload panel shown in a folder to signed-in visitors. Files go one at a
+ // time as raw PUTs to /api/files/<path>; the worker checks the SSO session
+ // and writes them into the R2 bucket, under this folder (or a new subfolder).
+
+ import { untrack } from "svelte";
+ import Icon from "./Icon.svelte";
+ import { encodePath, fmtSize } from "./files";
+
+ interface Item {
+ file: File;
+ status: "waiting" | "uploading" | "done" | "error";
+ progress: number;
+ message: string;
+ }
+
+ let { folder, onuploaded }: { folder: string; onuploaded: () => void } = $props();
+
+ let subInput = $state("");
+ let overwrite = $state(false);
+ let queue = $state<Item[]>([]);
+ let busy = $state(false);
+ let over = $state(false);
+
+ // A new folder starts with an empty queue.
+ $effect.pre(() => {
+ folder;
+ untrack(() => {
+ if (!busy) queue = [];
+ subInput = "";
+ });
+ });
+
+ const sub = $derived(subInput.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"));
+ const target = $derived([folder, sub].filter(Boolean).join("/"));
+ const pending = $derived(queue.filter((q) => q.status === "waiting" || q.status === "error").length);
+ const done = $derived(queue.filter((q) => q.status === "done").length);
+
+ function add(files: FileList | null | undefined) {
+ for (const file of files ?? []) {
+ // Picking the same name again replaces the earlier pick.
+ queue = queue.filter((q) => q.file.name !== file.name || q.status === "done");
+ queue.push({ file, status: "waiting", progress: 0, message: "" });
+ }
+ }
+
+ function put(item: Item, dir: string) {
+ return new Promise<void>((resolve) => {
+ const path = dir ? `${dir}/${item.file.name}` : item.file.name;
+ const xhr = new XMLHttpRequest();
+ xhr.open("PUT", `/api/files/${encodePath(path)}${overwrite ? "?overwrite=1" : ""}`);
+ if (item.file.type) xhr.setRequestHeader("Content-Type", item.file.type);
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable) item.progress = Math.round((e.loaded / e.total) * 100);
+ };
+ xhr.onload = () => {
+ let body: { url?: string; error?: string } | null = null;
+ try {
+ body = JSON.parse(xhr.responseText);
+ } catch {}
+ if (xhr.status === 201 && body?.url) {
+ item.status = "done";
+ } else {
+ item.status = "error";
+ item.message = body?.error || (xhr.status === 413 ? "Too big for one upload." : `Failed (${xhr.status}).`);
+ }
+ resolve();
+ };
+ xhr.onerror = () => {
+ item.status = "error";
+ item.message = "Network error.";
+ resolve();
+ };
+ item.status = "uploading";
+ item.progress = 0;
+ xhr.send(item.file);
+ });
+ }
+
+ async function uploadAll() {
+ busy = true;
+ const dir = target;
+ for (const item of queue) {
+ if (item.status === "waiting" || item.status === "error") await put(item, dir);
+ }
+ busy = false;
+ // Finished uploads now show in the listing, so only failures stay queued.
+ if (done) {
+ queue = queue.filter((q) => q.status !== "done");
+ onuploaded();
+ }
+ }
+
+ function dragOver(e: DragEvent) {
+ e.preventDefault();
+ over = true;
+ }
+</script>
+
+<section class="uploader">
+ <label
+ class="drop"
+ class:over
+ ondragenter={dragOver}
+ ondragover={dragOver}
+ ondragleave={() => (over = false)}
+ ondrop={(e) => {
+ e.preventDefault();
+ over = false;
+ add(e.dataTransfer?.files);
+ }}
+ >
+ <input
+ type="file"
+ multiple
+ onchange={(e) => {
+ add(e.currentTarget.files);
+ e.currentTarget.value = "";
+ }}
+ />
+ <Icon name="upload" />Drop files here to upload to <strong>/{target}</strong>, or click to pick them.
+ </label>
+
+ {#if queue.length}
+ <ul class="listing">
+ {#each queue as item, i (item)}
+ <li class="row file">
+ <span class="name">{item.file.name}</span>
+ <span class="size">{fmtSize(item.file.size)}</span>
+ {#if item.status === "uploading"}
+ <span class="status">{item.progress}%</span>
+ {:else if item.status === "done"}
+ <span class="status ok">done</span>
+ {:else if item.status === "error"}
+ <span class="status err">{item.message}</span>
+ {:else if busy}
+ <span class="status">waiting</span>
+ {:else}
+ <button class="remove" onclick={() => queue.splice(i, 1)}>remove</button>
+ {/if}
+ </li>
+ {/each}
+ </ul>
+
+ <div class="actions">
+ <button class="btn" type="button" disabled={busy || pending === 0} onclick={uploadAll}>
+ {pending > 1 ? `Upload ${pending} files` : "Upload"}
+ </button>
+ <input class="filter sub" type="text" placeholder="Into a subfolder (optional)" autocomplete="off" spellcheck="false" disabled={busy} bind:value={subInput} />
+ <label><input type="checkbox" bind:checked={overwrite} /> Replace existing files</label>
+ </div>
+ {/if}
+</section>
diff --git a/web/src/routes/Browse.svelte b/web/src/routes/Browse.svelte
index 9092d04..7f243c8 100644
--- a/web/src/routes/Browse.svelte
+++ b/web/src/routes/Browse.svelte
@@ -5,7 +5,8 @@
import Crumbs from "../lib/Crumbs.svelte";
import Hero from "../lib/Hero.svelte";
import Icon from "../lib/Icon.svelte";
- import { copyText, encodePath, fmtSize, type Listing } from "../lib/files";
+ import Uploader from "../lib/Uploader.svelte";
+ import { encodePath, fmtSize, type Listing } from "../lib/files";
import { link } from "../lib/router.svelte";
import NotFound from "./NotFound.svelte";
@@ -14,7 +15,9 @@
listing,
failed,
canUpload,
- }: { prefix: string; listing: Listing | null; failed: boolean; canUpload: boolean } = $props();
+ onuploaded,
+ }: { prefix: string; listing: Listing | null; failed: boolean; canUpload: boolean; onuploaded: () => void } =
+ $props();
let filter = $state("");
@@ -47,7 +50,6 @@
const files = $derived(children.files.filter((f) => !q || f.name.toLowerCase().includes(q)));
const missing = $derived(listing !== null && prefix !== "" && !children.folders.length && !children.files.length);
- const fileUrl = (path: string) => `${listing!.raw}/${encodePath(path)}`;
const childHref = (name: string) => `/${encodePath(prefix ? `${prefix}/${name}` : name)}`;
</script>
@@ -71,12 +73,10 @@
<div class="content">
<Crumbs path={prefix} />
- <!-- Uploaders get a shortcut to the upload page, aimed at this folder. -->
- <div class="folderbar">
- {#if canUpload}
- <a class="folderbtn" href="/upload?folder={encodeURIComponent(prefix)}"><Icon name="upload" />Upload here</a>
- {/if}
- </div>
+ <!-- Signed-in visitors upload straight into the folder they're looking at. -->
+ {#if canUpload}
+ <Uploader folder={prefix} {onuploaded} />
+ {/if}
<input class="filter" type="search" placeholder="Filter this folder…" autocomplete="off" bind:value={filter} />
@@ -95,7 +95,6 @@
<li class="row file">
<a class="name" href={childHref(f.name)} use:link><Icon name="file" />{f.name}</a>
<span class="size">{fmtSize(f.size)}</span>
- <button class="copy" title="Copy URL" onclick={(e) => copyText(e.currentTarget, fileUrl(f.path))}>copy</button>
</li>
{:else}
{#if !folders.length}<li class="row empty">Nothing here.</li>{/if}
diff --git a/web/src/routes/Preview.svelte b/web/src/routes/Preview.svelte
index 10210e6..6110c43 100644
--- a/web/src/routes/Preview.svelte
+++ b/web/src/routes/Preview.svelte
@@ -17,6 +17,8 @@
const ext = $derived(extensionOf(file.path));
const kind = $derived(kindOf(file.path));
const url = $derived(`${raw}/${encodePath(file.path)}`);
+ // This preview page, as opposed to the raw file.
+ const page = $derived(`${location.origin}/${encodePath(file.path)}`);
const local = $derived(`/api/files/${encodePath(file.path)}`);
const text = $derived(
@@ -41,7 +43,8 @@
<div class="actions">
<a class="btn" href={url} target="_blank" rel="noopener">Open raw</a>
<a class="btn" href={local} download={name}>Download</a>
- <button class="btn" type="button" onclick={(e) => copyText(e.currentTarget, url)}>Copy URL</button>
+ <button class="btn" type="button" title={page} onclick={(e) => copyText(e.currentTarget, page)}>Copy URL</button>
+ <button class="btn" type="button" title={url} onclick={(e) => copyText(e.currentTarget, url)}>Copy raw</button>
</div>
<div class="preview">
diff --git a/web/src/routes/Upload.svelte b/web/src/routes/Upload.svelte
deleted file mode 100644
index ff7a6c1..0000000
--- a/web/src/routes/Upload.svelte
+++ /dev/null
@@ -1,168 +0,0 @@
-<script lang="ts">
- // Upload page. Files go one at a time as raw PUTs to /api/files/<path>; the
- // worker checks the SSO session and writes them into the R2 bucket.
-
- import Hero from "../lib/Hero.svelte";
- import { allFolders, copyText, encodePath, fetchList, fetchMe, fmtSize } from "../lib/files";
-
- interface Item {
- file: File;
- status: "waiting" | "uploading" | "done" | "error";
- progress: number;
- message: string;
- url: string;
- }
-
- // "Upload here" from the browser links to /upload?folder=<folder>.
- let folderInput = $state(new URLSearchParams(location.search).get("folder") ?? "");
- let overwrite = $state(false);
- let queue = $state<Item[]>([]);
- let busy = $state(false);
- let over = $state(false);
- let who = $state("…");
- let suggestions = $state<string[]>([]);
-
- const folder = $derived(folderInput.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"));
- const pending = $derived(queue.filter((q) => q.status === "waiting" || q.status === "error").length);
- const done = $derived(queue.filter((q) => q.status === "done").length);
-
- fetchMe().then((me) => (who = me ? `@${me.username}` : "nobody"));
- loadFolders();
-
- // Suggest existing folders.
- async function loadFolders() {
- try {
- suggestions = allFolders((await fetchList(true)).files);
- } catch {}
- }
-
- function add(files: FileList | null | undefined) {
- for (const file of files ?? []) {
- // Picking the same name again replaces the earlier pick.
- queue = queue.filter((q) => q.file.name !== file.name || q.status === "done");
- queue.push({ file, status: "waiting", progress: 0, message: "", url: "" });
- }
- }
-
- function put(item: Item) {
- return new Promise<void>((resolve) => {
- const path = folder ? `${folder}/${item.file.name}` : item.file.name;
- const xhr = new XMLHttpRequest();
- xhr.open("PUT", `/api/files/${encodePath(path)}${overwrite ? "?overwrite=1" : ""}`);
- if (item.file.type) xhr.setRequestHeader("Content-Type", item.file.type);
- xhr.upload.onprogress = (e) => {
- if (e.lengthComputable) item.progress = Math.round((e.loaded / e.total) * 100);
- };
- xhr.onload = () => {
- let body: { url?: string; error?: string } | null = null;
- try {
- body = JSON.parse(xhr.responseText);
- } catch {}
- if (xhr.status === 201 && body?.url) {
- item.status = "done";
- item.url = body.url;
- } else {
- item.status = "error";
- item.message = body?.error || (xhr.status === 413 ? "Too big for one upload." : `Failed (${xhr.status}).`);
- }
- resolve();
- };
- xhr.onerror = () => {
- item.status = "error";
- item.message = "Network error.";
- resolve();
- };
- item.status = "uploading";
- item.progress = 0;
- xhr.send(item.file);
- });
- }
-
- async function uploadAll() {
- busy = true;
- for (const item of queue) {
- if (item.status === "waiting" || item.status === "error") await put(item);
- }
- busy = false;
- loadFolders();
- }
-
- function dragOver(e: DragEvent) {
- e.preventDefault();
- over = true;
- }
-</script>
-
-<svelte:head><title>Upload</title></svelte:head>
-
-<Hero eyebrow="Signed in as {who}" title="Upload">
- <p class="lede"><a href="/{encodePath(folder)}">Browse this folder</a> · <a href="/logout">Sign out</a></p>
-</Hero>
-
-<div class="content">
- <label class="field">
- <span class="label">Folder (blank for the top level)</span>
- <input class="filter" type="text" list="folders" placeholder="img/avatars" autocomplete="off" spellcheck="false" bind:value={folderInput} />
- <datalist id="folders">
- {#each suggestions as d (d)}<option value={d}></option>{/each}
- </datalist>
- </label>
-
- <label
- class="drop"
- class:over
- ondragenter={dragOver}
- ondragover={dragOver}
- ondragleave={() => (over = false)}
- ondrop={(e) => {
- e.preventDefault();
- over = false;
- add(e.dataTransfer?.files);
- }}
- >
- <input
- type="file"
- multiple
- onchange={(e) => {
- add(e.currentTarget.files);
- e.currentTarget.value = "";
- }}
- />
- Drop files here, or click to pick them.
- </label>
-
- <div class="actions">
- <button class="btn" type="button" disabled={busy || pending === 0} onclick={uploadAll}>
- {pending > 1 ? `Upload ${pending} files` : "Upload"}
- </button>
- <label><input type="checkbox" bind:checked={overwrite} /> Replace files that already exist</label>
- <span>{done ? `${done} uploaded` : ""}</span>
- </div>
-
- <ul class="listing">
- {#each queue as item, i (item)}
- <li class="row file">
- {#if item.status === "done"}
- <a class="name" href={item.url} target="_blank" rel="noopener">{item.file.name}</a>
- {:else}
- <span class="name">{item.file.name}</span>
- {/if}
- <span class="size">{fmtSize(item.file.size)}</span>
- {#if item.status === "uploading"}
- <span class="status">{item.progress}%</span>
- {:else if item.status === "done"}
- <span class="status ok">done</span>
- <button class="copy" title="Copy URL" onclick={(e) => copyText(e.currentTarget, item.url)}>copy</button>
- {:else if item.status === "error"}
- <span class="status err">{item.message}</span>
- {:else if busy}
- <span class="status">waiting</span>
- {:else}
- <button class="remove" onclick={() => queue.splice(i, 1)}>remove</button>
- {/if}
- </li>
- {:else}
- <li class="row empty">No files picked yet.</li>
- {/each}
- </ul>
-</div>