Compare commits

...

4 commits

Author SHA1 Message Date
Zaldimmar
eaff23839f 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>
2026-09-27 15:04:45 -05:00
Zaldimmar
cd393e4ab2 Add a Listed flag: published records reachable only by their link
is_listed (migration 027) sits beside is_published on organizations,
events, people, teams and awards. Unticked, the record's own page
still works, but the site's lists leave it out: the list routes, a
region's chapters, an organization's events, teams and awards, the
QR page's directory, and the front page's counts and countdown.
Places where someone attached it by hand (rosters, hosts, billed
people, recipients, timeline, a pinned countdown) still show it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:50:41 -05:00
Zaldimmar
3c02eb8971 Show platform icons on link buttons
Links pick their platform from a preset dropdown (PLATFORMS in
src/lib/platforms.ts), and every link button draws that platform's
icon beside its label. The footer and event cards now share the same
PlatformIcon component instead of their own copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:45:20 -05:00
Zaldimmar
99c3a87c87 Add a Tools block to the admin home with the QR code generator
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:42:12 -05:00
37 changed files with 1548 additions and 128 deletions

5
.gitignore vendored
View file

@ -19,3 +19,8 @@ build/
!.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
@ -171,6 +172,7 @@ also in `admin-schema.js` and a CHECK):
| Events → People → Role | speaker, leader, facilitator, host, musician, volunteer, attendee | no | `ROLE_LABEL` in `src/pages/EventDetail.tsx` | | Events → People → Role | speaker, leader, facilitator, host, musician, volunteer, attendee | no | `ROLE_LABEL` in `src/pages/EventDetail.tsx` |
| People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` | | People → Affiliations → Role; Teams → Members → Role | lead, board, staff, volunteer, member | no | `ROLE_LABEL` in `src/pages/PersonDetail.tsx` |
| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` | | Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` |
| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. |
| Content blocks → Slot | card, body | no | `ContentBlocks.tsx` | | Content blocks → Slot | card, body | no | `ContentBlocks.tsx` |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) | | Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider | no | `ContentBlocks.tsx` (one renderer per type) |
| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` | | Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` |
@ -181,7 +183,7 @@ also in `admin-schema.js` and a CHECK):
| Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` | | Front page → Feature | none, livestream, video | **yes** | `HeroStage.tsx` |
| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) | | Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) |
| Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) |
| Every list → Published / Featured filter | 1, 0 | **yes** | n/a | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
"No, shows values" means the dropdown currently shows the raw value, "No, shows values" means the dropdown currently shows the raw value,
so relabelling it is just [adding labels](#renaming-what-a-dropdown-shows). so relabelling it is just [adding labels](#renaming-what-a-dropdown-shows).

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

@ -217,10 +217,11 @@ const organizations = {
"locality", "locality",
"state_code", "state_code",
"is_published", "is_published",
"is_listed",
"sort_order", "sort_order",
"updated_at", "updated_at",
], ],
filters: ["kind", "is_published"], filters: ["kind", "is_published", "is_listed"],
search: ["name", "id", "locality"], search: ["name", "id", "locality"],
order: "kind, sort_order, name", order: "kind, sort_order, name",
}, },
@ -236,6 +237,7 @@ const organizations = {
text("logo"), text("logo"),
...placeColumns, ...placeColumns,
bool("is_published"), bool("is_published"),
bool("is_listed"),
int("sort_order"), int("sort_order"),
bool("in_timeline"), bool("in_timeline"),
], ],
@ -305,12 +307,13 @@ const events = {
"starts_on", "starts_on",
"status", "status",
"is_published", "is_published",
"is_listed",
"updated_at", "updated_at",
], ],
// No host filter: hosts are rows in another table now, and the // No host filter: hosts are rows in another table now, and the
// engine's filters are columns on this one. The events a host // engine's filters are columns on this one. The events a host
// owns are on that host's own page. // owns are on that host's own page.
filters: ["scope_id", "event_type", "status", "is_published"], filters: ["scope_id", "event_type", "status", "is_published", "is_listed"],
search: ["title", "id", "theme"], search: ["title", "id", "theme"],
order: "starts_on IS NULL, starts_on DESC, title", order: "starts_on IS NULL, starts_on DESC, title",
}, },
@ -342,7 +345,9 @@ 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("in_timeline"), bool("in_timeline"),
// A repeating schedule. Columns rather than a side table: the // A repeating schedule. Columns rather than a side table: the
@ -409,9 +414,10 @@ const people = {
"tagline", "tagline",
"locality", "locality",
"is_published", "is_published",
"is_listed",
"updated_at", "updated_at",
], ],
filters: ["is_published"], filters: ["is_published", "is_listed"],
search: ["display_name", "sort_name", "id"], search: ["display_name", "sort_name", "id"],
order: "sort_name, display_name", order: "sort_name, display_name",
}, },
@ -431,6 +437,7 @@ const people = {
text("country"), text("country"),
text("location_label"), text("location_label"),
bool("is_published"), bool("is_published"),
bool("is_listed"),
], ],
extensions: [ extensions: [
@ -510,8 +517,8 @@ const teams = {
concurrency: "updated_at", concurrency: "updated_at",
list: { list: {
columns: ["id", "org_id", "name", "tagline", "is_published", "sort_order", "updated_at"], columns: ["id", "org_id", "name", "tagline", "is_published", "is_listed", "sort_order", "updated_at"],
filters: ["org_id", "is_published"], filters: ["org_id", "is_published", "is_listed"],
search: ["name", "id", "tagline"], search: ["name", "id", "tagline"],
order: "org_id, sort_order, name", order: "org_id, sort_order, name",
}, },
@ -523,6 +530,7 @@ const teams = {
text("color"), text("color"),
text("logo"), text("logo"),
bool("is_published"), bool("is_published"),
bool("is_listed"),
int("sort_order"), int("sort_order"),
], ],
@ -569,8 +577,8 @@ const awards = {
idKind: "slug", idKind: "slug",
list: { list: {
columns: ["id", "org_id", "name", "description", "is_published", "sort_order"], columns: ["id", "org_id", "name", "description", "is_published", "is_listed", "sort_order"],
filters: ["org_id", "is_published"], filters: ["org_id", "is_published", "is_listed"],
search: ["name", "id", "description"], search: ["name", "id", "description"],
order: "org_id, sort_order, name", order: "org_id, sort_order, name",
}, },
@ -581,6 +589,7 @@ const awards = {
text("description"), text("description"),
text("logo"), text("logo"),
bool("is_published"), bool("is_published"),
bool("is_listed"),
int("sort_order"), int("sort_order"),
], ],
}; };

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,43 @@
-- ═══════════════════════════════════════════════════════════════
-- 027 LISTED: PUBLISHED BUT ONLY BY LINK
--
-- is_published stays the hard gate: 0 is a draft (or, for people,
-- private), off the site entirely and a 404 at its own URL.
-- is_listed only means anything on a published row. 0 keeps the
-- record's own page working but leaves it out of every list the
-- site gathers by itself:
--
-- the /events, /organizations, /teams and /awards lists (and so
-- every band, calendar, map and card grid built on them), a
-- region's chapters, an organization's events, teams and awards,
-- the /directory the QR page reads, and the front page's counts
-- and next-event countdown.
--
-- It still appears wherever someone attached it by hand: rosters,
-- billed people, hosts, award recipients, timeline entries, and a
-- countdown pinned to it by name. Each of those rows has its own
-- is_public (or is_published) to hide it there.
--
-- Defaults to 1, so every existing row stays listed.
--
-- Plain ADD COLUMN: NOT NULL with a constant default and a CHECK is
-- allowed without a rebuild, STRICT tables included. v_events reads
-- e.*, so it picks the column up with no change of its own.
--
-- PRAGMA user_version; -- reads 26 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE organizations ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE events ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE people ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE teams ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE awards ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));

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

@ -15,6 +15,11 @@
`details` rather than as separate routes — that's what lets a `details` rather than as separate routes — that's what lets a
list component be written once and pointed at any kind. list component be written once and pointed at any kind.
The lists leave out unlisted records (is_listed = 0); the
detail routes don't, since reaching one by its link is the
point. A region's chapters and an organization's events, teams
and awards are lists too. See 027_listed.sql.
Responses carry their fallbacks already resolved: an event's Responses carry their fallbacks already resolved: an event's
`color` is its own or its first host's, and `status` is derived `color` is its own or its first host's, and `status` is derived
from the dates when it isn't set. Components read one field and from the dates when it isn't set. Components read one field and
@ -143,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),
@ -266,7 +272,7 @@ function attachRegionDetails(db, orgs) {
.prepare( .prepare(
`SELECT c.region_id, o.id, o.name, o.location_label, o.logo `SELECT c.region_id, o.id, o.name, o.location_label, o.logo
FROM chapters c FROM chapters c
JOIN organizations o ON o.id = c.id AND o.is_published = 1 JOIN organizations o ON o.id = c.id AND o.is_published = 1 AND o.is_listed = 1
WHERE c.region_id IN (${marks(ids.length)}) WHERE c.region_id IN (${marks(ids.length)})
ORDER BY o.sort_order, o.name`, ORDER BY o.sort_order, o.name`,
) )
@ -377,7 +383,7 @@ function attachTeams(db, orgs) {
.prepare( .prepare(
`SELECT id, org_id, name, tagline, color, logo `SELECT id, org_id, name, tagline, color, logo
FROM teams FROM teams
WHERE org_id IN (${marks(ids.length)}) AND is_published = 1 WHERE org_id IN (${marks(ids.length)}) AND is_published = 1 AND is_listed = 1
ORDER BY sort_order, name`, ORDER BY sort_order, name`,
) )
.all(...ids); .all(...ids);
@ -412,7 +418,7 @@ function attachAwards(db, orgs) {
JOIN people p ON p.id = pa.person_id AND p.is_published = 1 JOIN people p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a FROM awards a
WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1
ORDER BY a.sort_order, a.name`, ORDER BY a.sort_order, a.name`,
) )
.all(...ids); .all(...ids);
@ -457,7 +463,7 @@ content.get("/events", (c) => {
const rows = db const rows = db
.prepare( .prepare(
`SELECT * FROM v_events `SELECT * FROM v_events
WHERE is_published = 1 WHERE is_published = 1 AND is_listed = 1
ORDER BY ${EVENT_ORDER}`, ORDER BY ${EVENT_ORDER}`,
) )
.all(); .all();
@ -538,7 +544,7 @@ content.get("/events/:id", (c) => {
/* ── Organizations ───────────────────────────────────────────── /* ── Organizations ─────────────────────────────────────────────
GET /organizations every published org GET /organizations every published, listed org
GET /organizations?kind=region one kind GET /organizations?kind=region one kind
GET /organizations?kind=region,chapter GET /organizations?kind=region,chapter
@ -565,7 +571,7 @@ content.get("/organizations", (c) => {
const rows = db const rows = db
.prepare( .prepare(
`SELECT * FROM organizations `SELECT * FROM organizations
WHERE is_published = 1 ${filter} WHERE is_published = 1 AND is_listed = 1 ${filter}
ORDER BY kind, sort_order, name`, ORDER BY kind, sort_order, name`,
) )
.all(...kinds); .all(...kinds);
@ -627,7 +633,7 @@ content.get("/organizations/:id", (c) => {
e.effective_color AS color e.effective_color AS color
FROM v_events e FROM v_events e
JOIN event_hosts eh ON eh.event_id = e.id AND eh.org_id = ? JOIN event_hosts eh ON eh.event_id = e.id AND eh.org_id = ?
WHERE e.is_published = 1 WHERE e.is_published = 1 AND e.is_listed = 1
ORDER BY ${EVENT_ORDER}`, ORDER BY ${EVENT_ORDER}`,
) )
.all(id); .all(id);
@ -637,7 +643,7 @@ content.get("/organizations/:id", (c) => {
/* ── Teams ───────────────────────────────────────────────────── /* ── Teams ─────────────────────────────────────────────────────
GET /teams every published team GET /teams every published, listed team
GET /teams?org=mid-atlantic one organization's teams GET /teams?org=mid-atlantic one organization's teams
GET /teams/:id one team's page GET /teams/:id one team's page
@ -655,7 +661,7 @@ content.get("/teams", (c) => {
`SELECT t.*, o.name AS org_name, o.kind AS org_kind `SELECT t.*, o.name AS org_name, o.kind AS org_kind
FROM teams t FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.is_published = 1 ${org ? "AND t.org_id = ?" : ""} WHERE t.is_published = 1 AND t.is_listed = 1 ${org ? "AND t.org_id = ?" : ""}
ORDER BY o.sort_order, t.sort_order, t.name`, ORDER BY o.sort_order, t.sort_order, t.name`,
) )
.all(...(org ? [org] : [])); .all(...(org ? [org] : []));
@ -720,7 +726,7 @@ content.get("/awards", (c) => {
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a FROM awards a
LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1 LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1
WHERE a.is_published = 1 ${org ? "AND a.org_id = ?" : ""} WHERE a.is_published = 1 AND a.is_listed = 1 ${org ? "AND a.org_id = ?" : ""}
ORDER BY a.sort_order, a.name`, ORDER BY a.sort_order, a.name`,
) )
.all(...(org ? [org] : [])); .all(...(org ? [org] : []));

View file

@ -19,6 +19,9 @@
awards published awards published
people published people published
and each leaves out unlisted records (is_listed = 0): the QR page
is public, and listing them here would undo the point of them.
The site already serves each of these at its own URL; this only The site already serves each of these at its own URL; this only
lists them in one place. lists them in one place.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
@ -39,32 +42,32 @@ directory.get("/directory", (c) => {
events: all( events: all(
`SELECT id, title AS name, starts_on `SELECT id, title AS name, starts_on
FROM events FROM events
WHERE is_published = 1 WHERE is_published = 1 AND is_listed = 1
ORDER BY starts_on IS NULL, starts_on DESC, title`, ORDER BY starts_on IS NULL, starts_on DESC, title`,
), ),
organizations: all( organizations: all(
`SELECT id, name, kind `SELECT id, name, kind
FROM organizations FROM organizations
WHERE is_published = 1 WHERE is_published = 1 AND is_listed = 1
ORDER BY kind, name`, ORDER BY kind, name`,
), ),
teams: all( teams: all(
`SELECT t.id, t.name, o.name AS org_name `SELECT t.id, t.name, o.name AS org_name
FROM teams t FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1 JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.is_published = 1 WHERE t.is_published = 1 AND t.is_listed = 1
ORDER BY o.name, t.sort_order, t.name`, ORDER BY o.name, t.sort_order, t.name`,
), ),
awards: all( awards: all(
`SELECT id, name `SELECT id, name
FROM awards FROM awards
WHERE is_published = 1 WHERE is_published = 1 AND is_listed = 1
ORDER BY name`, ORDER BY name`,
), ),
people: all( people: all(
`SELECT id, display_name AS name `SELECT id, display_name AS name
FROM people FROM people
WHERE is_published = 1 WHERE is_published = 1 AND is_listed = 1
ORDER BY COALESCE(sort_name, display_name)`, ORDER BY COALESCE(sort_name, display_name)`,
), ),
}, },

View file

@ -15,15 +15,17 @@
── Stats ── ── Stats ──
A stat's source picks a query from STAT_QUERIES. Each counts A stat's source picks a query from STAT_QUERIES. Each counts
exactly what the matching public page shows: published rows, and exactly what the matching public page shows: published, listed
for awards only public citations to published people. A count rows, and for awards only public citations to published people
(an award's page names its recipients whether they're listed or
not, so the count does too). A count
that disagreed with the page it summarises would be worse than that disagreed with the page it summarises would be worse than
none. 'manual' and 'years_since' read the row's own value. none. 'manual' and 'years_since' read the row's own value.
── Countdown ── ── Countdown ──
The pinned event if it is still published and not over; The pinned event if it is still published and not over, listed
otherwise the next published, non-cancelled event that hasn't or not; otherwise the next published, listed, non-cancelled
ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today, event that hasn't ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today,
so a running series with a start date in the past still counts. so a running series with a start date in the past still counts.
The client works out the next meeting of a series from `series`. The client works out the next meeting of a series from `series`.
@ -46,15 +48,15 @@ const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE });
const PAGE_ID = "home"; const PAGE_ID = "home";
const STAT_QUERIES = { const STAT_QUERIES = {
regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1`, regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`,
chapters: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'chapter' AND is_published = 1`, chapters: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'chapter' AND is_published = 1 AND is_listed = 1`,
partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1`, partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`,
events_held: `SELECT COUNT(*) AS n FROM v_events events_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND effective_status = 'past'`, WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`,
retreats_held: `SELECT COUNT(*) AS n FROM v_events retreats_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND effective_status = 'past' WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'
AND event_type = 'retreat'`, AND event_type = 'retreat'`,
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1`, people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1 JOIN people p ON p.id = pa.person_id AND p.is_published = 1
@ -166,7 +168,7 @@ home.get("/front-page", (c) => {
db db
.prepare( .prepare(
`SELECT * FROM v_events `SELECT * FROM v_events
WHERE ${notOver} ${filters.join(" ")} WHERE ${notOver} AND is_listed = 1 ${filters.join(" ")}
ORDER BY starts_on, title ORDER BY starts_on, title
LIMIT 1`, LIMIT 1`,
) )

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

@ -1,38 +1,12 @@
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts";
import nguLogo from "../assets/NGU_Logo.svg"; import nguLogo from "../assets/NGU_Logo.svg";
import PlatformIcon from "./PlatformIcon.tsx";
const InstagramIcon = ({ id = "ig-gradient" }) => (
<svg viewBox="0 0 24 24" className="w-6 h-6 ig-icon" style={{ "--ig-fill": `url(#${id})` }}>
<defs>
<linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#FEDA75" />
<stop offset="25%" stopColor="#FA7E1E" />
<stop offset="50%" stopColor="#D62976" />
<stop offset="75%" stopColor="#962FBF" />
<stop offset="100%" stopColor="#4F5BD5" />
</linearGradient>
</defs>
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
</svg>
);
const FacebookIcon = () => (
<svg viewBox="0 0 24 24" className="w-6 h-6 fb-icon" fill="currentColor">
<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
</svg>
);
const DiscordIcon = () => (
<svg viewBox="0 0 24 24" className="w-6 h-6 ds-icon" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057c.001.022.015.04.033.05a19.81 19.81 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
</svg>
);
const Social_Links = [ const Social_Links = [
{ label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", Icon: InstagramIcon }, { label: "Instagram", href: "https://www.instagram.com/nextgenerationunity/", platform: "instagram" },
{ label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", Icon: FacebookIcon }, { label: "Facebook", href: "https://www.facebook.com/NextGenerationofUnity", platform: "facebook" },
{ label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", Icon: DiscordIcon }, { label: "Discord", href: "https://discord.com/invite/AtngzpqaX5", platform: "discord" },
]; ];
// Give's destination lives in navConfig so the footer and the nav can't drift. // Give's destination lives in navConfig so the footer and the nav can't drift.
@ -147,7 +121,7 @@ export default function Footer() {
{/* Socials + get in touch */} {/* Socials + get in touch */}
<div className="md:col-span-3 flex flex-col items-center md:items-start"> <div className="md:col-span-3 flex flex-col items-center md:items-start">
<div className="flex gap-4 mb-8"> <div className="flex gap-4 mb-8">
{Social_Links.map(({ label, href, Icon }) => ( {Social_Links.map(({ label, href, platform }) => (
<a <a
key={label} key={label}
href={href} href={href}
@ -157,7 +131,7 @@ export default function Footer() {
className="footer-icons w-10 h-10 rounded-full flex items-center justify-center text-white/70 transition-colors" className="footer-icons w-10 h-10 rounded-full flex items-center justify-center text-white/70 transition-colors"
style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.15)" }} style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.15)" }}
> >
{label === "Instagram" ? <InstagramIcon id="ig-footer" /> : <Icon />} <PlatformIcon platform={platform} className="w-6 h-6" />
</a> </a>
))} ))}
</div> </div>

View file

@ -0,0 +1,98 @@
import { useId } from 'react'
import type { Platform } from '../lib/platforms.ts'
/* ═══════════════════════════════════════════════════════════════
PLATFORM ICON
The brand mark for a link's platform (links.platform), drawn in
currentColor so it takes the colour of the button it sits in.
Anything that isn't one of PLATFORMS in lib/platforms.ts, blank
included, draws nothing, so a caller can always pass the field
straight through.
Paths are Simple Icons (CC0), except Instagram, Facebook and
Discord, which came over from the footer unchanged.
Instagram is the odd one: its hover fill is a gradient, which
has to be an SVG <linearGradient> with an id. useId keeps that
id unique however many cards draw one. The hover itself is CSS
(.ig-icon in index.css), which only switches the fill inside an
.ig-link or .footer-icons parent; the Facebook and Discord
hovers are there too.
═══════════════════════════════════════════════════════════════ */
const PATHS: Record<Exclude<Platform, 'instagram'>, string> = {
facebook:
'M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z',
discord:
'M20.317 4.37a19.791 19.791 0 00-4.885-1.515.074.074 0 00-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 00-5.487 0 12.64 12.64 0 00-.617-1.25.077.077 0 00-.079-.037A19.736 19.736 0 003.677 4.37a.07.07 0 00-.032.027C.533 9.046-.32 13.58.099 18.057c.001.022.015.04.033.05a19.81 19.81 0 005.993 3.03.078.078 0 00.084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 00-.041-.106 13.107 13.107 0 01-1.872-.892.077.077 0 01-.008-.128 10.2 10.2 0 00.372-.292.074.074 0 01.077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 01.078.01c.12.098.246.198.373.292a.077.077 0 01-.006.127 12.299 12.299 0 01-1.873.892.077.077 0 00-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 00.084.028 19.839 19.839 0 006.002-3.03.077.077 0 00.032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 00-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z',
youtube:
'M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z',
tiktok:
'M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z',
x: 'M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z',
substack:
'M22.539 8.242H1.46V5.406h21.08v2.836zM1.46 10.812V24L12 18.11 22.54 24V10.812H1.46zM22.54 0H1.46v2.836h21.08V0z',
spotify:
'M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z',
linkedin:
'M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z',
}
/* Hover classes the footer's CSS already keys on. */
const HOVER_CLASS: Partial<Record<Platform, string>> = {
facebook: 'fb-icon',
discord: 'ds-icon',
}
const INSTAGRAM_PATH =
'M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z'
function InstagramIcon({ className }: { className: string }) {
// useId's output has characters an SVG url() reference won't take.
const id = `ig-${useId().replace(/[^a-zA-Z0-9-]/g, '')}`
return (
<svg
viewBox="0 0 24 24"
aria-hidden="true"
className={`ig-icon shrink-0 ${className}`}
style={{ '--ig-fill': `url(#${id})` }}
>
<defs>
<linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#FEDA75" />
<stop offset="25%" stopColor="#FA7E1E" />
<stop offset="50%" stopColor="#D62976" />
<stop offset="75%" stopColor="#962FBF" />
<stop offset="100%" stopColor="#4F5BD5" />
</linearGradient>
</defs>
<path d={INSTAGRAM_PATH} />
</svg>
)
}
export default function PlatformIcon({
platform,
className = 'h-4 w-4',
}: {
platform?: string | null
className?: string
}) {
if (platform === 'instagram') return <InstagramIcon className={className} />
const path = platform ? PATHS[platform as keyof typeof PATHS] : undefined
if (!path) return null
return (
<svg
viewBox="0 0 24 24"
aria-hidden="true"
fill="currentColor"
className={`shrink-0 ${HOVER_CLASS[platform as Platform] ?? ''} ${className}`}
>
<path d={path} />
</svg>
)
}

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

@ -16,6 +16,17 @@
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { preview } from "./text.ts"; 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 = [ const PLACE_FIELDS = [
{ path: "venue", label: "Venue" }, { path: "venue", label: "Venue" },
@ -31,10 +42,21 @@ const PLACE_FIELDS = [
const PUBLISHED_FIELD = { path: "is_published", label: "Published", widget: "checkbox" }; const PUBLISHED_FIELD = { path: "is_published", label: "Published", widget: "checkbox" };
/* Only means anything on a published record. Unticked, its own page
still works but the site's lists, counts and the QR page leave it
out. See 027_listed.sql for exactly which. */
const LISTED_FIELD = {
path: "is_listed",
label: "Listed",
widget: "checkbox",
help: "Unticked: only reachable by its link",
};
/* For entities whose lists the site orders by hand. Events sort by /* For entities whose lists the site orders by hand. Events sort by
date and people by sort_name, so they take PUBLISHED_FIELD alone. */ date and people by sort_name, so they take the first two alone. */
const PUBLISH_FIELDS = [ const PUBLISH_FIELDS = [
PUBLISHED_FIELD, PUBLISHED_FIELD,
LISTED_FIELD,
{ path: "sort_order", label: "Sort order", widget: "number" }, { path: "sort_order", label: "Sort order", widget: "number" },
]; ];
@ -140,7 +162,14 @@ const linksChild = {
widget: "select", widget: "select",
options: ["action", "social", "website", "email"], options: ["action", "social", "website", "email"],
}, },
{ path: "platform", label: "Platform", help: "instagram, discord…" }, {
path: "platform",
label: "Platform",
widget: "select",
options: PLATFORMS.map((platform) => [platform.id, platform.label]),
blankLabel: "Default: no icon",
help: "Shows the platform's icon on the button.",
},
{ path: "label", label: "Label", required: true }, { path: "label", label: "Label", required: true },
{ path: "url", label: "URL", required: true, full: true }, { path: "url", label: "URL", required: true, full: true },
{ path: "is_primary", label: "Primary", widget: "checkbox" }, { path: "is_primary", label: "Primary", widget: "checkbox" },
@ -209,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: [
@ -244,10 +273,12 @@ const organizations = {
{ key: "locality", label: "City" }, { key: "locality", label: "City" },
{ key: "state_code", label: "State" }, { key: "state_code", label: "State" },
{ key: "is_published", label: "Live", widget: "bool" }, { key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
], ],
filters: [ filters: [
{ key: "kind", label: "Kind", options: ["national", "region", "chapter", "partner"] }, { key: "kind", label: "Kind", options: ["national", "region", "chapter", "partner"] },
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
], ],
}, },
@ -267,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 },
], ],
}, },
{ {
@ -404,6 +435,7 @@ const events = {
{ key: "date_label", label: "Dates" }, { key: "date_label", label: "Dates" },
{ key: "status", label: "Status" }, { key: "status", label: "Status" },
{ key: "is_published", label: "Live", widget: "bool" }, { key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
], ],
filters: [ filters: [
{ key: "scope_id", label: "Scope", optionsFrom: "event_scopes" }, { key: "scope_id", label: "Scope", optionsFrom: "event_scopes" },
@ -414,6 +446,7 @@ const events = {
}, },
{ key: "status", label: "Status", options: ["upcoming", "past", "cancelled"] }, { key: "status", label: "Status", options: ["upcoming", "past", "cancelled"] },
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
], ],
}, },
@ -472,15 +505,23 @@ 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"),
timelineDetailGroup("event"), timelineDetailGroup("event"),
{ legend: "Publishing", fields: [PUBLISHED_FIELD] }, { legend: "Publishing", fields: [PUBLISHED_FIELD, LISTED_FIELD] },
], ],
children: [ children: [
@ -538,9 +579,11 @@ const people = {
{ key: "tagline", label: "Tagline" }, { key: "tagline", label: "Tagline" },
{ key: "locality", label: "City" }, { key: "locality", label: "City" },
{ key: "is_published", label: "Live", widget: "bool" }, { key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
], ],
filters: [ filters: [
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
], ],
}, },
@ -552,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",
@ -595,7 +638,7 @@ const people = {
{ {
legend: "Publishing", legend: "Publishing",
note: "Unpublished people are invisible everywhere.", note: "Unpublished people are invisible everywhere.",
fields: [PUBLISHED_FIELD], fields: [PUBLISHED_FIELD, LISTED_FIELD],
}, },
], ],
@ -686,10 +729,12 @@ const teams = {
{ key: "org_id", label: "Organization" }, { key: "org_id", label: "Organization" },
{ key: "tagline", label: "Tagline" }, { key: "tagline", label: "Tagline" },
{ key: "is_published", label: "Live", widget: "bool" }, { key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
], ],
filters: [ filters: [
{ key: "org_id", label: "Organization", optionsFrom: "organizations" }, { key: "org_id", label: "Organization", optionsFrom: "organizations" },
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
], ],
}, },
@ -711,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 },
@ -761,10 +806,12 @@ const awards = {
{ key: "org_id", label: "Awarded by" }, { key: "org_id", label: "Awarded by" },
{ key: "description", label: "Description" }, { key: "description", label: "Description" },
{ key: "is_published", label: "Live", widget: "bool" }, { key: "is_published", label: "Live", widget: "bool" },
{ key: "is_listed", label: "Listed", widget: "bool" },
], ],
filters: [ filters: [
{ key: "org_id", label: "Awarded by", optionsFrom: "organizations" }, { key: "org_id", label: "Awarded by", optionsFrom: "organizations" },
{ key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] },
{ key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] },
], ],
}, },
@ -785,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 },
], ],
}, },
{ {
@ -1122,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

29
src/lib/platforms.ts Normal file
View file

@ -0,0 +1,29 @@
/* ═══════════════════════════════════════════════════════════════
LINK PLATFORMS
The preset values for links.platform. Order here is the order
the admin's Platform dropdown lists them in.
links.platform is a plain TEXT column with no CHECK: a platform
carries nothing but an icon, and an unknown value just draws a
button without one. So adding a platform is two edits, both in
code: an entry here and its icon in PlatformIcon.tsx. The type
below makes the icon list refuse to compile without it.
'instagram' is also read by splitLinks in server/src/shape.js,
which lifts the handle out for the event cards' follow button.
═══════════════════════════════════════════════════════════════ */
export const PLATFORMS = [
{ id: 'instagram', label: 'Instagram' },
{ id: 'facebook', label: 'Facebook' },
{ id: 'discord', label: 'Discord' },
{ id: 'youtube', label: 'YouTube' },
{ id: 'tiktok', label: 'TikTok' },
{ id: 'x', label: 'X (Twitter)' },
{ id: 'substack', label: 'Substack' },
{ id: 'spotify', label: 'Spotify' },
{ id: 'linkedin', label: 'LinkedIn' },
] as const
export type Platform = (typeof PLATFORMS)[number]['id']

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

@ -20,6 +20,7 @@ import { Link, useParams } from 'react-router-dom'
import PageShell, { type ShellSection } from '../components/PageShell.tsx' import PageShell, { type ShellSection } from '../components/PageShell.tsx'
import PageState from '../components/PageState.tsx' import PageState from '../components/PageState.tsx'
import PlatformIcon from '../components/PlatformIcon.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx' import ContentBlocks from '../components/ContentBlocks.tsx'
import PeopleTiles, { type PeopleGroupInput } from '../components/PeopleTiles.tsx' import PeopleTiles, { type PeopleGroupInput } from '../components/PeopleTiles.tsx'
import { import {
@ -115,9 +116,10 @@ export default function EventDetail() {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }} style={{ background: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}

View file

@ -20,6 +20,7 @@ import { Link, Navigate, useLocation, useParams } from 'react-router-dom'
import PageShell from '../components/PageShell.tsx' import PageShell from '../components/PageShell.tsx'
import PageState from '../components/PageState.tsx' import PageState from '../components/PageState.tsx'
import PlatformIcon from '../components/PlatformIcon.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx' import ContentBlocks from '../components/ContentBlocks.tsx'
import PeopleTiles from '../components/PeopleTiles.tsx' import PeopleTiles from '../components/PeopleTiles.tsx'
import EventListCards from './sections/EventList-Cards.tsx' import EventListCards from './sections/EventList-Cards.tsx'
@ -324,9 +325,10 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }} style={{ background: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}
@ -334,8 +336,8 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) {
{/* website and email arrive as bare strings (splitLinks in {/* website and email arrive as bare strings (splitLinks in
shape.js); socials are whole link rows. */} shape.js); socials are whole link rows. */}
{[ {[
org.website ? { url: org.website, label: 'Website' } : null, org.website ? { url: org.website, label: 'Website', platform: null } : null,
org.email ? { url: `mailto:${org.email}`, label: org.email } : null, org.email ? { url: `mailto:${org.email}`, label: org.email, platform: null } : null,
...org.socials, ...org.socials,
] ]
.filter((link): link is NonNullable<typeof link> => Boolean(link)) .filter((link): link is NonNullable<typeof link> => Boolean(link))
@ -345,9 +347,10 @@ function Contact({ org, accent }: { org: OrganizationRecord; accent: string }) {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" className="inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]"
style={{ borderColor: accent, color: accent }} style={{ borderColor: accent, color: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}

View file

@ -22,6 +22,7 @@ import { Link, useParams } from 'react-router-dom'
import PageShell, { type ShellSection } from '../components/PageShell.tsx' import PageShell, { type ShellSection } from '../components/PageShell.tsx'
import PageState from '../components/PageState.tsx' import PageState from '../components/PageState.tsx'
import PlatformIcon from '../components/PlatformIcon.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx' import ContentBlocks from '../components/ContentBlocks.tsx'
import { import {
usePerson, usePerson,
@ -243,9 +244,9 @@ function Facts({ person, accent }: { person: PersonRecord; accent: string }) {
function Contact({ person, accent }: { person: PersonRecord; accent: string }) { function Contact({ person, accent }: { person: PersonRecord; accent: string }) {
const outlined = [ const outlined = [
person.website ? { url: person.website, label: 'Website' } : null, person.website ? { url: person.website, label: 'Website', platform: null } : null,
person.public_email person.public_email
? { url: `mailto:${person.public_email}`, label: person.public_email } ? { url: `mailto:${person.public_email}`, label: person.public_email, platform: null }
: null, : null,
...person.socials, ...person.socials,
].filter((link): link is NonNullable<typeof link> => Boolean(link)) ].filter((link): link is NonNullable<typeof link> => Boolean(link))
@ -260,9 +261,10 @@ function Contact({ person, accent }: { person: PersonRecord; accent: string }) {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }} style={{ background: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}
@ -273,9 +275,10 @@ function Contact({ person, accent }: { person: PersonRecord; accent: string }) {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]" className="inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-sm font-medium transition-colors hover:bg-[#eef9fb]"
style={{ borderColor: accent, color: accent }} style={{ borderColor: accent, color: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}

View file

@ -15,6 +15,7 @@ import { Link, useParams } from 'react-router-dom'
import PageShell from '../components/PageShell.tsx' import PageShell from '../components/PageShell.tsx'
import PageState from '../components/PageState.tsx' import PageState from '../components/PageState.tsx'
import PlatformIcon from '../components/PlatformIcon.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx' import ContentBlocks from '../components/ContentBlocks.tsx'
import PeopleTiles from '../components/PeopleTiles.tsx' import PeopleTiles from '../components/PeopleTiles.tsx'
import { useTeam } from '../lib/useContent.ts' import { useTeam } from '../lib/useContent.ts'
@ -75,9 +76,10 @@ export default function TeamDetail() {
href={link.url} href={link.url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105" className="inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white transition-transform hover:scale-105"
style={{ background: accent }} style={{ background: accent }}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</a> </a>
))} ))}

View file

@ -9,8 +9,8 @@
reads, so a new entity shows up here the moment it's registered. reads, so a new entity shows up here the moment it's registered.
Forms sit in their own block below: they're submissions coming Forms sit in their own block below: they're submissions coming
in rather than content going out, and there'll be more of them in rather than content going out, and there'll be more of them
than the feedback queue eventually. The Panel block below that than the feedback queue eventually. Tools come next, and the
only exists for superadmins. Panel block below that only exists for superadmins.
The right-hand panel is deliberately inert. Nothing here The right-hand panel is deliberately inert. Nothing here
fetches, so the landing page can't be slow or half-broken on fetches, so the landing page can't be slow or half-broken on
@ -22,7 +22,7 @@ import { Link } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { SITE_VERSION } from "../../lib/version.ts"; import { SITE_VERSION } from "../../lib/version.ts";
import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts";
import { CMS_NAV, FORMS_NAV, PANEL_NAV, target } from "./adminNav.ts"; import { CMS_NAV, FORMS_NAV, PANEL_NAV, TOOLS_NAV, target } from "./adminNav.ts";
/* One card. The title link is stretched over the whole card with /* One card. The title link is stretched over the whole card with
`after:absolute`, which makes the card clickable without nesting `after:absolute`, which makes the card clickable without nesting
@ -129,6 +129,12 @@ export default function AdminHome() {
))} ))}
</CardBlock> </CardBlock>
<CardBlock title={TOOLS_NAV.label} blurb={TOOLS_NAV.blurb}>
{TOOLS_NAV.children.map((tool) => (
<NavCard key={tool.to} item={tool} />
))}
</CardBlock>
{isSuper(user) && ( {isSuper(user) && (
<CardBlock title="Superadmin" blurb="Only superadmins see this block."> <CardBlock title="Superadmin" blurb="Only superadmins see this block.">
<NavCard item={PANEL_NAV} /> <NavCard item={PANEL_NAV} />

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
@ -89,6 +96,21 @@ export const FORMS_NAV = {
], ],
}; };
/* Tools are pages that make something rather than edit a record.
They live on the public site, so they're on the home page only:
a header tab would leave the admin area. */
export const TOOLS_NAV = {
label: "Tools",
blurb: "Handy pages for making things.",
children: [
{
to: "/qr",
label: "QR code generator",
blurb: "Codes for flyers, slides and signs, pointing at any page on the site.",
},
],
};
/* Accounts and server state, not content, which is why it sits /* Accounts and server state, not content, which is why it sits
outside the CMS rather than as another tab within it. */ outside the CMS rather than as another tab within it. */
export const PANEL_NAV = { export const PANEL_NAV = {

View file

@ -4,6 +4,8 @@ import { splitByStatus, typesPresent, useEvents } from "../../data/eventData.ts"
import { eventHref } from "../../lib/hrefs.ts"; 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 { eventBackground, isAbsoluteMedia } from "../../lib/media.ts";
/* ═══════════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════════
EVENT LIST — CARDS EVENT LIST — CARDS
@ -34,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
@ -59,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
@ -96,25 +119,6 @@ const EDGE_FADE = `linear-gradient(to right,
/* Card layout CSS lives in index.css under the .ev- prefix. */ /* Card layout CSS lives in index.css under the .ev- prefix. */
const InstagramIcon = ({ id = "ig-gradient" }) => (
<svg
viewBox="0 0 24 24"
className="ig-icon w-6 h-6"
style={{ "--ig-fill": `url(#${id})` }}
>
<defs>
<linearGradient id={id} x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#FEDA75" />
<stop offset="25%" stopColor="#FA7E1E" />
<stop offset="50%" stopColor="#D62976" />
<stop offset="75%" stopColor="#962FBF" />
<stop offset="100%" stopColor="#4F5BD5" />
</linearGradient>
</defs>
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" />
</svg>
);
/* The title is the way into the event's own page. /* The title is the way into the event's own page.
A link on the title rather than a wrapper around the whole card: A link on the title rather than a wrapper around the whole card:
@ -203,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",
}} }}
@ -302,11 +306,12 @@ export function Card({
<a <a
key={item.label} key={item.label}
href={item.url} href={item.url}
className={`rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${ className={`inline-flex items-center justify-center gap-2 rounded-xl font-700 transition-all duration-200 hover:scale-105 text-center ${
compact ? "py-2.5 px-5" : "py-2.5 px-6" compact ? "py-2.5 px-5" : "py-2.5 px-6"
}`} }`}
style={{ border: `1px solid ${color}`, color }} style={{ border: `1px solid ${color}`, color }}
> >
<PlatformIcon platform={item.platform} />
{item.label} {item.label}
</a> </a>
))} ))}
@ -324,7 +329,7 @@ export function Card({
}`} }`}
style={{ border: `1px solid ${accent}`, color: accent }} style={{ border: `1px solid ${accent}`, color: accent }}
> >
<InstagramIcon id={`ig-${ev.id}`} /> <PlatformIcon platform="instagram" className="w-6 h-6" />
{igHandle} {igHandle}
</a> </a>
)} )}

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,7 @@
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 { import {
areasSentence, areasSentence,
initialsFor, initialsFor,
@ -35,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";
@ -50,7 +50,7 @@ const FALLBACK_COLOR = "#4a6b72";
function RowButton({ as: As = "button", color, children, ...rest }: any) { function RowButton({ as: As = "button", color, children, ...rest }: any) {
return ( return (
<As <As
className="shrink-0 whitespace-nowrap py-2 px-4 rounded-xl font-700 text-sm transition-transform duration-200 hover:scale-105" className="inline-flex shrink-0 items-center gap-2 whitespace-nowrap py-2 px-4 rounded-xl font-700 text-sm transition-transform duration-200 hover:scale-105"
style={{ border: `1px solid ${color}`, color }} style={{ border: `1px solid ${color}`, color }}
{...rest} {...rest}
> >
@ -65,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"
@ -233,6 +233,7 @@ function OrgRow({ org, pageLabel, siteLabel }) {
rel="noopener noreferrer" rel="noopener noreferrer"
color={color} color={color}
> >
<PlatformIcon platform={link.platform} />
{link.label} {link.label}
</RowButton> </RowButton>
))} ))}

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: {