diff --git a/.gitignore b/.gitignore index a0d338c..deebeec 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,9 @@ build/ .vscode/* !.vscode/extensions.json .DS_Store -Thumbs.db \ No newline at end of file +Thumbs.db + +# plain txt files +.txt +# uploaded media (local dev) +server/uploads/ diff --git a/CLAUDE.md b/CLAUDE.md index 06fe51f..977fbfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ Frontend (repo root): - `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) - There is no test suite. -Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`) and `DB_PATH` (default `./ngu.db`); locally, use `DB_PATH=./dev.db`: +Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created @@ -30,6 +30,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - App deployed to `/srv/ngu-api`; database at `/var/lib/ngu/ngu.db` - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. +- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. diff --git a/docs/media-uploads.md b/docs/media-uploads.md new file mode 100644 index 0000000..d548e27 --- /dev/null +++ b/docs/media-uploads.md @@ -0,0 +1,71 @@ +# Media uploads + +Images uploaded in the admin (Media page, or the Upload and Choose +from library buttons on any image field) are stored on disk and listed +in the `media` table (`server/src/migrations/028_media.sql`). + +## How files are stored + +- An image field stores the file's public path, `/uploads/`. It + still accepts a bare filename in that field's `public/` directory or a + full URL, as before. +- By default a photo is turned upright, shrunk to fit 2400px on its + longest side, and saved as WebP. This also strips its metadata, + camera location included. Limit: 25 MB per file. +- **Keep original** stores the file exactly as uploaded (up to 10 MB), + metadata and all. +- SVGs are always kept as they are. +- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the + file's contents, not its name. +- Editors and up can upload. Admins and up can delete. The Media page + shows which tables still use a file before deleting it, because + nothing stops a file a record uses from being deleted. + +Limits and sizes are constants at the top of `server/src/media.js`. + +## Local development + +The API reads `UPLOADS_DIR` (default `./uploads`, so `server/uploads/`, +which git ignores). The API serves `/uploads/` itself, and Vite proxies +`/uploads` to the same target as `/api`. + +## Production + +1. Create the directory, owned by the service user: + + ```sh + sudo mkdir -p /var/lib/ngu/uploads + sudo chown : /var/lib/ngu/uploads + ``` + +2. Set it in the `ngu-api` unit (`systemctl edit ngu-api`): + + ```ini + [Service] + Environment=UPLOADS_DIR=/var/lib/ngu/uploads + ``` + + It lives outside `/srv/ngu-api` so an rsync deploy never deletes it. + Back it up alongside the database. + +3. In the nginx site, let uploads through and serve them from disk: + + ```nginx + # In the server block. nginx's default is 1 MB. + client_max_body_size 26m; + + location /uploads/ { + alias /var/lib/ngu/uploads/; + expires 30d; + add_header Cache-Control "public, immutable"; + add_header X-Content-Type-Options nosniff; + # An uploaded SVG opened on its own can't run script. + add_header Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + } + ``` + + Filenames are random and never reused, so `immutable` is safe. + +4. `sharp` is a server dependency now: run `pnpm install` in + `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, + so no build tools are needed. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 6f14402..b473c46 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -32,6 +32,7 @@ what a dropdown in the admin editor says. | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | +| Uploaded images | disk + the `media` table | Admin → Media, or any image field. See `docs/media-uploads.md` | The rule of thumb from `CLAUDE.md`: data belongs in the database, presentation belongs in code. A dropdown's *values* are data the diff --git a/server/package.json b/server/package.json index f898f59..9f206bf 100644 --- a/server/package.json +++ b/server/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@hono/node-server": "^1.0.0", - "hono": "^4.0.0" + "hono": "^4.0.0", + "sharp": "^0.35.4" } } diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index aae1e31..95d227b 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -345,6 +345,7 @@ const events = { text("event_logo"), text("color"), text("gradient"), + text("card_image"), bool("is_published"), bool("is_listed"), bool("in_timeline"), diff --git a/server/src/index.js b/server/src/index.js index 14fdde7..1fde53f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -8,7 +8,10 @@ there too. ═══════════════════════════════════════════════════════════════ */ +import { mkdir } from "node:fs/promises"; + import { serve } from "@hono/node-server"; +import { serveStatic } from "@hono/node-server/serve-static"; import { Hono } from "hono"; import { logger } from "hono/logger"; @@ -24,6 +27,8 @@ import auth from "./routes/auth.js"; import admin from "./routes/admin.js"; import panel from "./routes/panel.js"; import adminEntities from "./routes/admin-entities.js"; +import media from "./routes/media.js"; +import { UPLOADS_DIR } from "./media.js"; import { startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { ENTITIES } from "./admin-schema.js"; @@ -39,6 +44,8 @@ const version = migrate(db); syncDescriptorsWithSchema(db, ENTITIES); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); +await mkdir(UPLOADS_DIR, { recursive: true }); +console.log(`uploads ${UPLOADS_DIR}`); /* ── App ─────────────────────────────────────────────────────── */ @@ -69,8 +76,30 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 })); app.route("/api/admin/panel", panel); app.route("/api/auth", auth); app.route("/api/admin", admin); +// Before the entity routes, whose /:entity would claim /media. +app.route("/api/admin", media); app.route("/api/admin", adminEntities); +/* ── Uploads ─────────────────────────────────────────────────── + In production nginx serves /uploads/ straight from disk and + never passes it here. This is for development, where Vite + proxies /uploads to the API. The headers match the nginx + block's: an uploaded SVG opened on its own can't run script. + ───────────────────────────────────────────────────────────── */ + +app.use("/uploads/*", async (c, next) => { + await next(); + c.header("X-Content-Type-Options", "nosniff"); + c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox"); +}); +app.use( + "/uploads/*", + serveStatic({ + root: UPLOADS_DIR, + rewriteRequestPath: (p) => p.replace(/^\/uploads/, ""), + }), +); + startSessionSweeper(db); app.notFound((c) => c.json({ error: "Not found" }, 404)); diff --git a/server/src/media.js b/server/src/media.js new file mode 100644 index 0000000..c4a5b91 --- /dev/null +++ b/server/src/media.js @@ -0,0 +1,184 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA STORAGE + + Where uploads go and what happens to them on the way. The routes + in routes/media.js are HTTP around this; the rules are here. + + ── Where ── + UPLOADS_DIR, default ./uploads (next to dev.db when run from + server/). Production sets /var/lib/ngu/uploads, beside the + database and outside /srv/ngu-api, so a deploy's rsync never + deletes anyone's photos. Every file is served at + /uploads/: by nginx in production, by the API in + development (see index.js). + + ── What ── + The type is read from the file's first bytes, never from its + name or the browser's Content-Type, both of which the uploader + controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything + else is refused. + + ── Processing ── + By default a raster image is turned upright (EXIF orientation), + shrunk to fit MAX_EDGE on its longest side, and saved as WebP, + which also drops its metadata, camera location included. + `keepOriginal` stores the bytes exactly as uploaded instead, + under the tighter KEEP_MAX_BYTES. An SVG is always kept as it + is: it's already small, and rasterising it would lose the point + of it. + + Names are random, so two uploads of "logo.png" can't collide + and a filename says nothing about what's in it. + ═══════════════════════════════════════════════════════════════ */ + +import { randomBytes } from "node:crypto"; +import { mkdir, rename, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import sharp from "sharp"; + +export const UPLOADS_DIR = path.resolve(process.env.UPLOADS_DIR ?? "./uploads"); + +/* The public path an image field stores. media.ts passes anything + starting with "/" through untouched. */ +export const PUBLIC_PREFIX = "/uploads/"; + +const MB = 1024 * 1024; + +/* The largest file accepted at all, before processing: room for a + full-size phone photo. */ +export const MAX_UPLOAD_BYTES = 25 * MB; + +/* The largest file kept as uploaded, unprocessed. */ +export const KEEP_MAX_BYTES = 10 * MB; + +/* Longest side after processing, in pixels. Wide enough for a + full-bleed hero on a large screen. */ +const MAX_EDGE = 2400; + +const WEBP_QUALITY = 82; + +export class MediaError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +/* ── Sniffing ──────────────────────────────────────────────── */ + +const TYPES = { + jpeg: { mime: "image/jpeg", ext: ".jpg" }, + png: { mime: "image/png", ext: ".png" }, + gif: { mime: "image/gif", ext: ".gif" }, + webp: { mime: "image/webp", ext: ".webp" }, + svg: { mime: "image/svg+xml", ext: ".svg" }, +}; + +function startsWith(buf, bytes, offset = 0) { + return bytes.every((byte, i) => buf[offset + i] === byte); +} + +function sniff(buf) { + if (startsWith(buf, [0xff, 0xd8, 0xff])) return "jpeg"; + if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png"; + if (startsWith(buf, [0x47, 0x49, 0x46, 0x38])) return "gif"; + if (startsWith(buf, [0x52, 0x49, 0x46, 0x46]) && startsWith(buf, [0x57, 0x45, 0x42, 0x50], 8)) { + return "webp"; + } + + // SVG is text: an optional BOM, XML declaration, comments or a + // doctype, then an element. Look at the head only. + const head = buf.subarray(0, 1024).toString("utf8").replace(/^/, "").trimStart(); + if (/^(<\?xml[\s\S]*?\?>\s*)?(\s*|]*>\s*)*]/i.test(head)) { + return "svg"; + } + + return null; +} + +/* ── Store ───────────────────────────────────────────────────── + Writes the file and returns what the media row needs. The row + itself is the caller's, so a failed insert can call remove() + and leave nothing behind. + ───────────────────────────────────────────────────────────── */ + +export async function store(buf, { keepOriginal = false } = {}) { + if (buf.length === 0) throw new MediaError(400, "The file is empty."); + if (buf.length > MAX_UPLOAD_BYTES) { + throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`); + } + + const kind = sniff(buf); + if (!kind) { + throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded."); + } + + const convert = kind !== "svg" && !keepOriginal; + + if (!convert && buf.length > KEEP_MAX_BYTES) { + throw new MediaError( + 413, + `Files kept as uploaded can be at most ${KEEP_MAX_BYTES / MB} MB. ` + + "Leave the original unticked to have it shrunk instead.", + ); + } + + let out = buf; + let type = TYPES[kind]; + let width = null; + let height = null; + + try { + if (convert) { + // animated keeps every frame of a GIF or an animated WebP. + const { data, info } = await sharp(buf, { animated: true }) + .rotate() + .resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true }) + .webp({ quality: WEBP_QUALITY }) + .toBuffer({ resolveWithObject: true }); + out = data; + type = TYPES.webp; + width = info.width; + // An animated image reports the whole strip's height. + height = info.pageHeight ?? info.height; + } else if (kind !== "svg") { + const meta = await sharp(buf).metadata(); + width = meta.width ?? null; + height = meta.pageHeight ?? meta.height ?? null; + } + } catch { + throw new MediaError(415, "That image couldn't be read. It may be damaged."); + } + + const filename = `${randomBytes(12).toString("hex")}${type.ext}`; + + await mkdir(UPLOADS_DIR, { recursive: true }); + // Written under a temporary name and renamed, so a half-written + // file is never served under its real one. + const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`); + await writeFile(tmp, out); + await rename(tmp, path.join(UPLOADS_DIR, filename)); + + return { + filename, + content_type: type.mime, + bytes: out.length, + width, + height, + processed: convert ? 1 : 0, + }; +} + +/* Deletes one stored file. A file that's already gone is not an + error: the row is what's being removed. */ +export async function remove(filename) { + // filename comes from our own table, but it's joined onto a + // directory, so refuse anything that isn't a bare name. + if (path.basename(filename) !== filename) return; + try { + await unlink(path.join(UPLOADS_DIR, filename)); + } catch (err) { + if (err.code !== "ENOENT") throw err; + } +} diff --git a/server/src/migrations/028_media.sql b/server/src/migrations/028_media.sql new file mode 100644 index 0000000..09ca066 --- /dev/null +++ b/server/src/migrations/028_media.sql @@ -0,0 +1,41 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 028 MEDIA: UPLOADED IMAGES +-- +-- One row per file in UPLOADS_DIR (/var/lib/ngu/uploads in +-- production, outside the deployed app so an rsync can't touch +-- it). nginx serves the directory at /uploads/; the API only +-- writes and deletes. +-- +-- An image field stores the file's public path, '/uploads/', +-- not this row's id. That keeps every image column a plain TEXT +-- that also takes a filename in public/ or a full URL, as before, +-- and means media.ts needs no lookup. The cost is no foreign key: +-- deleting a file a record still names leaves that record showing +-- nothing (the and fallbacks already handle a missing +-- file), so the Media page warns before a delete. +-- +-- filename the stored name: random, so it can't collide or +-- be guessed from the original. '3f9c…e1.webp' +-- original_name what the uploader's file was called, for the +-- library's search and display +-- processed 1 when resized and converted to WebP, 0 when +-- kept as uploaded +-- width, height null for an SVG, which has no pixel size +-- +-- PRAGMA user_version; -- reads 27 before this file +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE media ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL UNIQUE, + original_name TEXT NOT NULL, + content_type TEXT NOT NULL, + bytes INTEGER NOT NULL CHECK (bytes >= 0), + width INTEGER, + height INTEGER, + processed INTEGER NOT NULL DEFAULT 1 CHECK (processed IN (0, 1)), + uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +) STRICT; + +CREATE INDEX media_created_idx ON media (created_at DESC); diff --git a/server/src/migrations/029_event_card_image.sql b/server/src/migrations/029_event_card_image.sql new file mode 100644 index 0000000..82cac9a --- /dev/null +++ b/server/src/migrations/029_event_card_image.sql @@ -0,0 +1,15 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 029 EVENTS: CARD BACKGROUND IMAGE +-- +-- A photo behind an event's card. The card keeps its size and its +-- layout; the image covers it, under a light veil (CARD_IMAGE_VEIL +-- in EventList-Cards.tsx) so the text on top stays readable. +-- +-- Like every image column, it holds a path: '/uploads/' from +-- the media library, a bare filename in public/event-backgrounds/, +-- or a full URL. Null draws the card as before. +-- +-- PRAGMA user_version; -- reads 28 before this file +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE events ADD COLUMN card_image TEXT; diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 7c827dd..1e56055 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -148,6 +148,7 @@ function shapeEvent(row, links, cardBlocks, hosts = []) { event_logo: row.event_logo, color: row.effective_color, gradient: row.gradient, + card_image: row.card_image, hosts: hosts.map(shapeHost), diff --git a/server/src/routes/media.js b/server/src/routes/media.js new file mode 100644 index 0000000..a0df5fa --- /dev/null +++ b/server/src/routes/media.js @@ -0,0 +1,181 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA ROUTES: mounted under /api/admin + + GET /media the library, newest first, ?q=name + POST /media upload one image (multipart: file, + keep_original) + GET /media/:id/uses which records name this file + DELETE /media/:id remove the row and the file + + Reading needs a session, uploading needs editor, deleting needs + admin: the same ladder the entity routes use, so an editor can + add images to what they edit but not take one out from under + somebody else's page. + + Mounted before the entity routes, whose /:entity would otherwise + claim /media and answer "Unknown entity." + ═══════════════════════════════════════════════════════════════ */ + +import { Hono } from "hono"; +import { bodyLimit } from "hono/body-limit"; + +import { requireAuth, requireRole } from "../auth.js"; +import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js"; + +const media = new Hono(); + +media.use("*", requireAuth); + +const NO_STORE = { "Cache-Control": "no-store" }; + +const MAX_LIST = 500; + +/* Tables that can't hold an image path, or mustn't be searched. */ +const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]); + +function shape(row) { + return { + id: row.id, + url: `${PUBLIC_PREFIX}${row.filename}`, + original_name: row.original_name, + content_type: row.content_type, + bytes: row.bytes, + width: row.width, + height: row.height, + processed: row.processed === 1, + uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null, + created_at: row.created_at, + }; +} + +const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email + FROM media m + LEFT JOIN admin_users u ON u.id = m.uploaded_by`; + +media.get("/media", (c) => { + const q = (c.req.query("q") ?? "").trim().slice(0, 100); + const rows = c + .get("db") + .prepare( + `${SELECT} + ${q ? "WHERE m.original_name LIKE ?" : ""} + ORDER BY m.created_at DESC, m.id DESC + LIMIT ${MAX_LIST}`, + ) + .all(...(q ? [`%${q}%`] : [])); + return c.json({ media: rows.map(shape) }, 200, NO_STORE); +}); + +media.post( + "/media", + requireRole("editor"), + // A little over the file limit, for the multipart framing. + bodyLimit({ + maxSize: MAX_UPLOAD_BYTES + 64 * 1024, + onError: (c) => c.json({ error: "That file is too large." }, 413), + }), + async (c) => { + const db = c.get("db"); + const user = c.get("user"); + + let body; + try { + body = await c.req.parseBody(); + } catch { + return c.json({ error: "Expected a file upload." }, 400); + } + + const file = body.file; + if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400); + + const stored = await store(Buffer.from(await file.arrayBuffer()), { + keepOriginal: body.keep_original === "1", + }); + + let row; + try { + const { lastInsertRowid } = db + .prepare( + `INSERT INTO media + (filename, original_name, content_type, bytes, width, height, processed, uploaded_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + stored.filename, + (file.name || "upload").slice(0, 200), + stored.content_type, + stored.bytes, + stored.width, + stored.height, + stored.processed, + user.id, + ); + row = db.prepare(`${SELECT} WHERE m.id = ?`).get(lastInsertRowid); + } catch (err) { + await remove(stored.filename); + throw err; + } + + console.log(`media ${stored.filename} uploaded by ${user.email}`); + return c.json({ media: shape(row) }, 201, NO_STORE); + }, +); + +/* Every TEXT column of every content table, searched for the exact + path. Read from the live schema rather than a list of image + columns, so a new image field is covered the day it's added. */ +function usesOf(db, url) { + const tables = db + .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) + .all() + .map((t) => t.name) + .filter((name) => !NOT_CONTENT.has(name)); + + const uses = []; + for (const table of tables) { + const columns = db + .prepare(`SELECT name, type FROM pragma_table_info(?)`) + .all(table) + .filter((col) => col.type.toUpperCase() === "TEXT") + .map((col) => col.name); + if (columns.length === 0) continue; + + // Names come from the schema, not the request; quoted anyway. + const where = columns.map((col) => `"${col}" = ?`).join(" OR "); + const { n } = db + .prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`) + .get(...columns.map(() => url)); + if (n > 0) uses.push({ table, count: n }); + } + return uses; +} + +function findOr404(c) { + const id = Number(c.req.param("id")); + const row = Number.isInteger(id) + ? c.get("db").prepare(`SELECT * FROM media WHERE id = ?`).get(id) + : null; + if (!row) throw new MediaError(404, "No such file."); + return row; +} + +media.get("/media/:id/uses", (c) => { + const row = findOr404(c); + return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE); +}); + +media.delete("/media/:id", requireRole("admin"), async (c) => { + const row = findOr404(c); + c.get("db").prepare(`DELETE FROM media WHERE id = ?`).run(row.id); + await remove(row.filename); + console.log(`media ${row.filename} deleted by ${c.get("user").email}`); + return c.body(null, 204); +}); + +media.onError((err, c) => { + if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE); + console.error(err); + return c.json({ error: "Something went wrong." }, 500); +}); + +export default media; diff --git a/src/App.tsx b/src/App.tsx index c72c0f2..8a8df02 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -32,6 +32,7 @@ import AdminLogin from "./pages/admin/AdminLogin.tsx"; import AdminPanel from "./pages/admin/AdminPanel.tsx"; import AdminHome from "./pages/admin/AdminHome.tsx"; import AdminFeedback from "./pages/admin/AdminFeedback.tsx"; +import AdminMedia from "./pages/admin/AdminMedia.tsx"; import EntityList from "./pages/admin/EntityList.tsx"; import EntityEdit from "./pages/admin/EntityEdit.tsx"; @@ -80,6 +81,7 @@ export default function App() { } /> } /> + } /> } /> } /> diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx new file mode 100644 index 0000000..8bb3b55 --- /dev/null +++ b/src/components/admin/MediaLibrary.tsx @@ -0,0 +1,407 @@ +/* ═══════════════════════════════════════════════════════════════ + MEDIA LIBRARY + + Everything the admin does with uploaded images, in one file: + + ImageInput the `widget: "image"` form field. A preview, the + stored value as editable text, and buttons to + upload a new file or pick an earlier one. + MediaPicker the dialog behind "Choose from library". + MediaGrid the thumbnails both the picker and the Media page + (pages/admin/AdminMedia.tsx) draw. + UploadButton a file input dressed as a button, with the + "keep original" choice beside it. + + An image field stores a path, not a media id: '/uploads/' + for an upload, or, as before, a bare filename in the field's + public/ directory or a full URL. So the text box stays: old + values keep working, and a URL from elsewhere can be pasted in. + `resolve` on the field (a media.ts helper) turns a bare filename + into something the preview can load. + + Uploading is editor and up; the server says the same. Reads use + ttl: 0 because two people uploading at once is exactly when a + cached list would lie. + ═══════════════════════════════════════════════════════════════ */ + +import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; + +import { ApiError, get, upload } from "../../lib/api.ts"; +import { useAuth } from "../../lib/auth.tsx"; +import { canWrite as roleCanWrite } from "../../lib/roles.ts"; + +export type MediaItem = { + id: number; + url: string; + original_name: string; + content_type: string; + bytes: number; + width: number | null; + height: number | null; + processed: boolean; + uploaded_by: string | null; + created_at: string; +}; + +const button = + "rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] " + + "transition-colors hover:bg-[#eef9fb] disabled:cursor-default disabled:opacity-50"; + +/* A light checkerboard, so a white logo on a transparent background + is still visible in its thumbnail. */ +const CHECKER = { + backgroundColor: "#fff", + backgroundImage: + "linear-gradient(45deg,#e6eef0 25%,transparent 25%),linear-gradient(-45deg,#e6eef0 25%,transparent 25%)," + + "linear-gradient(45deg,transparent 75%,#e6eef0 75%),linear-gradient(-45deg,transparent 75%,#e6eef0 75%)", + backgroundSize: "12px 12px", + backgroundPosition: "0 0,0 6px,6px -6px,-6px 0", +}; + +export function formatBytes(bytes: number) { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +export function mediaSize(item: MediaItem) { + const dims = item.width && item.height ? `${item.width} × ${item.height}, ` : ""; + return `${dims}${formatBytes(item.bytes)}`; +} + +/* ── Data ────────────────────────────────────────────────────── */ + +export function uploadImage(file: File, keepOriginal: boolean): Promise { + const form = new FormData(); + form.append("file", file); + if (keepOriginal) form.append("keep_original", "1"); + return upload("/admin/media", form).then((data) => data.media); +} + +export function useMediaLibrary(query: string) { + const [items, setItems] = useState(null); + const [error, setError] = useState(null); + + const reload = useCallback(() => { + const q = query.trim(); + setError(null); + get(`/admin/media${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) + .then((data) => setItems(data.media)) + .catch((err) => + setError(err instanceof ApiError ? err.message : "Couldn't load the library."), + ); + }, [query]); + + useEffect(reload, [reload]); + + return { items, error, reload, setItems }; +} + +/* ── Upload button ───────────────────────────────────────────── */ + +export function UploadButton({ + onUploaded, + multiple = false, + label = "Upload", +}: { + onUploaded: (item: MediaItem) => void; + multiple?: boolean; + label?: string; +}) { + const inputRef = useRef(null); + const keepId = useId(); + const [keepOriginal, setKeepOriginal] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function send(files: FileList | null) { + if (!files || files.length === 0) return; + setBusy(true); + setError(null); + try { + // One at a time: each is up to 25 MB, and a failure should + // name the file it happened to. + for (const file of Array.from(files)) { + try { + onUploaded(await uploadImage(file, keepOriginal)); + } catch (err) { + const why = err instanceof ApiError ? err.message : "Upload failed."; + setError(files.length > 1 ? `${file.name}: ${why}` : why); + break; + } + } + } finally { + setBusy(false); + if (inputRef.current) inputRef.current.value = ""; + } + } + + return ( +
+
+ + send(e.target.files)} + /> + +
+ {error &&

{error}

} +
+ ); +} + +export const UPLOAD_HELP = + "Photos are shrunk to 2400px and saved as WebP, which also removes their location data. " + + "Keep original stores the file exactly as it is (up to 10 MB). SVGs are always kept as they are."; + +/* ── Grid ────────────────────────────────────────────────────── */ + +export function MediaGrid({ + items, + selected, + onPick, + renderActions, +}: { + items: MediaItem[]; + selected?: string | null; + onPick?: (item: MediaItem) => void; + renderActions?: (item: MediaItem) => ReactNode; +}) { + if (items.length === 0) { + return

Nothing here yet.

; + } + + return ( +
    + {items.map((item) => { + const isSelected = selected === item.url; + const thumb = ( + <> +
    + +
    +

    + {item.original_name} +

    +

    {mediaSize(item)}

    + + ); + + return ( +
  • + {onPick ? ( + + ) : ( + thumb + )} + {renderActions &&
    {renderActions(item)}
    } +
  • + ); + })} +
+ ); +} + +/* ── Picker dialog ───────────────────────────────────────────── */ + +export function MediaPicker({ + selected, + onPick, + onClose, +}: { + selected?: string | null; + onPick: (item: MediaItem) => void; + onClose: () => void; +}) { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, error, setItems } = useMediaLibrary(query); + const dialogRef = useRef(null); + + // showModal gives focus trapping, Escape and the backdrop for free. + useEffect(() => { + dialogRef.current?.showModal(); + }, []); + + return ( + { + // A click on the backdrop lands on the dialog itself. + if (e.target === dialogRef.current) dialogRef.current?.close(); + }} + className="w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" + > +
+
+

Choose an image

+ setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-56 rounded-lg border border-[#4a6b72]/25 px-3 py-1.5 text-sm outline-none focus:border-[#138ba0]" + /> + +
+ + {roleCanWrite(user) && ( +
+ { + setItems((current) => [item, ...(current ?? [])]); + onPick(item); + dialogRef.current?.close(); + }} + /> +

{UPLOAD_HELP}

+
+ )} + +
+ {error ? ( +

{error}

+ ) : items === null ? ( +

Loading…

+ ) : ( + { + onPick(item); + dialogRef.current?.close(); + }} + /> + )} +
+
+
+ ); +} + +/* ── The form field ──────────────────────────────────────────── */ + +export function ImageInput({ + id, + value, + resolve, + locked, + className, + onChange, +}: { + id: string; + value: string | null | undefined; + resolve?: (file?: string | null) => string | null; + locked: boolean; + className: string; + onChange: (value: string) => void; +}) { + const { user } = useAuth(); + const [picking, setPicking] = useState(false); + const [broken, setBroken] = useState(false); + + const src = value ? (resolve ? resolve(value) : value) : null; + useEffect(() => setBroken(false), [src]); + + const editable = !locked && roleCanWrite(user); + + return ( +
+
+ {src && !broken ? ( + setBroken(true)} /> + ) : ( + + {src ? "Not found" : "No image"} + + )} +
+ +
+ onChange(e.target.value)} + className={className} + /> + {editable && ( +
+ onChange(item.url)} /> + + {value && ( + + )} +
+ )} +
+ + {picking && ( + onChange(item.url)} + onClose={() => setPicking(false)} + /> + )} +
+ ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index d202c53..8f395d7 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -18,6 +18,11 @@ that column in the server's admin-schema.js or the row will be saved as real input. + `widget: "image"` is a text box with a preview and upload and + library buttons beside it (ImageInput in MediaLibrary.tsx). Its + `resolve` option is the media.ts helper for the field's public/ + directory, so a bare filename previews from the right place. + Two options change the box itself rather than what goes in it: prefix fixed text inside the box, left of the cursor. The @@ -34,6 +39,8 @@ import { useRef, useState } from "react"; +import { ImageInput } from "./MediaLibrary.tsx"; + const input = "w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " + "outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25"; @@ -168,6 +175,15 @@ export function Field({ field, value, row, options, error, onChange }: any) { className={locked ? inputLocked : common.className} /> + ) : widget === "image" ? ( + ) : field.prefix && !locked ? ( // The span is not a form control, so it can't be typed // into, tabbed to, or selected by dragging through the diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index c5a794b..2be582b 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -17,6 +17,16 @@ import { preview } from "./text.ts"; import { PLATFORMS } from "./platforms.ts"; +import { + awardLogo, + blockMedia, + eventBackground, + eventLogo, + heroPhoto, + orgLogo, + personPhoto, + teamLogo, +} from "./media.ts"; const PLACE_FIELDS = [ { path: "venue", label: "Venue" }, @@ -228,7 +238,7 @@ const blocksChild = { ], }, { path: "text", label: "Text", widget: "textarea", full: true }, - { path: "media", label: "Media", help: "Filename or URL" }, + { path: "media", label: "Media", widget: "image", resolve: blockMedia, full: true }, { path: "href", label: "Link" }, ], children: [ @@ -288,7 +298,7 @@ const organizations = { { path: "short_name", label: "Short name" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: orgLogo, full: true }, ], }, { @@ -495,10 +505,18 @@ const events = { { legend: "Appearance", fields: [ - { path: "event_logo", label: "Event logo", help: "Filename in /event-logos/" }, - { path: "org_logo", label: "Org logo override" }, + { path: "event_logo", label: "Event logo", widget: "image", resolve: eventLogo, full: true }, + { path: "org_logo", label: "Org logo override", widget: "image", resolve: orgLogo, full: true }, { path: "color", label: "Colour", widget: "color" }, { path: "gradient", label: "Gradient", full: true }, + { + path: "card_image", + label: "Card background", + widget: "image", + resolve: eventBackground, + full: true, + help: "A photo behind the event's card, faded so the text stays readable.", + }, ], }, timelineGroup("event"), @@ -577,7 +595,7 @@ const people = { { path: "sort_name", label: "Sort name", help: "Doe, Jane" }, { path: "pronouns", label: "Pronouns" }, { path: "tagline", label: "Tagline", full: true }, - { path: "photo", label: "Photo", help: "Filename in /people/" }, + { path: "photo", label: "Photo", widget: "image", resolve: personPhoto, full: true }, { path: "primary_org_id", label: "Home organization", @@ -738,7 +756,7 @@ const teams = { { path: "name", label: "Name", required: true, help: "Board, Leadership Team" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", help: "Filename in /org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: teamLogo, full: true }, ], }, { legend: "Publishing", fields: PUBLISH_FIELDS }, @@ -814,7 +832,7 @@ const awards = { }, { path: "name", label: "Name", required: true }, { path: "description", label: "Description", widget: "textarea", full: true }, - { path: "logo", label: "Logo", help: "Filename in public/org-logos/" }, + { path: "logo", label: "Logo", widget: "image", resolve: awardLogo, full: true }, ], }, { @@ -1151,7 +1169,7 @@ const frontPage = { title: (row) => row.caption || row.media || "New photo", blank: { media: "", alt: "", caption: "" }, fields: [ - { path: "media", label: "Photo", required: true, help: "Filename in /front-page/, or a URL" }, + { path: "media", label: "Photo", required: true, widget: "image", resolve: heroPhoto, full: true }, { path: "alt", label: "Description", help: "For screen readers" }, { path: "caption", label: "Caption", full: true }, { path: "link_url", label: "Link", help: "Optional; makes the caption a link" }, diff --git a/src/lib/api.ts b/src/lib/api.ts index 9086e2f..5eeca0a 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -115,3 +115,9 @@ export function patch(path, data) { export function del(path) { return request(path, { method: "DELETE" }); } + +/* A multipart body. No Content-Type here: the browser sets it, + boundary included, from the FormData itself. */ +export function upload(path, form: FormData) { + return request(path, { method: "POST", body: form }); +} diff --git a/src/lib/media.ts b/src/lib/media.ts index 0234c91..df238c8 100644 --- a/src/lib/media.ts +++ b/src/lib/media.ts @@ -17,6 +17,10 @@ const ABSOLUTE = /^(https?:|\/|data:)/ +/* An uploaded file ('/uploads/…'), a path anywhere on the site, or + a full URL: something to use as it is rather than resolve. */ +export const isAbsoluteMedia = (file?: string | null) => Boolean(file && ABSOLUTE.test(file)) + function inDir(dir: string) { return (file?: string | null): string | null => { if (!file) return null @@ -27,6 +31,7 @@ function inDir(dir: string) { export const personPhoto = inDir('/people') // confirmed export const eventLogo = inDir('/event-logos') // confirmed +export const eventBackground = inDir('/event-backgrounds') export const orgLogo = inDir('/org-logos') // ⚠ guess export const teamLogo = inDir('/team-logos') // ⚠ guess export const awardLogo = inDir('/award-logos') // ⚠ guess diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index 86feaa1..7a6972d 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -101,6 +101,8 @@ export type EventRecord = { event_logo?: string | null color?: string | null gradient?: string | null + /** Behind the card. See 029_event_card_image.sql. */ + card_image?: string | null /* In billing order. The first is the one `color` and `org_logo` fell back to when the event set neither. */ hosts: EventHost[] diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx new file mode 100644 index 0000000..379a185 --- /dev/null +++ b/src/pages/admin/AdminMedia.tsx @@ -0,0 +1,193 @@ +/* ═══════════════════════════════════════════════════════════════ + ADMIN: MEDIA + + The uploaded-image library: search it, add to it, copy a file's + path, delete what nothing needs. Image fields in the editors + upload and pick from the same library (MediaLibrary.tsx), so this + page is for housekeeping rather than the way images get in. + + Two ranks, as on the server: editors and up upload, admins and + up delete. A delete first asks the server which records still + name the file, since nothing stops one being removed from under + a page (an image field stores the path, not a foreign key). + ═══════════════════════════════════════════════════════════════ */ + +import { useState } from "react"; + +import { ApiError, del, get } from "../../lib/api.ts"; +import { useAuth } from "../../lib/auth.tsx"; +import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; +import { + MediaGrid, + UPLOAD_HELP, + UploadButton, + useMediaLibrary, + type MediaItem, +} from "../../components/admin/MediaLibrary.tsx"; + +type Use = { table: string; count: number }; + +function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) { + const [uses, setUses] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function ask() { + setBusy(true); + setError(null); + try { + const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 }); + setUses(data.uses); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't check where it's used."); + } finally { + setBusy(false); + } + } + + async function remove() { + setBusy(true); + setError(null); + try { + await del(`/admin/media/${item.id}`); + onDeleted(); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't delete that."); + setBusy(false); + } + } + + if (uses === null) { + return ( + <> + + {error &&

{error}

} + + ); + } + + return ( +
+ {uses.length > 0 ? ( +

+ Still used by{" "} + {uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those + will show no image. +

+ ) : ( +

Nothing uses this file.

+ )} +
+ + +
+ {error &&

{error}

} +
+ ); +} + +function CopyPath({ url }: { url: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} + +export default function AdminMedia() { + const { user } = useAuth(); + const [query, setQuery] = useState(""); + const { items, error, setItems } = useMediaLibrary(query); + + return ( +
+
+

Media

+

+ Uploaded images. Image fields in every editor pick from here. +

+
+ +
+ {roleCanWrite(user) && ( +
+ setItems((current) => [item, ...(current ?? [])])} + /> +

{UPLOAD_HELP}

+
+ )} + setQuery(e.target.value)} + placeholder="Search by file name" + className="ml-auto w-64 rounded-lg border border-[#4a6b72]/25 px-3 py-2 text-sm outline-none focus:border-[#138ba0]" + /> +
+ +
+ {error ? ( +

{error}

+ ) : items === null ? ( +

Loading…

+ ) : ( + ( +
+ + + Open + + {canDelete(user) && ( +
+ + setItems((current) => (current ?? []).filter((m) => m.id !== item.id)) + } + /> +
+ )} +
+ )} + /> + )} +
+
+ ); +} diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index 0748c6c..b907f54 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -70,6 +70,13 @@ export const CMS_NAV = [ label: "Front page", blurb: "The hero, its photos or livestream, and which bands the home page draws.", }, + // Not an entity: the uploaded-image library every image field + // picks from. Its own page, AdminMedia.tsx. + { + to: "/admin/media", + label: "Media", + blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.", + }, ]; /* Forms are submissions coming in rather than content going out, so diff --git a/src/pages/sections/EventList-Cards.tsx b/src/pages/sections/EventList-Cards.tsx index 2a7f3e6..238ab43 100644 --- a/src/pages/sections/EventList-Cards.tsx +++ b/src/pages/sections/EventList-Cards.tsx @@ -5,6 +5,7 @@ import { eventHref } from "../../lib/hrefs.ts"; import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts"; import { seriesLabel } from "../../lib/eventSeries.ts"; import PlatformIcon from "../../components/PlatformIcon.tsx"; +import { eventBackground, isAbsoluteMedia } from "../../lib/media.ts"; /* ═══════════════════════════════════════════════════════════════ EVENT LIST — CARDS @@ -35,7 +36,9 @@ const LOGOS = Object.fromEntries( Object.entries(LOGO_FILES).map(([path, src]) => [path.split("/").pop(), src]) ); -const logoSrc = file => (file && LOGOS[file]) || null; +/* A bundled logo by filename, or an upload or URL as it is. */ +const logoSrc = file => + (file && LOGOS[file]) || (isAbsoluteMedia(file) ? file : null); /* Last resort only. The API already falls back to the host organization's logo when an event doesn't name its own, so this @@ -60,6 +63,25 @@ function Logo({ file, alt = "", className }) { const TEAL = "#138ba0"; // last-resort card color const CARD_BG = "#ffffff"; // sits under every card, gradient or not +/* Laid over a card's background image so black text reads on any + photo. Heavier at the top, where the title and dates are, and + lighter lower down so more of the picture shows through. */ +const CARD_IMAGE_VEIL = + "linear-gradient(to bottom, rgba(255,255,255,0.9), rgba(255,255,255,0.78))"; + +/* The card's background layers, top first: its gradient if it has + one, then the veil and photo if it has one, then white. */ +function cardBackground(ev) { + const layers: string[] = []; + if (ev.gradient) layers.push(ev.gradient); + const image = eventBackground(ev.card_image); + if (image) { + layers.push(CARD_IMAGE_VEIL, `url(${JSON.stringify(image)}) center / cover no-repeat`); + } + layers.push(CARD_BG); + return layers.join(", "); +} + /* ── Grid view ──────────────────────────────────────────────── The grid fits as many columns as the screen allows, with no breakpoints: each card is at least CARD_MIN wide, and the @@ -185,7 +207,7 @@ export function Card({ }`} style={{ border: `1px solid ${color}`, - background: ev.gradient ? `${ev.gradient}, ${CARD_BG}` : CARD_BG, + background: cardBackground(ev), filter: past ? "saturate(0.75)" : "none", pointerEvents: interactive ? "auto" : "none", }} diff --git a/src/pages/sections/OrgList-Card.tsx b/src/pages/sections/OrgList-Card.tsx index 7d13ccf..86901b9 100644 --- a/src/pages/sections/OrgList-Card.tsx +++ b/src/pages/sections/OrgList-Card.tsx @@ -1,5 +1,6 @@ import { useState } from "react"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import { initialsFor, orgPath, @@ -21,8 +22,6 @@ import { array — only the short card description. ═══════════════════════════════════════════════════════════════ */ -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const INK = "#2c4a50"; const FALLBACK_COLOR = "#4a6b72"; @@ -39,7 +38,7 @@ function OrgMark({ org, color }) { if (org.logo && !failed) { return ( setFailed(true)} className="h-14 w-14 object-contain rounded-xl shrink-0" diff --git a/src/pages/sections/OrgList-Map.tsx b/src/pages/sections/OrgList-Map.tsx index 2eb06c8..eec121c 100644 --- a/src/pages/sections/OrgList-Map.tsx +++ b/src/pages/sections/OrgList-Map.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { useCommunity } from "../../data/chapters.ts"; import { Link } from "react-router-dom"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import { initialsFor, orgPath } from "../../data/organizations.ts"; import { AREAS, AREA_NAMES } from "../../data/mapGrid.ts"; @@ -39,8 +40,6 @@ const ROWS = 7; // stays at max-w-6xl, so this deliberately breaks out past it. const CONTENT_MAX = "88rem"; -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const RULE = "#cfe3e7"; const INK = "#2c4a50"; @@ -472,7 +471,7 @@ function OrgLogo({ org, color, size = "h-14 w-14" }) { if (org.logo && !failed) { return ( {org.name} setFailed(true)} className={`${size} object-contain rounded-xl shrink-0`} diff --git a/src/pages/sections/OrgList-Vertical.tsx b/src/pages/sections/OrgList-Vertical.tsx index 5f3f0f3..f35113d 100644 --- a/src/pages/sections/OrgList-Vertical.tsx +++ b/src/pages/sections/OrgList-Vertical.tsx @@ -1,5 +1,6 @@ import { useId, useState } from "react"; import ArrowLink from "../../components/ArrowLink.tsx"; +import { orgLogo } from "../../lib/media.ts"; import PlatformIcon from "../../components/PlatformIcon.tsx"; import { areasSentence, @@ -36,8 +37,6 @@ import { a partner row simply doesn't have them. ═══════════════════════════════════════════════════════════════ */ -const LOGO_BASE = "/org-logos/"; - const MUTED = "#7a9299"; const RULE = "#cfe3e7"; const INK = "#2c4a50"; @@ -66,7 +65,7 @@ function OrgMark({ org, color }) { if (org.logo && !failed) { return ( setFailed(true)} className="h-8 w-8 object-contain shrink-0" diff --git a/vite.config.ts b/vite.config.ts index cdace2e..c514c7f 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -24,6 +24,12 @@ export default defineConfig({ changeOrigin: false, xfwd: true, }, + // Uploaded images. nginx serves these in production; in dev + // the API does, so they go to the same place as /api. + "/uploads": { + target: "http://127.0.0.1:5173", + changeOrigin: false, + }, }, }, build: {