commit
Add deletions
diff --git a/public/style.css b/public/style.css
index 3d1bc7c..e05ec73 100644
--- a/public/style.css
+++ b/public/style.css
@@ -302,6 +302,13 @@ header nav a[aria-current="page"] { color: var(--text); }
color: var(--text);
}
+.btn.danger:hover:not(:disabled),
+.row .delete:hover:not(:disabled) {
+ border-color: var(--danger);
+ box-shadow: 0 0 0 4px rgb(237 66 69 / 15%);
+ color: var(--danger);
+}
+
.btn:disabled {
color: var(--muted);
cursor: default;
@@ -353,19 +360,24 @@ header nav a[aria-current="page"] { color: var(--text); }
.row .status.ok { color: var(--accent); }
.row .status.err { color: var(--danger); text-align: right; white-space: normal; }
+.actions .status.err { color: var(--danger); }
.row.empty {
justify-content: center;
color: var(--muted);
}
-/* Upload panel (in a folder, signed in) */
+/* Folder tools and upload panel (signed in) */
-.uploader { margin-bottom: 1.5rem; }
-.uploader .listing { margin-bottom: 1rem; }
-.uploader .actions { margin-bottom: 0; }
+.newfolder {
+ display: flex;
+ flex: 1;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ align-items: center;
+}
-.uploader .sub {
+.newfolder .filter {
flex: 1;
min-width: 12rem;
width: auto;
@@ -373,6 +385,10 @@ header nav a[aria-current="page"] { color: var(--text); }
padding: 0.35rem 0.9rem;
}
+.uploader { margin-bottom: 1.5rem; }
+.uploader .listing { margin-bottom: 1rem; }
+.uploader .actions { margin-bottom: 0; }
+
.drop {
display: flex;
flex-wrap: wrap;
diff --git a/shared/folders.ts b/shared/folders.ts
new file mode 100644
index 0000000..44cd762
--- /dev/null
+++ b/shared/folders.ts
@@ -0,0 +1,5 @@
+// R2 only has keys, so a folder exists while something is in it. An empty
+// folder is held open by this zero-byte marker, which the viewer hides. Upload
+// paths can't have dot-names, so nobody's file can clash with it.
+
+export const FOLDER_MARKER = ".keep";
diff --git a/src/env.ts b/src/env.ts
index fc160bc..e06247d 100644
--- a/src/env.ts
+++ b/src/env.ts
@@ -17,7 +17,8 @@ export interface Session {
username: string;
}
-export type AppEnv = { Bindings: Env };
+// `session` is set on API writes, by the guard in main.ts.
+export type AppEnv = { Bindings: Env; Variables: { session: Session } };
export type AppContext = Context<AppEnv>;
export function issuer(env: Env): string {
diff --git a/src/files.ts b/src/files.ts
index ed2b22a..e21df86 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -1,6 +1,7 @@
// Everything backed by the R2 bucket: serving files, listing them for the
-// browser, and uploads.
+// browser, and uploads, new folders and deletes.
+import { FOLDER_MARKER } from "../shared/folders";
import { rawBase, type AppContext } from "./env";
/** Browser cache for served files. URLs can change any time, so nothing longer. */
@@ -158,6 +159,39 @@ export async function uploadFile(c: AppContext, key: string, uploader: string):
return c.json({ path: obj.key, size: obj.size, url: `${rawBase(c.env)}/${encodeKey(obj.key)}` }, 201);
}
+/** POST /api/folders/<key> — an empty folder, held open by its marker. */
+export async function createFolder(c: AppContext, key: string, uploader: string): Promise<Response> {
+ const bad = checkKey(key);
+ if (bad) return c.json({ error: bad }, 400);
+ if (await c.env.BUCKET.head(key)) return c.json({ error: "A file already exists at that path." }, 409);
+ if (await isFolder(c, key)) return c.json({ error: "That folder already exists." }, 409);
+
+ await c.env.BUCKET.put(`${key}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
+ return c.json({ path: key }, 201);
+}
+
+/**
+ * DELETE /api/files/<key> — one file, or a folder's marker (which deletes that
+ * empty folder). Whatever folder the viewer goes back to afterwards keeps
+ * existing, with a marker if nothing else is left in it.
+ */
+export async function deleteFile(c: AppContext, key: string, uploader: string): Promise<Response> {
+ if (!(await c.env.BUCKET.head(key))) return c.json({ error: "No file at that path." }, 404);
+ await c.env.BUCKET.delete(key);
+
+ const deleted = key.endsWith(`/${FOLDER_MARKER}`) ? parentOf(key) : key;
+ const keep = parentOf(deleted);
+ if (keep && !(await isFolder(c, keep))) {
+ await c.env.BUCKET.put(`${keep}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
+ }
+ return c.body(null, 204);
+}
+
+/** "img/avatars/x.png" → "img/avatars"; "" at the top level. */
+function parentOf(key: string): string {
+ return key.slice(0, Math.max(0, key.lastIndexOf("/")));
+}
+
export function encodeKey(key: string): string {
return key.split("/").map(encodeURIComponent).join("/");
}
diff --git a/src/main.ts b/src/main.ts
index 49e5412..08812ac 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 API, the Genshin proxy
+// 2. Worker routes: sign-in, the file API (uploads, folders, deletes), 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
@@ -17,7 +17,7 @@ import { auth, getSession } from "./auth";
import { cors } from "./cors";
import { fileEmbed } from "./embed";
import { issuer, type AppContext, type AppEnv } from "./env";
-import { isFolder, listFiles, serveFile, uploadFile } from "./files";
+import { createFolder, deleteFile, isFolder, listFiles, serveFile, uploadFile } from "./files";
import { genshinUi } from "./genshin";
const app = new Hono<AppEnv>();
@@ -47,19 +47,37 @@ app.get("/api/me", async (c) => {
app.get("/api/list", listFiles);
+// Every write must come from this site (CSRF: the cookie is SameSite=Lax
+// already) and be signed in.
+app.on(["PUT", "POST", "DELETE"], "/api/*", async (c, next) => {
+ if (c.req.header("Origin") !== new URL(c.req.url).origin) return c.json({ error: "Cross-site request refused." }, 403);
+ const session = await getSession(c);
+ if (!session) return c.json({ error: "Signed out. Reload the page to sign in again." }, 401);
+ c.set("session", session);
+ await next();
+});
+
app.get("/api/files/*", async (c) => {
const key = keyFromPath(c, "/api/files/");
return (key && (await serveFile(c, key))) || c.json({ error: "Not found" }, 404);
});
app.put("/api/files/*", async (c) => {
- // 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);
const key = keyFromPath(c, "/api/files/");
if (key === null) return c.json({ error: "That path doesn't decode." }, 400);
- return uploadFile(c, key, session.username);
+ return uploadFile(c, key, c.get("session").username);
+});
+
+app.delete("/api/files/*", async (c) => {
+ const key = keyFromPath(c, "/api/files/");
+ if (key === null) return c.json({ error: "That path doesn't decode." }, 400);
+ return deleteFile(c, key, c.get("session").username);
+});
+
+app.post("/api/folders/*", async (c) => {
+ const key = keyFromPath(c, "/api/folders/");
+ if (key === null) return c.json({ error: "That path doesn't decode." }, 400);
+ return createFolder(c, key, c.get("session").username);
});
app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
diff --git a/web/src/App.svelte b/web/src/App.svelte
index f79ebef..f78638e 100644
--- a/web/src/App.svelte
+++ b/web/src/App.svelte
@@ -13,9 +13,9 @@
let me = $state<{ username: string } | null>(null);
// Fetched once whatever page the visit starts on, since in-app navigation
- // never reloads. After an upload it's refetched fresh.
+ // never reloads. After any change it's refetched fresh.
function load(fresh = false) {
- fetchList(fresh)
+ return fetchList(fresh)
.then((l) => {
listing = l;
failed = false;
@@ -47,9 +47,9 @@
{:else if path === null}
<NotFound />
{:else if file && listing}
- <Preview {file} raw={listing.raw} />
+ <Preview {file} raw={listing.raw} canEdit={Boolean(me)} onchanged={() => load(true)} />
{:else}
- <Browse prefix={path} {listing} {failed} canUpload={Boolean(me)} onuploaded={() => load(true)} />
+ <Browse prefix={path} {listing} {failed} canEdit={Boolean(me)} onchanged={() => load(true)} />
{/if}
</main>
<Footer count={listing?.count} />
diff --git a/web/src/lib/Icon.svelte b/web/src/lib/Icon.svelte
index 7353074..8c118f3 100644
--- a/web/src/lib/Icon.svelte
+++ b/web/src/lib/Icon.svelte
@@ -1,9 +1,11 @@
<script lang="ts">
- // The three icons the browser uses, from iconsax like the rest of doughmination.gay
+ // The icons the browser uses, from iconsax like the rest of doughmination.gay
const NAMES = {
folder: "folder-2",
file: "document",
upload: "document-upload",
+ "new-folder": "folder-add",
+ trash: "trash",
};
let { name }: { name: keyof typeof NAMES } = $props();
diff --git a/web/src/lib/Uploader.svelte b/web/src/lib/Uploader.svelte
index 326d184..93c1691 100644
--- a/web/src/lib/Uploader.svelte
+++ b/web/src/lib/Uploader.svelte
@@ -1,7 +1,7 @@
<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).
+ // and writes them into the R2 bucket, under this folder.
import { untrack } from "svelte";
import Icon from "./Icon.svelte";
@@ -14,9 +14,8 @@
message: string;
}
- let { folder, onuploaded }: { folder: string; onuploaded: () => void } = $props();
+ let { folder, onchanged }: { folder: string; onchanged: () => Promise<void> } = $props();
- let subInput = $state("");
let overwrite = $state(false);
let queue = $state<Item[]>([]);
let busy = $state(false);
@@ -27,12 +26,9 @@
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);
@@ -79,7 +75,7 @@
async function uploadAll() {
busy = true;
- const dir = target;
+ const dir = folder;
for (const item of queue) {
if (item.status === "waiting" || item.status === "error") await put(item, dir);
}
@@ -87,7 +83,7 @@
// Finished uploads now show in the listing, so only failures stay queued.
if (done) {
queue = queue.filter((q) => q.status !== "done");
- onuploaded();
+ onchanged();
}
}
@@ -118,7 +114,7 @@
e.currentTarget.value = "";
}}
/>
- <Icon name="upload" />Drop files here to upload to <strong>/{target}</strong>, or click to pick them.
+ <Icon name="upload" />Drop files here to upload to <strong>/{folder}</strong>, or click to pick them.
</label>
{#if queue.length}
@@ -146,7 +142,6 @@
<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}
diff --git a/web/src/lib/files.ts b/web/src/lib/files.ts
index bfec1f4..e842884 100644
--- a/web/src/lib/files.ts
+++ b/web/src/lib/files.ts
@@ -36,6 +36,18 @@ export async function fetchMe(): Promise<{ username: string } | null> {
}
}
+/** A write to the API (sign-in is checked there); an error message, or null when it worked. */
+export async function apiWrite(method: "POST" | "DELETE", url: string): Promise<string | null> {
+ try {
+ const res = await fetch(url, { method });
+ if (res.ok) return null;
+ const body = await res.json().catch(() => null);
+ return body?.error || `Failed (${res.status}).`;
+ } catch {
+ return "Network error.";
+ }
+}
+
/** Every folder in the listing, e.g. "img" and "img/avatars". */
export function allFolders(files: FileEntry[]): string[] {
const dirs = new Set<string>();
diff --git a/web/src/routes/Browse.svelte b/web/src/routes/Browse.svelte
index 7f243c8..4532818 100644
--- a/web/src/routes/Browse.svelte
+++ b/web/src/routes/Browse.svelte
@@ -1,43 +1,53 @@
<script lang="ts">
// Directory browser over /api/list (every object in the bucket). The path
// is the folder: /f/Comic-Code shows everything under "f/Comic-Code/".
+ // Signed in, it also uploads, makes folders and deletes.
import Crumbs from "../lib/Crumbs.svelte";
import Hero from "../lib/Hero.svelte";
import Icon from "../lib/Icon.svelte";
import Uploader from "../lib/Uploader.svelte";
- import { encodePath, fmtSize, type Listing } from "../lib/files";
- import { link } from "../lib/router.svelte";
+ import { apiWrite, encodePath, fmtSize, type Listing } from "../lib/files";
+ import { link, navigate } from "../lib/router.svelte";
+ import { FOLDER_MARKER } from "../../../shared/folders";
import NotFound from "./NotFound.svelte";
let {
prefix,
listing,
failed,
- canUpload,
- onuploaded,
- }: { prefix: string; listing: Listing | null; failed: boolean; canUpload: boolean; onuploaded: () => void } =
+ canEdit,
+ onchanged,
+ }: { prefix: string; listing: Listing | null; failed: boolean; canEdit: boolean; onchanged: () => Promise<void> } =
$props();
let filter = $state("");
+ let naming = $state(false);
+ let newName = $state("");
+ let working = $state(false);
+ let error = $state("");
- // A new folder starts unfiltered.
+ // A new folder starts unfiltered, with nothing half-done.
$effect.pre(() => {
prefix;
filter = "";
+ naming = false;
+ newName = "";
+ error = "";
});
+ const base = $derived(prefix ? prefix + "/" : "");
+
// Immediate children (folders + files) of the current folder.
const children = $derived.by(() => {
- const base = prefix ? prefix + "/" : "";
const folders = new Set<string>();
const files: { name: string; path: string; size: number }[] = [];
for (const f of listing?.files ?? []) {
if (!f.path.startsWith(base)) continue;
const rest = f.path.slice(base.length);
const slash = rest.indexOf("/");
- if (slash === -1) files.push({ name: rest, path: f.path, size: f.size });
- else folders.add(rest.slice(0, slash));
+ if (slash !== -1) folders.add(rest.slice(0, slash));
+ else if (rest !== FOLDER_MARKER) files.push({ name: rest, path: f.path, size: f.size });
}
return {
folders: [...folders].sort((a, b) => a.localeCompare(b)),
@@ -48,9 +58,41 @@
const q = $derived(filter.trim().toLowerCase());
const folders = $derived(children.folders.filter((n) => !q || n.toLowerCase().includes(q)));
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);
+ // A folder held open only by its marker still exists; it's just empty.
+ const missing = $derived(listing !== null && prefix !== "" && !listing.files.some((f) => f.path.startsWith(base)));
+ const empty = $derived(!children.folders.length && !children.files.length);
const childHref = (name: string) => `/${encodePath(prefix ? `${prefix}/${name}` : name)}`;
+ const parentHref = $derived(`/${encodePath(prefix.slice(0, Math.max(0, prefix.lastIndexOf("/"))))}`);
+
+ /** Runs one API write, then reloads the listing and (if given) goes to `then`. */
+ async function change(method: "POST" | "DELETE", url: string, then?: string) {
+ working = true;
+ error = (await apiWrite(method, url)) ?? "";
+ if (!error) {
+ await onchanged();
+ if (then) navigate(then);
+ }
+ working = false;
+ }
+
+ function createFolder(e: SubmitEvent) {
+ e.preventDefault();
+ const name = newName.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
+ if (!name) return;
+ const path = prefix ? `${prefix}/${name}` : name;
+ change("POST", `/api/folders/${encodePath(path)}`, `/${encodePath(path)}`);
+ }
+
+ function deleteFile(f: { name: string; path: string }) {
+ if (confirm(`Delete ${f.name}? Anything linking to it will break.`)) {
+ change("DELETE", `/api/files/${encodePath(f.path)}`);
+ }
+ }
+
+ function deleteFolder() {
+ change("DELETE", `/api/files/${encodePath(`${prefix}/${FOLDER_MARKER}`)}`, parentHref);
+ }
</script>
<svelte:head><title>{prefix ? `${prefix} · CDN` : "CDN"}</title></svelte:head>
@@ -73,9 +115,26 @@
<div class="content">
<Crumbs path={prefix} />
- <!-- Signed-in visitors upload straight into the folder they're looking at. -->
- {#if canUpload}
- <Uploader folder={prefix} {onuploaded} />
+ <!-- Signed-in visitors manage the folder they're looking at. -->
+ {#if canEdit && listing}
+ <div class="actions">
+ {#if naming}
+ <form class="newfolder" onsubmit={createFolder}>
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="filter" type="text" placeholder="Folder name" autocomplete="off" spellcheck="false" autofocus disabled={working} bind:value={newName} />
+ <button class="btn" type="submit" disabled={working || !newName.trim()}>Create</button>
+ <button class="btn" type="button" disabled={working} onclick={() => (naming = false)}>Cancel</button>
+ </form>
+ {:else}
+ <button class="btn" type="button" onclick={() => (naming = true)}><Icon name="new-folder" />New folder</button>
+ {#if prefix && empty}
+ <button class="btn danger" type="button" disabled={working} onclick={deleteFolder}><Icon name="trash" />Delete folder</button>
+ {/if}
+ {/if}
+ {#if error}<span class="status err">{error}</span>{/if}
+ </div>
+
+ <Uploader folder={prefix} {onchanged} />
{/if}
<input class="filter" type="search" placeholder="Filter this folder…" autocomplete="off" bind:value={filter} />
@@ -95,6 +154,9 @@
<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>
+ {#if canEdit}
+ <button class="remove delete" title="Delete {f.name}" aria-label="Delete {f.name}" disabled={working} onclick={() => deleteFile(f)}><Icon name="trash" /></button>
+ {/if}
</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 6110c43..8b9936c 100644
--- a/web/src/routes/Preview.svelte
+++ b/web/src/routes/Preview.svelte
@@ -5,10 +5,20 @@
import Crumbs from "../lib/Crumbs.svelte";
import Hero from "../lib/Hero.svelte";
- import { copyText, encodePath, fmtSize, type FileEntry } from "../lib/files";
+ import Icon from "../lib/Icon.svelte";
+ import { apiWrite, copyText, encodePath, fmtSize, type FileEntry } from "../lib/files";
+ import { navigate } from "../lib/router.svelte";
import { extensionOf, kindOf } from "../../../shared/kinds";
- let { file, raw }: { file: FileEntry; raw: string } = $props();
+ let {
+ file,
+ raw,
+ canEdit,
+ onchanged,
+ }: { file: FileEntry; raw: string; canEdit: boolean; onchanged: () => Promise<void> } = $props();
+
+ let deleting = $state(false);
+ let error = $state("");
/** Bigger text files only get the links; nobody wants to scroll that. */
const MAX_TEXT = 512 * 1024;
@@ -21,6 +31,18 @@
const page = $derived(`${location.origin}/${encodePath(file.path)}`);
const local = $derived(`/api/files/${encodePath(file.path)}`);
+ // Back to the folder afterwards; the worker keeps it even if it's now empty.
+ async function remove() {
+ if (!confirm(`Delete ${name}? Anything linking to it will break.`)) return;
+ deleting = true;
+ error = (await apiWrite("DELETE", local)) ?? "";
+ if (!error) {
+ await onchanged();
+ navigate(`/${encodePath(file.path.slice(0, Math.max(0, file.path.lastIndexOf("/"))))}`);
+ }
+ deleting = false;
+ }
+
const text = $derived(
kind === "text" && file.size <= MAX_TEXT
? fetch(local, { cache: "no-cache" }).then((r) => {
@@ -45,6 +67,10 @@
<a class="btn" href={local} download={name}>Download</a>
<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>
+ {#if canEdit}
+ <button class="btn danger" type="button" disabled={deleting} onclick={remove}><Icon name="trash" />Delete</button>
+ {/if}
+ {#if error}<span class="status err">{error}</span>{/if}
</div>
<div class="preview">