Add image uploads with a media library, and event card backgrounds

Uploads (migration 028, server/src/media.js, routes/media.js): editors
and up upload JPEG, PNG, GIF, WebP or SVG. Photos are resized to 2400px
and saved as WebP by default, or kept as uploaded on request. Files
live in UPLOADS_DIR, served by nginx in production and by the API in
dev. Admins and up delete, after seeing what still uses the file.

Every image field in the editor is now an image widget: preview, the
path as text, Upload and Choose from library. A new Media page lists
the library. Org lists and event cards now resolve logos through
media.ts, so uploaded paths work there.

Events get a card_image (migration 029): a photo behind the card under
a light veil so the text stays readable. The card's size is unchanged.

Setup for production is in docs/media-uploads.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 15:04:45 -05:00
parent cd393e4ab2
commit eaff23839f
26 changed files with 1234 additions and 22 deletions

7
.gitignore vendored
View file

@ -18,4 +18,9 @@ build/
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
.DS_Store .DS_Store
Thumbs.db Thumbs.db
# plain txt files
.txt
# uploaded media (local dev)
server/uploads/

View file

@ -18,7 +18,7 @@ Frontend (repo root):
- `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) - `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script)
- There is no test suite. - 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 dev`: run with `node --watch`
- `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `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 - `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` - 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. - 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. - 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 ## Git workflow
- Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`.

71
docs/media-uploads.md Normal file
View file

@ -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/<file>`. 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 <ngu-api user>: /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.

View file

@ -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 **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) | | 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) | | 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, The rule of thumb from `CLAUDE.md`: data belongs in the database,
presentation belongs in code. A dropdown's *values* are data the presentation belongs in code. A dropdown's *values* are data the

View file

@ -13,6 +13,7 @@
}, },
"dependencies": { "dependencies": {
"@hono/node-server": "^1.0.0", "@hono/node-server": "^1.0.0",
"hono": "^4.0.0" "hono": "^4.0.0",
"sharp": "^0.35.4"
} }
} }

View file

@ -345,6 +345,7 @@ const events = {
text("event_logo"), text("event_logo"),
text("color"), text("color"),
text("gradient"), text("gradient"),
text("card_image"),
bool("is_published"), bool("is_published"),
bool("is_listed"), bool("is_listed"),
bool("in_timeline"), bool("in_timeline"),

View file

@ -8,7 +8,10 @@
there too. there too.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server"; import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono"; import { Hono } from "hono";
import { logger } from "hono/logger"; import { logger } from "hono/logger";
@ -24,6 +27,8 @@ import auth from "./routes/auth.js";
import admin from "./routes/admin.js"; import admin from "./routes/admin.js";
import panel from "./routes/panel.js"; import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.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 { startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { ENTITIES } from "./admin-schema.js"; import { ENTITIES } from "./admin-schema.js";
@ -39,6 +44,8 @@ const version = migrate(db);
syncDescriptorsWithSchema(db, ENTITIES); syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
/* ── App ─────────────────────────────────────────────────────── */ /* ── 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/admin/panel", panel);
app.route("/api/auth", auth); app.route("/api/auth", auth);
app.route("/api/admin", admin); app.route("/api/admin", admin);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", adminEntities); 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); startSessionSweeper(db);
app.notFound((c) => c.json({ error: "Not found" }, 404)); app.notFound((c) => c.json({ error: "Not found" }, 404));

184
server/src/media.js Normal file
View file

@ -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/<filename>: 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 <svg> element. Look at the head only.
const head = buf.subarray(0, 1024).toString("utf8").replace(/^/, "").trimStart();
if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\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;
}
}

View file

@ -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/<file>',
-- 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 <Logo> and <img> 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);

View file

@ -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/<file>' 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;

View file

@ -148,6 +148,7 @@ function shapeEvent(row, links, cardBlocks, hosts = []) {
event_logo: row.event_logo, event_logo: row.event_logo,
color: row.effective_color, color: row.effective_color,
gradient: row.gradient, gradient: row.gradient,
card_image: row.card_image,
hosts: hosts.map(shapeHost), hosts: hosts.map(shapeHost),

181
server/src/routes/media.js Normal file
View file

@ -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;

View file

@ -32,6 +32,7 @@ import AdminLogin from "./pages/admin/AdminLogin.tsx";
import AdminPanel from "./pages/admin/AdminPanel.tsx"; import AdminPanel from "./pages/admin/AdminPanel.tsx";
import AdminHome from "./pages/admin/AdminHome.tsx"; import AdminHome from "./pages/admin/AdminHome.tsx";
import AdminFeedback from "./pages/admin/AdminFeedback.tsx"; import AdminFeedback from "./pages/admin/AdminFeedback.tsx";
import AdminMedia from "./pages/admin/AdminMedia.tsx";
import EntityList from "./pages/admin/EntityList.tsx"; import EntityList from "./pages/admin/EntityList.tsx";
import EntityEdit from "./pages/admin/EntityEdit.tsx"; import EntityEdit from "./pages/admin/EntityEdit.tsx";
@ -80,6 +81,7 @@ export default function App() {
<Route path="panel" element={<AdminPanel />} /> <Route path="panel" element={<AdminPanel />} />
</Route> </Route>
<Route path="feedback" element={<AdminFeedback />} /> <Route path="feedback" element={<AdminFeedback />} />
<Route path="media" element={<AdminMedia />} />
<Route path=":entity" element={<EntityList />} /> <Route path=":entity" element={<EntityList />} />
<Route path=":entity/:id" element={<EntityEdit />} /> <Route path=":entity/:id" element={<EntityEdit />} />
</Route> </Route>

View file

@ -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/<file>'
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<MediaItem> {
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<MediaItem[] | null>(null);
const [error, setError] = useState<string | null>(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<HTMLInputElement>(null);
const keepId = useId();
const [keepOriginal, setKeepOriginal] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 (
<div>
<div className="flex flex-wrap items-center gap-3">
<button
type="button"
className={button}
disabled={busy}
onClick={() => inputRef.current?.click()}
>
{busy ? "Uploading…" : label}
</button>
<input
ref={inputRef}
type="file"
accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
multiple={multiple}
className="hidden"
onChange={(e) => send(e.target.files)}
/>
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-[#4a6b72]">
<input
id={keepId}
type="checkbox"
checked={keepOriginal}
onChange={(e) => setKeepOriginal(e.target.checked)}
className="h-3.5 w-3.5 rounded border-[#4a6b72]/40 text-[#138ba0]"
/>
Keep original
</label>
</div>
{error && <p className="mt-1 text-xs text-[#b3261e]">{error}</p>}
</div>
);
}
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 <p className="text-sm text-[#4a6b72]">Nothing here yet.</p>;
}
return (
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{items.map((item) => {
const isSelected = selected === item.url;
const thumb = (
<>
<div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}>
<img
src={item.url}
alt=""
loading="lazy"
className="h-full w-full object-contain"
/>
</div>
<p className="mt-1.5 truncate text-xs font-medium text-[#26454c]" title={item.original_name}>
{item.original_name}
</p>
<p className="text-xs text-[#4a6b72]/80">{mediaSize(item)}</p>
</>
);
return (
<li
key={item.id}
className={`rounded-xl border bg-white p-2 ${
isSelected ? "border-[#138ba0] ring-2 ring-[#138ba0]/30" : "border-[#4a6b72]/20"
}`}
>
{onPick ? (
<button
type="button"
onClick={() => onPick(item)}
className="block w-full text-left"
aria-pressed={isSelected}
>
{thumb}
</button>
) : (
thumb
)}
{renderActions && <div className="mt-2">{renderActions(item)}</div>}
</li>
);
})}
</ul>
);
}
/* ── 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<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free.
useEffect(() => {
dialogRef.current?.showModal();
}, []);
return (
<dialog
ref={dialogRef}
onClose={onClose}
onClick={(e) => {
// 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"
>
<div className="flex max-h-[85vh] flex-col">
<div className="flex flex-wrap items-center gap-3 border-b border-[#138ba0]/15 px-5 py-4">
<h2 className="text-lg font-semibold text-[#138ba0]">Choose an image</h2>
<input
type="search"
value={query}
onChange={(e) => 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]"
/>
<button
type="button"
onClick={() => dialogRef.current?.close()}
aria-label="Close"
className="h-8 w-8 rounded-full text-[#4a6b72] hover:bg-[#eef9fb]"
>
✕
</button>
</div>
{roleCanWrite(user) && (
<div className="border-b border-[#138ba0]/10 px-5 py-3">
<UploadButton
label="Upload new"
onUploaded={(item) => {
setItems((current) => [item, ...(current ?? [])]);
onPick(item);
dialogRef.current?.close();
}}
/>
<p className="mt-1 text-xs text-[#4a6b72]">{UPLOAD_HELP}</p>
</div>
)}
<div className="overflow-y-auto px-5 py-4">
{error ? (
<p className="text-sm text-[#b3261e]">{error}</p>
) : items === null ? (
<p className="text-sm text-[#4a6b72]">Loading…</p>
) : (
<MediaGrid
items={items}
selected={selected}
onPick={(item) => {
onPick(item);
dialogRef.current?.close();
}}
/>
)}
</div>
</div>
</dialog>
);
}
/* ── 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 (
<div className="flex gap-3">
<div
className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-[#4a6b72]/20"
style={CHECKER}
>
{src && !broken ? (
<img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} />
) : (
<span className="px-1 text-center text-[10px] text-[#4a6b72]/70">
{src ? "Not found" : "No image"}
</span>
)}
</div>
<div className="min-w-0 flex-1 space-y-2">
<input
id={id}
type="text"
value={value ?? ""}
readOnly={locked}
onChange={(e) => onChange(e.target.value)}
className={className}
/>
{editable && (
<div className="flex flex-wrap items-start gap-2">
<UploadButton onUploaded={(item) => onChange(item.url)} />
<button type="button" className={button} onClick={() => setPicking(true)}>
Choose from library
</button>
{value && (
<button
type="button"
onClick={() => onChange("")}
className="px-2 py-1 text-sm text-[#4a6b72] hover:text-[#b3261e]"
>
Clear
</button>
)}
</div>
)}
</div>
{picking && (
<MediaPicker
selected={value}
onPick={(item) => onChange(item.url)}
onClose={() => setPicking(false)}
/>
)}
</div>
);
}

View file

@ -18,6 +18,11 @@
that column in the server's admin-schema.js or the row will be that column in the server's admin-schema.js or the row will be
saved as real input. 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: Two options change the box itself rather than what goes in it:
prefix fixed text inside the box, left of the cursor. The prefix fixed text inside the box, left of the cursor. The
@ -34,6 +39,8 @@
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { ImageInput } from "./MediaLibrary.tsx";
const input = const input =
"w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-2 text-sm text-[#26454c] " + "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"; "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} className={locked ? inputLocked : common.className}
/> />
</div> </div>
) : widget === "image" ? (
<ImageInput
id={id}
value={value}
resolve={field.resolve}
locked={locked}
className={locked ? inputLocked : common.className}
onChange={onChange}
/>
) : field.prefix && !locked ? ( ) : field.prefix && !locked ? (
// The span is not a form control, so it can't be typed // The span is not a form control, so it can't be typed
// into, tabbed to, or selected by dragging through the // into, tabbed to, or selected by dragging through the

View file

@ -17,6 +17,16 @@
import { preview } from "./text.ts"; import { preview } from "./text.ts";
import { PLATFORMS } from "./platforms.ts"; import { PLATFORMS } from "./platforms.ts";
import {
awardLogo,
blockMedia,
eventBackground,
eventLogo,
heroPhoto,
orgLogo,
personPhoto,
teamLogo,
} from "./media.ts";
const PLACE_FIELDS = [ const PLACE_FIELDS = [
{ path: "venue", label: "Venue" }, { path: "venue", label: "Venue" },
@ -228,7 +238,7 @@ const blocksChild = {
], ],
}, },
{ path: "text", label: "Text", widget: "textarea", full: true }, { 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" }, { path: "href", label: "Link" },
], ],
children: [ children: [
@ -288,7 +298,7 @@ const organizations = {
{ path: "short_name", label: "Short name" }, { path: "short_name", label: "Short name" },
{ path: "tagline", label: "Tagline", full: true }, { path: "tagline", label: "Tagline", full: true },
{ path: "color", label: "Colour", widget: "color" }, { 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", legend: "Appearance",
fields: [ fields: [
{ path: "event_logo", label: "Event logo", help: "Filename in /event-logos/" }, { path: "event_logo", label: "Event logo", widget: "image", resolve: eventLogo, full: true },
{ path: "org_logo", label: "Org logo override" }, { path: "org_logo", label: "Org logo override", widget: "image", resolve: orgLogo, full: true },
{ path: "color", label: "Colour", widget: "color" }, { path: "color", label: "Colour", widget: "color" },
{ path: "gradient", label: "Gradient", full: true }, { 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"), timelineGroup("event"),
@ -577,7 +595,7 @@ const people = {
{ path: "sort_name", label: "Sort name", help: "Doe, Jane" }, { path: "sort_name", label: "Sort name", help: "Doe, Jane" },
{ path: "pronouns", label: "Pronouns" }, { path: "pronouns", label: "Pronouns" },
{ path: "tagline", label: "Tagline", full: true }, { 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", path: "primary_org_id",
label: "Home organization", label: "Home organization",
@ -738,7 +756,7 @@ const teams = {
{ path: "name", label: "Name", required: true, help: "Board, Leadership Team" }, { path: "name", label: "Name", required: true, help: "Board, Leadership Team" },
{ path: "tagline", label: "Tagline", full: true }, { path: "tagline", label: "Tagline", full: true },
{ path: "color", label: "Colour", widget: "color" }, { 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 }, { legend: "Publishing", fields: PUBLISH_FIELDS },
@ -814,7 +832,7 @@ const awards = {
}, },
{ path: "name", label: "Name", required: true }, { path: "name", label: "Name", required: true },
{ path: "description", label: "Description", widget: "textarea", full: 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", title: (row) => row.caption || row.media || "New photo",
blank: { media: "", alt: "", caption: "" }, blank: { media: "", alt: "", caption: "" },
fields: [ 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: "alt", label: "Description", help: "For screen readers" },
{ path: "caption", label: "Caption", full: true }, { path: "caption", label: "Caption", full: true },
{ path: "link_url", label: "Link", help: "Optional; makes the caption a link" }, { path: "link_url", label: "Link", help: "Optional; makes the caption a link" },

View file

@ -115,3 +115,9 @@ export function patch(path, data) {
export function del(path) { export function del(path) {
return request(path, { method: "DELETE" }); 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 });
}

View file

@ -17,6 +17,10 @@
const ABSOLUTE = /^(https?:|\/|data:)/ 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) { function inDir(dir: string) {
return (file?: string | null): string | null => { return (file?: string | null): string | null => {
if (!file) return null if (!file) return null
@ -27,6 +31,7 @@ function inDir(dir: string) {
export const personPhoto = inDir('/people') // confirmed export const personPhoto = inDir('/people') // confirmed
export const eventLogo = inDir('/event-logos') // confirmed export const eventLogo = inDir('/event-logos') // confirmed
export const eventBackground = inDir('/event-backgrounds')
export const orgLogo = inDir('/org-logos') // ⚠ guess export const orgLogo = inDir('/org-logos') // ⚠ guess
export const teamLogo = inDir('/team-logos') // ⚠ guess export const teamLogo = inDir('/team-logos') // ⚠ guess
export const awardLogo = inDir('/award-logos') // ⚠ guess export const awardLogo = inDir('/award-logos') // ⚠ guess

View file

@ -101,6 +101,8 @@ export type EventRecord = {
event_logo?: string | null event_logo?: string | null
color?: string | null color?: string | null
gradient?: 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` /* In billing order. The first is the one `color` and `org_logo`
fell back to when the event set neither. */ fell back to when the event set neither. */
hosts: EventHost[] hosts: EventHost[]

View file

@ -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<Use[] | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 (
<>
<button
type="button"
onClick={ask}
disabled={busy}
className="text-xs text-[#4a6b72] hover:text-[#b3261e]"
>
Delete
</button>
{error && <p className="mt-1 text-xs text-[#b3261e]">{error}</p>}
</>
);
}
return (
<div className="rounded-lg bg-[#fdf3f2] p-2 text-xs text-[#26454c]">
{uses.length > 0 ? (
<p>
Still used by{" "}
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those
will show no image.
</p>
) : (
<p>Nothing uses this file.</p>
)}
<div className="mt-2 flex gap-3">
<button
type="button"
onClick={remove}
disabled={busy}
className="font-medium text-[#b3261e] hover:underline"
>
{busy ? "Deleting…" : "Delete for good"}
</button>
<button type="button" onClick={() => setUses(null)} className="text-[#4a6b72] hover:underline">
Cancel
</button>
</div>
{error && <p className="mt-1 text-[#b3261e]">{error}</p>}
</div>
);
}
function CopyPath({ url }: { url: string }) {
const [copied, setCopied] = useState(false);
return (
<button
type="button"
onClick={() => {
navigator.clipboard?.writeText(url).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
}}
className="text-xs text-[#138ba0] hover:underline"
>
{copied ? "Copied" : "Copy path"}
</button>
);
}
export default function AdminMedia() {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query);
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-[#138ba0]">Media</h1>
<p className="text-sm text-[#4a6b72]">
Uploaded images. Image fields in every editor pick from here.
</p>
</div>
<div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && (
<div className="max-w-md">
<UploadButton
multiple
label="Upload images"
onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])}
/>
<p className="mt-1 text-xs text-[#4a6b72]">{UPLOAD_HELP}</p>
</div>
)}
<input
type="search"
value={query}
onChange={(e) => 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]"
/>
</div>
<div className="mt-6">
{error ? (
<p className="text-sm text-[#b3261e]">{error}</p>
) : items === null ? (
<p className="text-sm text-[#4a6b72]">Loading…</p>
) : (
<MediaGrid
items={items}
renderActions={(item) => (
<div className="flex flex-wrap items-start gap-x-3 gap-y-1">
<CopyPath url={item.url} />
<a
href={item.url}
target="_blank"
rel="noreferrer"
className="text-xs text-[#138ba0] hover:underline"
>
Open
</a>
{canDelete(user) && (
<div className="w-full">
<DeleteControl
item={item}
onDeleted={() =>
setItems((current) => (current ?? []).filter((m) => m.id !== item.id))
}
/>
</div>
)}
</div>
)}
/>
)}
</div>
</div>
);
}

View file

@ -70,6 +70,13 @@ export const CMS_NAV = [
label: "Front page", label: "Front page",
blurb: "The hero, its photos or livestream, and which bands the home page draws.", 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 /* Forms are submissions coming in rather than content going out, so

View file

@ -5,6 +5,7 @@ import { eventHref } from "../../lib/hrefs.ts";
import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts"; import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts";
import { seriesLabel } from "../../lib/eventSeries.ts"; import { seriesLabel } from "../../lib/eventSeries.ts";
import PlatformIcon from "../../components/PlatformIcon.tsx"; import PlatformIcon from "../../components/PlatformIcon.tsx";
import { eventBackground, isAbsoluteMedia } from "../../lib/media.ts";
/* ═══════════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════════
EVENT LIST — CARDS EVENT LIST — CARDS
@ -35,7 +36,9 @@ const LOGOS = Object.fromEntries(
Object.entries(LOGO_FILES).map(([path, src]) => [path.split("/").pop(), src]) 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 /* Last resort only. The API already falls back to the host
organization's logo when an event doesn't name its own, so this 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 TEAL = "#138ba0"; // last-resort card color
const CARD_BG = "#ffffff"; // sits under every card, gradient or not 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 ──────────────────────────────────────────────── /* ── Grid view ────────────────────────────────────────────────
The grid fits as many columns as the screen allows, with no The grid fits as many columns as the screen allows, with no
breakpoints: each card is at least CARD_MIN wide, and the breakpoints: each card is at least CARD_MIN wide, and the
@ -185,7 +207,7 @@ export function Card({
}`} }`}
style={{ style={{
border: `1px solid ${color}`, border: `1px solid ${color}`,
background: ev.gradient ? `${ev.gradient}, ${CARD_BG}` : CARD_BG, background: cardBackground(ev),
filter: past ? "saturate(0.75)" : "none", filter: past ? "saturate(0.75)" : "none",
pointerEvents: interactive ? "auto" : "none", pointerEvents: interactive ? "auto" : "none",
}} }}

View file

@ -1,5 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import ArrowLink from "../../components/ArrowLink.tsx"; import ArrowLink from "../../components/ArrowLink.tsx";
import { orgLogo } from "../../lib/media.ts";
import { import {
initialsFor, initialsFor,
orgPath, orgPath,
@ -21,8 +22,6 @@ import {
array — only the short card description. array — only the short card description.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
const LOGO_BASE = "/org-logos/";
const MUTED = "#7a9299"; const MUTED = "#7a9299";
const INK = "#2c4a50"; const INK = "#2c4a50";
const FALLBACK_COLOR = "#4a6b72"; const FALLBACK_COLOR = "#4a6b72";
@ -39,7 +38,7 @@ function OrgMark({ org, color }) {
if (org.logo && !failed) { if (org.logo && !failed) {
return ( return (
<img <img
src={`${LOGO_BASE}${org.logo}`} src={orgLogo(org.logo) ?? undefined}
alt="" alt=""
onError={() => setFailed(true)} onError={() => setFailed(true)}
className="h-14 w-14 object-contain rounded-xl shrink-0" className="h-14 w-14 object-contain rounded-xl shrink-0"

View file

@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { useCommunity } from "../../data/chapters.ts"; import { useCommunity } from "../../data/chapters.ts";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import ArrowLink from "../../components/ArrowLink.tsx"; import ArrowLink from "../../components/ArrowLink.tsx";
import { orgLogo } from "../../lib/media.ts";
import { initialsFor, orgPath } from "../../data/organizations.ts"; import { initialsFor, orgPath } from "../../data/organizations.ts";
import { AREAS, AREA_NAMES } from "../../data/mapGrid.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. // stays at max-w-6xl, so this deliberately breaks out past it.
const CONTENT_MAX = "88rem"; const CONTENT_MAX = "88rem";
const LOGO_BASE = "/org-logos/";
const MUTED = "#7a9299"; const MUTED = "#7a9299";
const RULE = "#cfe3e7"; const RULE = "#cfe3e7";
const INK = "#2c4a50"; const INK = "#2c4a50";
@ -472,7 +471,7 @@ function OrgLogo({ org, color, size = "h-14 w-14" }) {
if (org.logo && !failed) { if (org.logo && !failed) {
return ( return (
<img <img
src={`${LOGO_BASE}${org.logo}`} src={orgLogo(org.logo) ?? undefined}
alt={org.name} alt={org.name}
onError={() => setFailed(true)} onError={() => setFailed(true)}
className={`${size} object-contain rounded-xl shrink-0`} className={`${size} object-contain rounded-xl shrink-0`}

View file

@ -1,5 +1,6 @@
import { useId, useState } from "react"; import { useId, useState } from "react";
import ArrowLink from "../../components/ArrowLink.tsx"; import ArrowLink from "../../components/ArrowLink.tsx";
import { orgLogo } from "../../lib/media.ts";
import PlatformIcon from "../../components/PlatformIcon.tsx"; import PlatformIcon from "../../components/PlatformIcon.tsx";
import { import {
areasSentence, areasSentence,
@ -36,8 +37,6 @@ import {
a partner row simply doesn't have them. a partner row simply doesn't have them.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
const LOGO_BASE = "/org-logos/";
const MUTED = "#7a9299"; const MUTED = "#7a9299";
const RULE = "#cfe3e7"; const RULE = "#cfe3e7";
const INK = "#2c4a50"; const INK = "#2c4a50";
@ -66,7 +65,7 @@ function OrgMark({ org, color }) {
if (org.logo && !failed) { if (org.logo && !failed) {
return ( return (
<img <img
src={`${LOGO_BASE}${org.logo}`} src={orgLogo(org.logo) ?? undefined}
alt="" alt=""
onError={() => setFailed(true)} onError={() => setFailed(true)}
className="h-8 w-8 object-contain shrink-0" className="h-8 w-8 object-contain shrink-0"

View file

@ -24,6 +24,12 @@ export default defineConfig({
changeOrigin: false, changeOrigin: false,
xfwd: true, 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: { build: {