Compare commits

..

No commits in common. "c76df021a8ccfa142a3a31744666051c3a8964fc" and "f797e2c509029345520b490923d557ddf684a3e3" have entirely different histories.

40 changed files with 181 additions and 2058 deletions

View file

@ -62,7 +62,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
- `api.ts` is the shared caching client used by frontend data hooks. - `api.ts` is the shared caching client used by frontend data hooks.
- `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content.
- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). - Images: every record image (logos, photos, backgrounds, block images) is an upload. A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
## Rules and gotchas ## Rules and gotchas
- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.

View file

@ -60,8 +60,8 @@ hand.
| Folder | Used by | Set in | | Folder | Used by | Set in |
| --- | --- | --- | | --- | --- | --- |
| `Requests/<type>` | Files sent with the Request form, a folder per type (`Requests/Chapters`, `Requests/Blog Posts`...) | `DRIVE_FOLDER` and `TYPE_FOLDERS` in `server/src/routes/requests.js` | | `Requests` | Files sent with the Request form | `DRIVE_FOLDER` in `server/src/routes/requests.js` |
| `Media` and folders in it | Files for pages to link to (Tools → Media → Files), in folders you make there | `FOLDER` in `server/src/routes/files.js` | | `Media` | Files for pages to link to (Tools → Media → Files) | `FOLDER` in `server/src/routes/files.js` |
A new use calls `driveUpload("<Folder>", name, mime, bytes)` from A new use calls `driveUpload("<Folder>", name, mime, bytes)` from
`server/src/googleService.js`; a path such as `"Media/2026"` makes each `server/src/googleService.js`; a path such as `"Media/2026"` makes each
@ -78,22 +78,7 @@ folders to the drive; the site ignores them.
Request files are named `Request 12 - original name.docx`, so the number Request files are named `Request 12 - original name.docx`, so the number
matches the one in Forms → Content requests. Deleting a request in the matches the one in Forms → Content requests. Deleting a request in the
admin deletes its files from Drive too. Request files from before the admin deletes its files from Drive too.
per-type folders stay where they are, in `Requests` itself.
Tools → Media → **Requests** lists every request file by its type folder,
each with its request; Forms → Content requests lists a request's own.
Both say **Missing from Drive** for a file Drive no longer has under
`Requests` (deleted, or moved out, by hand): it can't be downloaded or
made into a post, but can be taken off the request. **Remove** (admins
and up) trashes a file in Drive and takes it off its request; the
request itself stays.
**Deleting means Drive's trash.** Whatever the admin deletes (a
request's files, a file, an empty folder) goes to the shared drive's
trash, which keeps it 30 days; restore it from there if needed. A
shared drive's Content manager, the service account's role, can trash
but not permanently delete.
## 3. Gmail (domain-wide delegation) ## 3. Gmail (domain-wide delegation)
@ -216,14 +201,7 @@ Drive" above the title.
and shortcuts don't. A file Drive won't share with anyone who has the and shortcuts don't. A file Drive won't share with anyone who has the
link is named in a red note instead of listed, and tried again every link is named in a red note instead of listed, and tried again every
ten minutes. ten minutes.
- **Folders:** Media → Files has a tab per folder under `Media` (up to - Deleting a file in the admin deletes it from Drive; the delete says
three deep), and uploads go into the one showing. **New folder** makes
one inside it, **Rename** renames it (and everything in it follows),
and **Delete** (admins and up) removes it once it's empty. Each file
has a Folder dropdown to move it. Choose a file has the same tabs. A
folder made in Drive itself, and a file moved there by hand, show up
on the next look.
- Deleting a file in the admin moves it to Drive's trash; the delete says
first which records still link to it (those links stop working). first which records still link to it (those links stop working).
Deleting it in Drive by hand leaves a broken link and a list entry Deleting it in Drive by hand leaves a broken link and a list entry
that can still be deleted. that can still be deleted.

View file

@ -23,37 +23,10 @@ in the `media` table (`server/src/migrations/028_media.sql`).
Limits and sizes are constants at the top of `server/src/media.js`. Limits and sizes are constants at the top of `server/src/media.js`.
## Folders
Images are kept in folders by what they're for (`FOLDERS` in
`server/src/media.js`), and the paths records store include them:
| Folder | What goes in it |
| --- | --- |
| `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` |
| `images/` | Every other upload: photos, backgrounds, covers, block images |
| `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages |
Each image's `-640.webp` small copy sits beside it. Video and audio
clips (Tools → Video clips) stay in the root. The Media page and every
image picker have a tab per folder; a picker opens on its field's
folder, and uploads there.
**Images from before folders** (a bare name in the root) are sorted
once, when the server first starts with this version: a logo or icon
field names it → `logos/`; saved as a preview → `thumbnails/`; anything
else → `images/`. Every record that names it is rewritten to the new
path in one transaction, after the files move (if that fails, the files
move back). The journal says `uploads: moved N image(s) into folders`.
Back up the database and uploads before that first start; nothing is
needed after.
nginx needs no change: `location /uploads/` already serves the folders.
## Files copied in by hand ## Files copied in by hand
A file put straight into the uploads directory, or into one of its A file put straight into the uploads directory (with `scp`, say) shows
folders (with `scp`, say), shows up in the library the next time the Media page or an image picker opens: up in the library the next time the Media page or an image picker opens:
the server registers any image it finds there without a record, under the server registers any image it finds there without a record, under
the file's own name, kept as it is (not resized). Anything that isn't a the file's own name, kept as it is (not resized). Anything that isn't a
JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by

View file

@ -273,7 +273,7 @@ The numbers band's "Number Source" dropdown works the same way:
| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. | | History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. |
| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). | | Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). |
| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. | | Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints, the name field's question and each type's `fields` (the details it asks for, and where each lands in the admin editor: a field path, a link row or a description paragraph) are client-only: the server stores whatever detail keys come as JSON (`feedback.details`, 049), so adding a field needs no migration. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). | | Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints and the name field's question are client-only. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). |
| The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. | | The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. |
| A page section's accent colour | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a colour there, not a hex in a page. Each is readable as text on white and the tints. | | A page section's accent colour | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a colour there, not a hex in a page. Each is readable as text on white and the tints. |

View file

@ -9,26 +9,11 @@ Facebook links; the server downloads it, then you cut clips from it:
the crop; the white box over the video shows what's kept. the crop; the white box over the video shows what's kept.
- **Format**: video (MP4, H.264 and AAC) or audio only (MP3). - **Format**: video (MP4, H.264 and AAC) or audio only (MP3).
A downloaded video can be kept whole too, before or without cutting
it: **Save to library** and **Save to Drive** on the download itself.
It stays on the server to cut clips from either way (until the day's
sweep).
Clips queue and run one at a time. A finished clip is deleted from the Clips queue and run one at a time. A finished clip is deleted from the
server once it's downloaded, unless **Save to library** is pressed first, server once it's downloaded, unless **Save to library** is pressed first,
which puts it in the media library as an upload (usable as a featured which puts it in the media library as an upload (usable as a featured
video or in a video block). Everything is cleared a day after it's made. video or in a video block). Everything is cleared a day after it's made.
**Save to Drive** puts a copy in a folder under Media in the shared
Google Drive (pick it, eg. `Media/Videos` or `Media/Audio`; the list is
Tools → Media → Files's folders, and the one named for the clip's kind
is chosen first). It becomes a Files entry, shared with anyone who has
the link, so pages link to it with Choose a file. It's uploaded straight
from the server's copy (the working file, or the library's), streamed
rather than read into memory, so a long clip is fine; nginx isn't in the
way. A clip can be in both the library and Drive. Needs Google Drive set
up (`docs/google-drive-and-mail.md`) and migration 051.
Only YouTube and Facebook links are accepted, and only for videos NGU owns Only YouTube and Facebook links are accepted, and only for videos NGU owns
or has permission to use. Sources can be up to 4 hours and 4 GB; clips up or has permission to use. Sources can be up to 4 hours and 4 GB; clips up
to an hour. Limits are constants at the top of `server/src/clips.js`. to an hour. Limits are constants at the top of `server/src/clips.js`.

View file

@ -490,10 +490,9 @@ export function kick(db = dbRef) {
export const fileOf = (job) => (job?.file ? filePath(job.file) : null); export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
/* A finished clip, or a whole downloaded video, into the media /* A finished clip into the media library: copied into the uploads
library: copied into the uploads directory under a random name and directory under a random name, given a media row, and its working
given a media row. A clip's working file is deleted; a video's is file deleted. Returns the media row's id. */
kept for cutting. Returns the media row's id. */
export async function saveToLibrary(db, job, userId) { export async function saveToLibrary(db, job, userId) {
const from = fileOf(job); const from = fileOf(job);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again."); if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
@ -529,11 +528,7 @@ export async function saveToLibrary(db, job, userId) {
const { size } = await stat(from); const { size } = await stat(from);
const params = JSON.parse(job.params ?? "{}"); const params = JSON.parse(job.params ?? "{}");
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`; const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
// A whole download is named for itself; a clip for its span. const label = `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
const label =
job.kind === "source"
? `${job.title ?? "Video"}${ext}`
: `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
id = await step("adding it to the media table", () => id = await step("adding it to the media table", () =>
Number( Number(
@ -551,14 +546,8 @@ export async function saveToLibrary(db, job, userId) {
throw err; throw err;
} }
// A clip's working file goes; a downloaded video's stays, to cut await rm(from, { force: true });
// clips from (the day's sweep clears it). update(db, job.id, { saved_media_id: id, file: null });
if (job.kind === "source") {
update(db, job.id, { saved_media_id: id });
} else {
await rm(from, { force: true });
update(db, job.id, { saved_media_id: id, file: null });
}
return { id, url: `${PUBLIC_PREFIX}${filename}` }; return { id, url: `${PUBLIC_PREFIX}${filename}` };
} }

View file

@ -32,9 +32,7 @@
Setup: docs/google-drive-and-mail.md. Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { createReadStream, readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign } from "node:crypto"; import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
@ -101,11 +99,11 @@ async function accessToken(scope, subject) {
return data.access_token; return data.access_token;
} }
async function call(url, init, scope, subject, timeoutMs = 60_000) { async function call(url, init, scope, subject) {
const res = await fetch(url, { const res = await fetch(url, {
...init, ...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(timeoutMs), signal: AbortSignal.timeout(60_000),
}); });
if (!res.ok) { if (!res.ok) {
const detail = await res.json().catch(() => null); const detail = await res.json().catch(() => null);
@ -126,7 +124,6 @@ const folders = new Map();
"Media/2026", made if it isn't there. Found by name, so a folder "Media/2026", made if it isn't there. Found by name, so a folder
renamed in Drive is made again under the old name. */ renamed in Drive is made again under the old name. */
export function driveFolder(path) { export function driveFolder(path) {
path = path.split("/").filter(Boolean).join("/");
let pending = folders.get(path); let pending = folders.get(path);
if (!pending) { if (!pending) {
pending = findOrMakeFolder(path); pending = findOrMakeFolder(path);
@ -136,21 +133,10 @@ export function driveFolder(path) {
return pending; return pending;
} }
/* After a folder is renamed or deleted: its path, and the paths
under it, are looked up afresh next time. */
export function forgetFolders(path) {
for (const key of folders.keys()) if (key === path || key.startsWith(`${path}/`)) folders.delete(key);
}
async function findOrMakeFolder(path) { async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE; const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive; let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) { for (const name of path.split("/").filter(Boolean)) {
// Each level on the way is known too: "Requests" once
// "Requests/Chapters" has been found.
if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent));
walked.push(name);
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({ const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`, q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
@ -201,15 +187,16 @@ export async function driveUpload(folder, name, mime, buffer) {
return await res.json(); return await res.json();
} }
/* Everything directly in a folder: [{ id, name, mimeType, size, /* The files (not folders) directly in a folder of the shared drive:
webViewLink }]. size is missing for Google's own Docs, Sheets and [{ id, name, mimeType, size, webViewLink }]. size is missing for
Slides. */ Google's own Docs, Sheets and Slides. */
async function driveChildren(parent) { export async function driveList(folder) {
const parent = await driveFolder(folder);
const found = []; const found = [];
let pageToken = ""; let pageToken = "";
do { do {
const query = new URLSearchParams({ const query = new URLSearchParams({
q: `'${parent}' in parents and trashed = false`, q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`,
corpora: "drive", corpora: "drive",
driveId: process.env.GOOGLE_SHARED_DRIVE, driveId: process.env.GOOGLE_SHARED_DRIVE,
includeItemsFromAllDrives: "true", includeItemsFromAllDrives: "true",
@ -225,88 +212,6 @@ async function driveChildren(parent) {
return found; return found;
} }
/* A folder and the folders under it, down to `depth` levels: the
folders' paths (relative to it, "" for itself) and ids, and every
file with the path of the folder it's in. */
export async function driveTree(path, depth = 3) {
const folderList = [{ path: "", id: await driveFolder(path) }];
const files = [];
for (let i = 0; i < folderList.length; i++) {
const here = folderList[i];
for (const item of await driveChildren(here.id)) {
if (item.mimeType === FOLDER) {
const sub = here.path ? `${here.path}/${item.name}` : item.name;
if (sub.split("/").length <= depth) {
folderList.push({ path: sub, id: item.id });
// Known now: no lookup needed to upload into it.
const full = `${path}/${sub}`;
if (!folders.has(full)) folders.set(full, Promise.resolve(item.id));
}
} else {
files.push({ ...item, folder: here.path });
}
}
}
return { folders: folderList, files };
}
/* Whether a folder has anything in it (files or folders). */
export async function driveFolderEmpty(id) {
return (await driveChildren(id)).length === 0;
}
/* A file or folder from one folder into another. */
export async function driveMove(id, fromParent, toParent) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true&addParents=${encodeURIComponent(toParent)}&removeParents=${encodeURIComponent(fromParent)}`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}" },
DRIVE_SCOPE,
);
}
export async function driveRename(id, name) {
await call(
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) },
DRIVE_SCOPE,
);
}
/* A file on disk into a folder of the shared drive, streamed through
a resumable upload rather than read into memory (a video clip can
be large). Returns { id, webViewLink }, as driveUpload does. */
export async function driveUploadFile(folder, name, mime, filePath) {
const { size } = await stat(filePath);
const start = await call(
`${DRIVE_UPLOAD}?uploadType=resumable&supportsAllDrives=true&fields=id,webViewLink`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": mime,
"X-Upload-Content-Length": String(size),
},
body: JSON.stringify({ name, parents: [await driveFolder(folder)] }),
},
DRIVE_SCOPE,
);
const session = start.headers.get("location");
if (!session) throw new GoogleError("Drive didn't start the upload.");
const res = await call(
session,
{
method: "PUT",
headers: { "Content-Type": mime, "Content-Length": String(size) },
body: Readable.toWeb(createReadStream(filePath)),
duplex: "half",
},
DRIVE_SCOPE,
undefined,
30 * 60_000,
);
return await res.json();
}
/* Anyone with the link can view: for files the public site links to. /* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */ sharing outside the organization. */
@ -339,15 +244,8 @@ export async function driveDownload(id) {
return Buffer.from(await res.arrayBuffer()); return Buffer.from(await res.arrayBuffer());
} }
/* Into Drive's trash (a shared drive keeps it 30 days), not deleted
outright: a shared drive's Content manager, the service account's
role, may trash but not permanently delete. */
export async function driveDelete(id) { export async function driveDelete(id) {
await call( await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE);
`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`,
{ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) },
DRIVE_SCOPE,
);
} }
/* ── Gmail ───────────────────────────────────────────────────── */ /* ── Gmail ───────────────────────────────────────────────────── */

View file

@ -38,7 +38,7 @@ import clips from "./routes/clips.js";
import imports from "./routes/import.js"; import imports from "./routes/import.js";
import files from "./routes/files.js"; import files from "./routes/files.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, sortIntoFolders, writeMissingThumbs } from "./media.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js"; import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js"; import { startGroupSync } from "./accessGroups.js";
@ -57,9 +57,6 @@ 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 }); await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`); console.log(`uploads ${UPLOADS_DIR}`);
// Once: images from before folders into logos/, images/, thumbnails/.
const sorted = await sortIntoFolders(db);
if (sorted) console.log(`uploads: moved ${sorted} image(s) into folders`);
// In the background: pages fall back to the full file until it's done. // In the background: pages fall back to the full file until it's done.
writeMissingThumbs() writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`)) .then((made) => made && console.log(`uploads: made ${made} small copies`))

View file

@ -30,15 +30,6 @@
Names are random, so two uploads of "logo.png" can't collide Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in it. and a filename says nothing about what's in it.
── Folders ──
Each upload goes in a folder by what it's for (FOLDERS): logos/
for logo and icon fields, thumbnails/ for pictures the site saves
by itself (link previews, Drive files' first pages), images/ for
the rest. A stored name includes it: 'logos/3f9c….webp', served at
/uploads/logos/3f9c….webp. The small copy sits beside it. Clips
and files from before folders keep a bare name in the root.
sortIntoFolders() moves those older images once, at boot.
── Files copied in by hand ── ── Files copied in by hand ──
A file put straight into UPLOADS_DIR has no media row, so the A file put straight into UPLOADS_DIR has no media row, so the
library wouldn't know it. registerLooseFiles() gives each image library wouldn't know it. registerLooseFiles() gives each image
@ -50,8 +41,6 @@
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto"; import { randomBytes } from "node:crypto";
import { tx } from "./db.js";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
@ -67,42 +56,6 @@ const MB = 1024 * 1024;
/* The largest file accepted at all, before processing: room for a /* The largest file accepted at all, before processing: room for a
full-size phone photo. */ full-size phone photo. */
/* Where an upload goes, by what it's for (see Folders above). */
export const FOLDERS = ["logos", "images", "thumbnails"];
export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images");
/* A name this library stores: a bare name in the root, or one inside
a FOLDER. Anything else (a path out, a dotfile) is refused wherever
a name is joined onto UPLOADS_DIR. */
export function isStoredName(name) {
const parts = String(name ?? "").split("/");
const base = parts[parts.length - 1];
if (!base || base.startsWith(".") || path.basename(base) !== base) return false;
return parts.length === 1 || (parts.length === 2 && FOLDERS.includes(parts[0]));
}
/* The public path of a stored name, each part escaped. */
export const publicPath = (filename) =>
`${PUBLIC_PREFIX}${String(filename).split("/").map(encodeURIComponent).join("/")}`;
/* Every stored file's name: the root's, then each folder's. */
async function listStored() {
const names = [];
for (const dir of ["", ...FOLDERS]) {
let entries;
try {
entries = await readdir(path.join(UPLOADS_DIR, dir), { withFileTypes: true });
} catch (err) {
if (err.code === "ENOENT") continue;
throw err;
}
for (const entry of entries) {
if (entry.isFile() && !entry.name.startsWith(".")) names.push(dir ? `${dir}/${entry.name}` : entry.name);
}
}
return names;
}
export const MAX_UPLOAD_BYTES = 25 * MB; export const MAX_UPLOAD_BYTES = 25 * MB;
/* The largest file kept as uploaded, unprocessed. */ /* The largest file kept as uploaded, unprocessed. */
@ -163,7 +116,7 @@ function sniff(buf) {
and leave nothing behind. and leave nothing behind.
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
export async function store(buf, { keepOriginal = false, folder } = {}) { export async function store(buf, { keepOriginal = false } = {}) {
if (buf.length === 0) throw new MediaError(400, "The file is empty."); if (buf.length === 0) throw new MediaError(400, "The file is empty.");
if (buf.length > MAX_UPLOAD_BYTES) { if (buf.length > MAX_UPLOAD_BYTES) {
throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`); throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`);
@ -211,14 +164,12 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
throw new MediaError(415, "That image couldn't be read. It may be damaged."); throw new MediaError(415, "That image couldn't be read. It may be damaged.");
} }
const dir = folderOf(folder); const filename = `${randomBytes(12).toString("hex")}${type.ext}`;
const base = `${randomBytes(12).toString("hex")}${type.ext}`;
const filename = `${dir}/${base}`;
await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true }); await mkdir(UPLOADS_DIR, { recursive: true });
// Written under a temporary name and renamed, so a half-written // Written under a temporary name and renamed, so a half-written
// file is never served under its real one. // file is never served under its real one.
const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
await writeFile(tmp, out); await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename)); await rename(tmp, path.join(UPLOADS_DIR, filename));
if (kind !== "svg") await writeThumb(filename, out); if (kind !== "svg") await writeThumb(filename, out);
@ -249,7 +200,7 @@ export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.
async function writeThumb(filename, buf) { async function writeThumb(filename, buf) {
const name = thumbName(filename); const name = thumbName(filename);
const tmp = path.join(UPLOADS_DIR, path.dirname(name), `.${path.basename(name)}.tmp`); const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`);
try { try {
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS }) await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate() .rotate()
@ -267,11 +218,17 @@ async function writeThumb(filename, buf) {
/* Makes the small copy for every raster upload that lacks one. /* Makes the small copy for every raster upload that lacks one.
Returns how many it made. */ Returns how many it made. */
export async function writeMissingThumbs() { export async function writeMissingThumbs() {
const names = await listStored(); let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const present = new Set(names); const present = new Set(names);
let made = 0; let made = 0;
for (const name of names) { for (const name of names) {
if (THUMB.test(name) || /\.svg$/i.test(name)) continue; if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue;
if (present.has(thumbName(name))) continue; if (present.has(thumbName(name))) continue;
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; if (!buf || !sniff(buf) || sniff(buf) === "svg") continue;
@ -285,8 +242,8 @@ export async function writeMissingThumbs() {
gone is not an error: the row is what's being removed. */ gone is not an error: the row is what's being removed. */
export async function remove(filename) { export async function remove(filename) {
// filename comes from our own table, but it's joined onto a // filename comes from our own table, but it's joined onto a
// directory, so refuse anything that isn't a stored name. // directory, so refuse anything that isn't a bare name.
if (!isStoredName(filename)) return; if (path.basename(filename) !== filename) return;
for (const name of [filename, thumbName(filename)]) { for (const name of [filename, thumbName(filename)]) {
try { try {
await unlink(path.join(UPLOADS_DIR, name)); await unlink(path.join(UPLOADS_DIR, name));
@ -335,7 +292,13 @@ async function describe(filename) {
how many it added. Safe to run often: it only reads the folder how many it added. Safe to run often: it only reads the folder
and the table, and inserts nothing twice (filename is UNIQUE). */ and the table, and inserts nothing twice (filename is UNIQUE). */
export async function registerLooseFiles(db) { export async function registerLooseFiles(db) {
const names = await listStored(); let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename)); const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename));
const insert = db.prepare( const insert = db.prepare(
@ -346,7 +309,7 @@ export async function registerLooseFiles(db) {
let added = 0; let added = 0;
for (const name of names) { for (const name of names) {
if (known.has(name) || THUMB.test(name) || !isStoredName(name)) continue; if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue;
let row; let row;
try { try {
row = await describe(name); row = await describe(name);
@ -356,7 +319,7 @@ export async function registerLooseFiles(db) {
if (!row) continue; if (!row) continue;
const result = insert.run( const result = insert.run(
row.filename, row.filename,
path.basename(row.filename), row.filename,
row.content_type, row.content_type,
row.bytes, row.bytes,
row.width, row.width,
@ -368,88 +331,3 @@ export async function registerLooseFiles(db) {
if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`); if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`);
return added; return added;
} }
/* ── Into folders, once ───────────────────────────────────────── */
// Columns that hold a logo or a site icon: an image one of these
// names goes in logos/.
const LOGO_COLUMNS = new Set(["logo", "org_logo", "event_logo", "favicon", "apple_touch_icon"]);
// Tables whose text never names an upload a page uses.
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
/* Every image still in the root from before folders, moved into the
folder its uses call for (logos/ if a logo or icon field names it,
thumbnails/ if the site saved it as a preview, else images/), with
every record that names it rewritten to the new path. The files
move first; the rows change in one transaction, and if that fails
the files move back. Returns how many moved; run at boot, and a
no-op once nothing is left in the root. */
export async function sortIntoFolders(db) {
const rows = db
.prepare(
`SELECT id, filename, original_name FROM media
WHERE instr(filename, '/') = 0 AND content_type LIKE 'image/%'`,
)
.all();
if (rows.length === 0) return 0;
const columns = [];
for (const { name: table } of db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()) {
if (NOT_CONTENT.has(table)) continue;
for (const col of db.prepare(`SELECT name, type FROM pragma_table_info(?)`).all(table)) {
if (col.type.toUpperCase() === "TEXT") columns.push({ table, column: col.name });
}
}
const namesOf = (filename) => [
...new Set([`${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, filename]),
];
const holds = (table, column, values) =>
db
.prepare(`SELECT 1 FROM "${table}" WHERE "${column}" IN (${values.map(() => "?").join(", ")}) LIMIT 1`)
.get(...values);
const moved = [];
for (const row of rows) {
const values = namesOf(row.filename);
const folder = columns.some(({ table, column }) => LOGO_COLUMNS.has(column) && holds(table, column, values))
? "logos"
: /^preview |\(preview\)$/.test(row.original_name) || holds("drive_files", "preview", values)
? "thumbnails"
: "images";
const to = `${folder}/${row.filename}`;
try {
await mkdir(path.join(UPLOADS_DIR, folder), { recursive: true });
await rename(path.join(UPLOADS_DIR, row.filename), path.join(UPLOADS_DIR, to));
} catch (err) {
// Not on disk (deleted by hand): leave its row as it is.
if (err.code !== "ENOENT") console.warn(`media: couldn't move ${row.filename}: ${err.message}`);
continue;
}
await rename(path.join(UPLOADS_DIR, thumbName(row.filename)), path.join(UPLOADS_DIR, thumbName(to))).catch(() => {});
moved.push({ row, to, values });
}
try {
tx(db, () => {
for (const { row, to, values } of moved) {
db.prepare(`UPDATE media SET filename = ? WHERE id = ?`).run(to, row.id);
for (const { table, column } of columns) {
db.prepare(`UPDATE "${table}" SET "${column}" = ? WHERE "${column}" IN (${values.map(() => "?").join(", ")})`).run(
publicPath(to),
...values,
);
}
}
});
} catch (err) {
for (const { row, to } of moved) {
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, row.filename)).catch(() => {});
await rename(path.join(UPLOADS_DIR, thumbName(to)), path.join(UPLOADS_DIR, thumbName(row.filename))).catch(() => {});
}
throw err;
}
return moved.length;
}

View file

@ -1,12 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 049 REQUEST DETAILS
--
-- The Request form's details for the record it's about (a chapter's
-- city, website and meeting time, an event's dates...), as one JSON
-- object of strings: { "city": "Kansas City", "meets": "..." }. Which
-- keys there are is src/data/requestTypes.ts's business; the server
-- only checks the shape (routes/requests.js). Forms → Content
-- requests shows them and opens the record's editor filled in.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE feedback ADD COLUMN details TEXT CHECK (details IS NULL OR json_valid(details));

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 050 FOLDERS FOR DRIVE FILES
--
-- The folder a file is in, under the shared drive's Media folder:
-- '' for Media itself, 'Slides' or 'Slides/2026' below it. Made,
-- renamed and deleted from Tools → Media → Files (routes/files.js);
-- a file moved in Drive by hand is followed on the next look.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE drive_files ADD COLUMN folder TEXT NOT NULL DEFAULT '';

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 051 CLIPS SAVED TO DRIVE
--
-- Tools → Video clips → Save to Drive puts a finished clip in a folder
-- under the shared drive's Media folder, as a Files entry
-- (drive_files, 048). The job keeps which one, as it keeps its media
-- library copy in saved_media_id; a clip can be in both.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE clip_jobs ADD COLUMN saved_drive_file_id INTEGER REFERENCES drive_files (id) ON DELETE SET NULL;

View file

@ -11,9 +11,7 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js"; import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js"; import { driveDelete, driveDownload } from "../googleService.js";
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
import { addToLibrary, shape as mediaShape } from "./media.js";
import { HttpError } from "../admin-crud.js"; import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js"; import { importDocx } from "./import.js";
@ -32,43 +30,20 @@ const KIND_WHERE = {
content: "feedback_type = 'content'", content: "feedback_type = 'content'",
}; };
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id, const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject, details`; status, admin_note, category, request_action, subject`;
/* The ids of every file under Requests in Drive (any type folder), /* Each row with its files (content requests), in one query. */
looked up at most every 30 seconds; null when Drive isn't set up or function withFiles(db, rows) {
didn't answer, which marks nothing missing. A file someone deleted
or moved out of Requests in Drive is then "missing". */
let inDrive = { at: 0, ids: null };
async function requestFilesInDrive() {
if (!driveReady()) return null;
if (Date.now() - inDrive.at < 30_000) return inDrive.ids;
try {
const tree = await driveTree(DRIVE_FOLDER, 2);
inDrive = { at: Date.now(), ids: new Set(tree.files.map((f) => f.id)) };
} catch (err) {
console.warn(`feedback: couldn't list ${DRIVE_FOLDER} in Drive: ${err.message}`);
inDrive = { at: Date.now(), ids: null };
}
return inDrive.ids;
}
/* Each row with its files (content requests), in one query. `ids`
(requestFilesInDrive) says which are still in Drive. */
function withFiles(db, rows, ids = null) {
if (rows.length === 0) return rows; if (rows.length === 0) return rows;
const files = db const files = db
.prepare( .prepare(
`SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files `SELECT id, feedback_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`, WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
) )
.all(...rows.map((r) => r.id)); .all(...rows.map((r) => r.id));
return rows.map((row) => ({ return rows.map((row) => ({
...row, ...row,
// Stored as JSON text (049); the admin wants the object. files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
details: row.details ? JSON.parse(row.details) : null,
files: files
.filter((f) => f.feedback_id === row.id)
.map(({ feedback_id, drive_id, ...f }) => ({ ...f, missing: ids ? !ids.has(drive_id) : false })),
})); }));
} }
const MAX_LIMIT = 200; const MAX_LIMIT = 200;
@ -85,7 +60,7 @@ const NOTE_LIMIT = 2000;
?limit=50 ?limit=50
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
admin.get("/feedback", async (c) => { admin.get("/feedback", (c) => {
const db = c.get("db"); const db = c.get("db");
const { status, type, kind, q, before, limit } = c.req.query(); const { status, type, kind, q, before, limit } = c.req.query();
@ -125,7 +100,7 @@ admin.get("/feedback", async (c) => {
.all(...params, take + 1); // one extra to detect a next page .all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take; const hasMore = rows.length > take;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null); const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
// Status counts cover this queue (kind) but ignore the other // Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a // filters: the tabs show what's waiting, not what's left after a
@ -195,7 +170,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive()); const result = db_update(c.get("db"), id, sets, params);
if (!result) return c.json({ error: "No such feedback." }, 404); if (!result) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} updated by ${c.get("user").email}`); console.log(`feedback #${id} updated by ${c.get("user").email}`);
@ -203,14 +178,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
return c.json({ feedback: result }, 200, NO_STORE); return c.json({ feedback: result }, 200, NO_STORE);
}); });
function db_update(db, id, sets, params, ids) { function db_update(db, id, sets, params) {
const changed = db const changed = db
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`) .prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
.run(...params, id); .run(...params, id);
if (changed.changes === 0) return null; if (changed.changes === 0) return null;
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0]; return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
} }
/* ── DELETE /api/admin/feedback/:id ────────────────────────────── /* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -244,16 +219,9 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
}); });
/* ── A content request's files ─────────────────────────────────── /* ── A content request's files ───────────────────────────────────
GET /feedback/:id/files/:file download, from Drive GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up unpublished blog post (import.js), editors and up
POST /feedback/:id/files/:file/to-library { folder }: a photo
into the media library, for an image field (the picker's
From requests tab), editors and up
DELETE /feedback/:id/files/:file into Drive's trash and
off the request, admins and up
GET /request-files every request's files,
by type folder, for Tools → Media → Requests
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
function fileOf(c) { function fileOf(c) {
@ -288,29 +256,6 @@ admin.get("/feedback/:id/files/:file", async (c) => {
} }
}); });
/* A request's photo as an upload: records' images live in the media
library, not Drive. Once per file: the copy is found again by name. */
admin.post("/feedback/:id/files/:file/to-library", requireRole("editor"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
if (!file.mime.startsWith("image/")) return c.json({ error: "Only a photo (JPEG or PNG) can go in the library." }, 400);
const db = c.get("db");
const name = `${file.name} (request ${c.req.param("id")})`.slice(0, 200);
const known = db.prepare(`SELECT m.* FROM media m WHERE m.original_name = ?`).get(name);
if (known) return c.json({ media: mediaShape(known) }, 200, NO_STORE);
try {
const bytes = await fromDrive(file);
const body = (await c.req.json().catch(() => null)) ?? {};
const row = await addToLibrary(db, bytes, { originalName: name, folder: body.folder, userId: c.get("user").id });
console.log(`feedback #${c.req.param("id")}: ${file.name} into the media library by ${c.get("user").email}`);
return c.json({ media: mediaShape(row) }, 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
if (err?.status && err?.message) return c.json({ error: err.message }, err.status); // MediaError
throw err;
}
});
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => { admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
const file = fileOf(c); const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404); if (!file) return c.json({ error: "No such file." }, 404);
@ -323,45 +268,4 @@ admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (
} }
}); });
admin.delete("/feedback/:id/files/:file", requireRole("admin"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
try {
await driveDelete(file.drive_id);
} catch (err) {
// Already gone from Drive: the row goes anyway.
if (!/^404 /.test(err.message)) return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
c.get("db").prepare(`DELETE FROM feedback_files WHERE id = ?`).run(file.id);
inDrive.ids?.delete(file.drive_id);
console.log(`feedback #${c.req.param("id")}: file ${file.name} removed by ${c.get("user").email}`);
return c.body(null, 204);
});
admin.get("/request-files", async (c) => {
const db = c.get("db");
const ids = await requestFilesInDrive();
const rows = db
.prepare(
`SELECT f.id, f.feedback_id, f.drive_id, f.name, f.mime, f.size,
r.category, r.subject, r.request_action, r.status, r.created_at
FROM feedback_files f JOIN feedback r ON r.id = f.feedback_id
ORDER BY r.id DESC, f.id`,
)
.all();
return c.json(
{
files: rows.map(({ drive_id, ...row }) => ({
...row,
folder: TYPE_FOLDERS[row.category] ?? "",
missing: ids ? !ids.has(drive_id) : false,
})),
folders: Object.values(TYPE_FOLDERS),
checked: ids !== null,
},
200,
NO_STORE,
);
});
export default admin; export default admin;

View file

@ -80,24 +80,6 @@ function shapeSummary(row, authors, body) {
}; };
} }
/* A person's page: the published, listed posts they're an author
of, newest first, as the same summaries the blog section shows.
routes/people.js adds them to /people/:id. */
export function postsBy(db, personId) {
const rows = db
.prepare(
`SELECT b.* FROM blog_posts b
JOIN blog_post_authors a ON a.post_id = b.id AND a.person_id = ?
WHERE b.is_published = 1 AND b.is_listed = 1
ORDER BY b.published_on IS NULL, b.published_on DESC, b.created_at DESC`,
)
.all(personId);
const ids = rows.map((row) => row.id);
const authors = loadAuthors(db, ids);
const bodies = loadBlocks(db, "blog_post", ids, "body");
return rows.map((row) => shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []));
}
/* ── One post ──────────────────────────────────────────────── */ /* ── One post ──────────────────────────────────────────────── */
blog.get("/blog/:id", (c) => { blog.get("/blog/:id", (c) => {

View file

@ -11,13 +11,8 @@
GET /clips/:id/download a finished clip, as an attachment; GET /clips/:id/download a finished clip, as an attachment;
its file is deleted once it has its file is deleted once it has
gone out in full, unless saved gone out in full, unless saved
POST /clips/:id/save a finished clip, or a whole POST /clips/:id/save a finished clip into the media
downloaded video, into the media
library library
POST /clips/:id/drive { folder }: a finished clip (or a
whole downloaded video) into a
folder under Media in Drive, as a
Files entry (routes/files.js)
DELETE /clips/:id a job and its files (a source DELETE /clips/:id a job and its files (a source
takes its clips) takes its clips)
@ -28,7 +23,6 @@
import { createReadStream } from "node:fs"; import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises"; import { stat } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream"; import { Readable } from "node:stream";
import { Hono } from "hono"; import { Hono } from "hono";
@ -46,9 +40,6 @@ import {
toolVersions, toolVersions,
} from "../clips.js"; } from "../clips.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
import { UPLOADS_DIR } from "../media.js";
import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js";
import { cleanFolder, inDrive, recordDriveUpload } from "./files.js";
const clips = new Hono(); const clips = new Hono();
@ -80,19 +71,15 @@ function shape(job) {
has_file: Boolean(job.file), has_file: Boolean(job.file),
saved_media_id: job.saved_media_id, saved_media_id: job.saved_media_id,
saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null, saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null,
saved_drive: job.saved_drive_file_id
? { id: job.saved_drive_file_id, url: job.saved_drive_url, folder: job.saved_drive_folder }
: null,
downloaded_at: job.downloaded_at, downloaded_at: job.downloaded_at,
created_at: job.created_at, created_at: job.created_at,
finished_at: job.finished_at, finished_at: job.finished_at,
}; };
} }
const SELECT = `SELECT j.*, m.filename AS saved_filename, d.url AS saved_drive_url, d.folder AS saved_drive_folder const SELECT = `SELECT j.*, m.filename AS saved_filename
FROM clip_jobs j FROM clip_jobs j
LEFT JOIN media m ON m.id = j.saved_media_id LEFT JOIN media m ON m.id = j.saved_media_id`;
LEFT JOIN drive_files d ON d.id = j.saved_drive_file_id`;
function findOr404(c) { function findOr404(c) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));
@ -216,61 +203,13 @@ clips.get("/clips/:id/download", async (c) => {
clips.post("/clips/:id/save", async (c) => { clips.post("/clips/:id/save", async (c) => {
const db = c.get("db"); const db = c.get("db");
const job = findOr404(c); const job = findOr404(c);
if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved."); if (job.kind !== "clip" || job.status !== "done") throw new ClipError(400, "Only a finished clip can be saved.");
if (job.saved_media_id) throw new ClipError(409, "It's already in the media library."); if (job.saved_media_id) throw new ClipError(409, "It's already in the media library.");
if (!job.file) throw new ClipError(410, "Its file is gone from the server.");
const media = await saveToLibrary(db, job, c.get("user").id); const media = await saveToLibrary(db, job, c.get("user").id);
console.log(`clips: clip ${job.id} saved to the library by ${c.get("user").email}`); console.log(`clips: clip ${job.id} saved to the library by ${c.get("user").email}`);
return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE); return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
}); });
/* Into Drive: the working file, or once it's gone into the library,
the library's copy. It stays wherever it was, so a clip can be in
both, and the day's sweep still clears the working file. */
clips.post("/clips/:id/drive", async (c) => {
const db = c.get("db");
const job = findOr404(c);
if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved.");
if (job.saved_drive_file_id) throw new ClipError(409, "It's already in Drive.");
if (!driveReady()) throw new ClipError(400, "Google Drive isn't set up on the server (docs/google-drive-and-mail.md).");
const folder = cleanFolder((await body(c)).folder);
if (folder === null) throw new ClipError(422, "That isn't a folder name.");
const from = fileOf(job) ?? (job.saved_filename ? path.join(UPLOADS_DIR, job.saved_filename) : null);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = from.endsWith(".mp3");
const mime = audio ? "audio/mpeg" : "video/mp4";
const params = job.params ? JSON.parse(job.params) : {};
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const title = (job.title ?? "").replace(/[\u0000-\u001f"\\/]+/g, " ").trim().slice(0, 120);
const name =
job.kind === "source"
? `${title || "Video"}.mp4`
: `${title || "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)}).${audio ? "mp3" : "mp4"}`;
let uploaded;
try {
uploaded = await driveUploadFile(inDrive(folder), name, mime, from);
} catch (err) {
console.warn(`clips: clip ${job.id} to Drive failed: ${err.message}`);
throw new ClipError(502, `Google Drive didn't take it: ${err.message}`);
}
try {
await driveShareWithAnyone(uploaded.id);
} catch (err) {
await driveDelete(uploaded.id).catch(() => {});
throw new ClipError(
502,
`Drive wouldn't share it with anyone who has the link (${err.message}). The sharing settings must allow sharing outside the organization.`,
);
}
const { size } = await stat(from);
const file = await recordDriveUpload(db, uploaded, { name, mime, bytes: size, folder, userId: c.get("user").id });
db.prepare(`UPDATE clip_jobs SET saved_drive_file_id = ? WHERE id = ?`).run(file.id, job.id);
console.log(`clips: clip ${job.id} saved to Drive (${inDrive(folder)}) by ${c.get("user").email}`);
return c.json({ file, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
});
clips.delete("/clips/:id", async (c) => { clips.delete("/clips/:id", async (c) => {
const job = findOr404(c); const job = findOr404(c);
if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish."); if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish.");

View file

@ -5,19 +5,9 @@
Picks up files put in the folder Picks up files put in the folder
in Drive by hand first (pickUp, at in Drive by hand first (pickUp, at
most every SCAN_EVERY_MS) most every SCAN_EVERY_MS)
POST /files upload one (multipart: file, folder) POST /files upload one (multipart: file)
PATCH /files/:id { folder }: move it to another folder
GET /files/:id/uses which records link to it GET /files/:id/uses which records link to it
DELETE /files/:id into Drive's trash, out of the list DELETE /files/:id out of Drive and the list
POST /files/folders { path }: make a folder
PATCH /files/folders { path, name }: rename one
DELETE /files/folders?path= delete an empty one
Folders: under FOLDER, at most MAX_DEPTH deep, named by a path
relative to it ('' is FOLDER itself, 'Slides/2026' below it). The
list's `folders` are every one Drive has there, so one made in
Drive by hand shows up too.
Files for the public site to link to, kept in the shared drive's Files for the public site to link to, kept in the shared drive's
FOLDER (googleService.js) and shared as "anyone with the link can FOLDER (googleService.js) and shared as "anyone with the link can
@ -45,53 +35,14 @@ import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit"; import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js"; import { requireAuth, requireRole } from "../auth.js";
import { import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
driveDelete,
driveFolder,
driveFolderEmpty,
driveMove,
driveReady,
driveRename,
driveShareWithAnyone,
driveThumbnail,
driveTree,
driveUpload,
forgetFolders,
} from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js"; import { addToLibrary, recordsNaming } from "./media.js";
import { publicPath } from "../media.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
const files = new Hono(); const files = new Hono();
files.use("*", requireAuth); files.use("*", requireAuth);
export const FOLDER = "Media"; const FOLDER = "Media";
const MAX_DEPTH = 3;
/* A folder path as given, cleaned: '' for FOLDER itself, or up to
MAX_DEPTH names of 1 to 60 characters, none of them "." or "..",
joined by "/". null when it can't be one. */
export function cleanFolder(value) {
const parts = String(value ?? "")
.split("/")
.map((part) => part.replace(/[\u0000-\u001f\\]+/g, " ").trim())
.filter(Boolean);
if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null;
return parts.join("/");
}
export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
/* A file just uploaded to Drive (and shared) into the list: its row,
and the first try at its preview (more follow on their own).
Returns what the list shows. Also how the clip tool's Save to Drive
lands (routes/clips.js). */
export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) {
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId).lastInsertRowid;
await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId);
return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id));
}
const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500; const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again. // Seconds after upload to ask Drive for the preview again.
@ -137,7 +88,6 @@ const shape = (row) => ({
bytes: row.bytes, bytes: row.bytes,
url: row.url, url: row.url,
preview: row.preview, preview: row.preview,
folder: row.folder,
uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null, uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null,
created_at: row.created_at, created_at: row.created_at,
}); });
@ -150,8 +100,8 @@ function fetchPreview(db, row, userId) {
try { try {
const image = await driveThumbnail(row.drive_id); const image = await driveThumbnail(row.drive_id);
if (image) { if (image) {
const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId, folder: "thumbnails" }); const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId });
db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(publicPath(saved.filename), row.id); db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(`/uploads/${saved.filename}`, row.id);
return; return;
} }
} catch (err) { } catch (err) {
@ -169,29 +119,20 @@ function fetchPreview(db, row, userId) {
Never throws: the list still shows what's known. */ Never throws: the list still shows what's known. */
const RETRY_MS = 10 * 60 * 1000; const RETRY_MS = 10 * 60 * 1000;
let lastScan = 0; let lastScan = 0;
let folderPaths = [];
const refused = new Map(); // drive id → { name, at } const refused = new Map(); // drive id → { name, at }
async function pickUp(db, force = false) { async function pickUp(db) {
if (!driveReady() || (!force && Date.now() - lastScan < SCAN_EVERY_MS)) return; if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return;
lastScan = Date.now(); lastScan = Date.now();
let tree; let found;
try { try {
tree = await driveTree(FOLDER, MAX_DEPTH); found = await driveList(FOLDER);
} catch (err) { } catch (err) {
console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`); console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`);
return; return;
} }
folderPaths = tree.folders.map((f) => f.path).filter(Boolean).sort((a, b) => a.localeCompare(b)); const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id));
const known = new Map(db.prepare(`SELECT drive_id, folder FROM drive_files`).all().map((r) => [r.drive_id, r.folder])); for (const file of found) {
for (const file of tree.files) { if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue;
// Moved in Drive by hand: follow it.
if (known.has(file.id)) {
if (known.get(file.id) !== file.folder) {
db.prepare(`UPDATE drive_files SET folder = ? WHERE drive_id = ?`).run(file.folder, file.id);
}
continue;
}
if (SKIP_TYPES.has(file.mimeType)) continue;
if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue; if (Date.now() - (refused.get(file.id)?.at ?? 0) < RETRY_MS) continue;
try { try {
await driveShareWithAnyone(file.id); await driveShareWithAnyone(file.id);
@ -202,8 +143,8 @@ async function pickUp(db, force = false) {
} }
refused.delete(file.id); refused.delete(file.id);
const id = db const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`) .prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url) VALUES (?, ?, ?, ?, ?)`)
.run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder).lastInsertRowid; .run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink).lastInsertRowid;
console.log(`files: ${file.name} picked up from Drive`); console.log(`files: ${file.name} picked up from Drive`);
// In the background: a folder of new files shouldn't hold the list. // In the background: a folder of new files shouldn't hold the list.
fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null); fetchPreview(db, db.prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id), null);
@ -217,16 +158,7 @@ files.get("/files", async (c) => {
.get("db") .get("db")
.prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`) .prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`)
.all(...(q ? [`%${q}%`] : [])); .all(...(q ? [`%${q}%`] : []));
// Every folder Drive has, and any a file names that the last look return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE);
// didn't reach (made since, or Drive unreachable).
const folders = [...new Set([...folderPaths, ...rows.map((r) => r.folder).filter(Boolean)])].sort((a, b) =>
a.localeCompare(b),
);
return c.json(
{ files: rows.map(shape), folders, ready: driveReady(), refused: [...refused.values()].map((r) => r.name) },
200,
NO_STORE,
);
}); });
files.post( files.post(
@ -257,12 +189,10 @@ files.post(
return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415); return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415);
} }
const name = safeName(file.name); const name = safeName(file.name);
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
let uploaded; let uploaded;
try { try {
uploaded = await driveUpload(inDrive(folder), name, mime, buffer); uploaded = await driveUpload(FOLDER, name, mime, buffer);
} catch (err) { } catch (err) {
console.warn(`files: upload of ${name} failed: ${err.message}`); console.warn(`files: upload of ${name} failed: ${err.message}`);
return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502); return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502);
@ -282,10 +212,15 @@ files.post(
); );
} }
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, user.id).lastInsertRowid;
const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id);
console.log(`files: ${name} uploaded by ${user.email}`); console.log(`files: ${name} uploaded by ${user.email}`);
// The first preview try is waited for; Drive often has it already.
const saved = await recordDriveUpload(db, uploaded, { name, mime, bytes: buffer.length, folder, userId: user.id }); // The first try is waited for; Drive often has the picture already.
return c.json({ file: saved }, 201, NO_STORE); await fetchPreview(db, row, user.id);
return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE);
}, },
); );
@ -294,86 +229,6 @@ function findOr404(c) {
return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null; return Number.isInteger(id) ? c.get("db").prepare(`SELECT * FROM drive_files WHERE id = ?`).get(id) : null;
} }
/* ── Folders ────────────────────────────────────────────────── */
const pathOf = async (c, from = "json") => {
const body = from === "json" ? ((await c.req.json().catch(() => null)) ?? {}) : { path: c.req.query("path") };
return { body, path: cleanFolder(body.path) };
};
files.post("/files/folders", requireRole("editor"), async (c) => {
const { path } = await pathOf(c);
if (!path) return c.json({ error: "Give the folder a name." }, 422);
try {
await driveFolder(inDrive(path));
} catch (err) {
return c.json({ error: `Google Drive didn't make it: ${err.message}` }, 502);
}
await pickUp(c.get("db"), true);
console.log(`files: folder ${path} made by ${c.get("user").email}`);
return c.json({ path }, 201, NO_STORE);
});
files.patch("/files/folders", requireRole("editor"), async (c) => {
const { body, path } = await pathOf(c);
const name = cleanFolder(body.name);
if (!path) return c.json({ error: "Which folder?" }, 422);
if (!name || name.includes("/")) return c.json({ error: "Give it a new name (no slashes)." }, 422);
const renamed = [...path.split("/").slice(0, -1), name].join("/");
const db = c.get("db");
try {
await driveRename(await driveFolder(inDrive(path)), name);
} catch (err) {
return c.json({ error: `Google Drive didn't rename it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
// The folder and everything under it.
db.prepare(
`UPDATE drive_files SET folder = ? || substr(folder, ?) WHERE folder = ? OR folder LIKE ? ESCAPE '\\'`,
).run(renamed, path.length + 1, path, `${path.replace(/[\\%_]/g, "\\$&")}/%`);
await pickUp(db, true);
console.log(`files: folder ${path} renamed to ${renamed} by ${c.get("user").email}`);
return c.json({ path: renamed }, 200, NO_STORE);
});
files.delete("/files/folders", requireRole("admin"), async (c) => {
const { path } = await pathOf(c, "query");
if (!path) return c.json({ error: "Which folder?" }, 422);
const db = c.get("db");
let id;
try {
id = await driveFolder(inDrive(path));
if (!(await driveFolderEmpty(id))) {
return c.json({ error: "That folder isn't empty: move or delete what's in it first." }, 409);
}
await driveDelete(id);
} catch (err) {
return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
forgetFolders(inDrive(path));
await pickUp(db, true);
console.log(`files: folder ${path} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
files.patch("/files/:id", requireRole("editor"), async (c) => {
const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404);
const body = (await c.req.json().catch(() => null)) ?? {};
const folder = cleanFolder(body.folder);
if (folder === null) return c.json({ error: "That isn't a folder name." }, 422);
if (folder !== row.folder) {
try {
await driveMove(row.drive_id, await driveFolder(inDrive(row.folder)), await driveFolder(inDrive(folder)));
} catch (err) {
return c.json({ error: `Google Drive didn't move it: ${err.message}` }, 502);
}
c.get("db").prepare(`UPDATE drive_files SET folder = ? WHERE id = ?`).run(folder, row.id);
console.log(`files: ${row.name} moved to ${folder || FOLDER} by ${c.get("user").email}`);
}
return c.json({ file: shape(c.get("db").prepare(`${SELECT} WHERE f.id = ?`).get(row.id)) }, 200, NO_STORE);
});
files.get("/files/:id/uses", (c) => { files.get("/files/:id/uses", (c) => {
const row = findOr404(c); const row = findOr404(c);
if (!row) return c.json({ error: "No such file." }, 404); if (!row) return c.json({ error: "No such file." }, 404);

View file

@ -2,15 +2,13 @@
MEDIA ROUTES: mounted under /api/admin MEDIA ROUTES: mounted under /api/admin
GET /media the library, newest first, ?q=name, GET /media the library, newest first, ?q=name,
?type=image|video|audio, ?type=image|video|audio.
?folder=logos|images|thumbnails.
Picks up images copied into the Picks up images copied into the
uploads folder by hand first uploads folder by hand first
(registerLooseFiles, at most every (registerLooseFiles, at most every
SCAN_EVERY_MS) SCAN_EVERY_MS)
POST /media upload one image (multipart: file, POST /media upload one image (multipart: file,
keep_original, folder: FOLDERS in keep_original)
media.js, default images)
GET /media/:id/uses which records name this file GET /media/:id/uses which records name this file
DELETE /media/:id remove the row and the file DELETE /media/:id remove the row and the file
POST /link-preview a page's title, description and POST /link-preview a page's title, description and
@ -31,11 +29,9 @@ import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js"; import { requireAuth, requireRole } from "../auth.js";
import { import {
FOLDERS,
MAX_UPLOAD_BYTES, MAX_UPLOAD_BYTES,
MediaError, MediaError,
PUBLIC_PREFIX, PUBLIC_PREFIX,
publicPath,
registerLooseFiles, registerLooseFiles,
remove, remove,
store, store,
@ -58,13 +54,12 @@ let lastScan = 0;
/* Tables that can't hold an image path, or mustn't be searched. */ /* Tables that can't hold an image path, or mustn't be searched. */
const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]); const NOT_CONTENT = new Set(["media", "drive_files", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
export function shape(row) { function shape(row) {
return { return {
id: row.id, id: row.id,
// A hand-copied file keeps its own name, which may need escaping // A hand-copied file keeps its own name, which may need escaping
// in a URL (a space, say); uploads' random names never do. // in a URL (a space, say); uploads' random names never do.
url: publicPath(row.filename), url: `${PUBLIC_PREFIX}${encodeURIComponent(row.filename)}`,
folder: row.filename.includes("/") ? row.filename.split("/")[0] : null,
original_name: row.original_name, original_name: row.original_name,
content_type: row.content_type, content_type: row.content_type,
bytes: row.bytes, bytes: row.bytes,
@ -82,8 +77,8 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e
/* Writes the file, then its row; a failed insert takes the file /* Writes the file, then its row; a failed insert takes the file
back out so nothing is left on disk that the library can't see. */ back out so nothing is left on disk that the library can't see. */
export async function addToLibrary(db, buf, { originalName, keepOriginal, userId, folder }) { export async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
const stored = await store(buf, { keepOriginal, folder }); const stored = await store(buf, { keepOriginal });
try { try {
const { lastInsertRowid } = db const { lastInsertRowid } = db
.prepare( .prepare(
@ -118,8 +113,7 @@ media.get("/media", async (c) => {
// ?type=image (what image fields pick from), video or audio // ?type=image (what image fields pick from), video or audio
// (clips saved from Tools → Video clips); none lists everything. // (clips saved from Tools → Video clips); none lists everything.
const type = ["image", "video", "audio"].includes(c.req.query("type")) ? c.req.query("type") : null; const type = ["image", "video", "audio"].includes(c.req.query("type")) ? c.req.query("type") : null;
const folder = FOLDERS.includes(c.req.query("folder")) ? c.req.query("folder") : null; const where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?"].filter(Boolean);
const where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?", folder && "m.filename LIKE ?"].filter(Boolean);
const rows = c const rows = c
.get("db") .get("db")
.prepare( .prepare(
@ -128,7 +122,7 @@ media.get("/media", async (c) => {
ORDER BY m.created_at DESC, m.id DESC ORDER BY m.created_at DESC, m.id DESC
LIMIT ${MAX_LIST}`, LIMIT ${MAX_LIST}`,
) )
.all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []), ...(folder ? [`${folder}/%`] : [])); .all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []));
return c.json({ media: rows.map(shape) }, 200, NO_STORE); return c.json({ media: rows.map(shape) }, 200, NO_STORE);
}); });
@ -157,7 +151,6 @@ media.post(
const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), { const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
originalName: file.name, originalName: file.name,
keepOriginal: body.keep_original === "1", keepOriginal: body.keep_original === "1",
folder: body.folder,
userId: user.id, userId: user.id,
}); });
@ -186,7 +179,6 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
try { try {
const row = await addToLibrary(c.get("db"), await fetchImage(page.image), { const row = await addToLibrary(c.get("db"), await fetchImage(page.image), {
originalName: `preview ${new URL(page.image).hostname}`, originalName: `preview ${new URL(page.image).hostname}`,
folder: "thumbnails",
keepOriginal: false, keepOriginal: false,
userId: user.id, userId: user.id,
}); });
@ -214,7 +206,6 @@ function usesOf(db, filename) {
return recordsNaming(db, [ return recordsNaming(db, [
`${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${filename}`,
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
publicPath(filename),
filename, filename,
]); ]);
} }

View file

@ -22,7 +22,6 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { asBool, json, loadOwned, marks, paragraphs, splitLinks } from "../shape.js"; import { asBool, json, loadOwned, marks, paragraphs, splitLinks } from "../shape.js";
import { postsBy } from "./blog.js";
const people = new Hono(); const people = new Hono();
@ -285,8 +284,6 @@ people.get("/people/:id", (c) => {
roles, roles,
events: [...byEvent.values()], events: [...byEvent.values()],
awards, awards,
// Blog posts they wrote (published and listed).
posts: postsBy(db, id),
}, },
}); });
}); });

View file

@ -39,43 +39,9 @@ const CATEGORIES = {
}; };
const LIMITS = { name: 120, email: 254, subject: 200, message: 5000 }; const LIMITS = { name: 120, email: 254, subject: 200, message: 5000 };
// details (049): at most this many keys, each value this long.
const MAX_DETAILS = 30;
const MAX_DETAIL = 2000;
/* The form's details as a JSON object of short strings, or null.
Which keys exist is the client's (requestTypes.ts); anything that
isn't a plain key with a string value is dropped, as are blanks. */
export function cleanDetails(raw) {
let parsed;
try {
parsed = JSON.parse(raw || "null");
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
const out = {};
for (const [key, value] of Object.entries(parsed).slice(0, MAX_DETAILS)) {
if (!/^[a-z_]{1,40}$/.test(key) || typeof value !== "string") continue;
const text = value.trim().slice(0, MAX_DETAIL);
if (text) out[key] = text;
}
return Object.keys(out).length ? out : null;
}
const MIN_MESSAGE = 10; const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js): a // Where in the shared drive the files go (googleService.js).
// folder per type under Requests, eg. Requests/Chapters. const DRIVE_FOLDER = "Requests";
export const DRIVE_FOLDER = "Requests";
export const TYPE_FOLDERS = {
blog: "Blog Posts",
event: "Events",
chapter: "Chapters",
region: "Regions",
partner: "Partners",
team: "Teams",
award: "Awards",
person: "People",
};
export const MAX_FILES = 3; export const MAX_FILES = 3;
export const MAX_FILE_BYTES = 10 * 1024 * 1024; export const MAX_FILE_BYTES = 10 * 1024 * 1024;
@ -121,7 +87,6 @@ requests.post(
const message = field("message", LIMITS.message); const message = field("message", LIMITS.message);
const name = field("name", LIMITS.name); const name = field("name", LIMITS.name);
const email = field("email", LIMITS.email); const email = field("email", LIMITS.email);
const details = cleanDetails(field("details", MAX_DETAILS * (MAX_DETAIL + 60)));
const files = [body.files ?? []].flat().filter((f) => f instanceof File && f.size > 0); const files = [body.files ?? []].flat().filter((f) => f instanceof File && f.size > 0);
const errors = {}; const errors = {};
@ -157,20 +122,10 @@ requests.post(
db db
.prepare( .prepare(
`INSERT INTO feedback `INSERT INTO feedback
(feedback_type, category, request_action, subject, details, message, name, email, user_agent, ip_hash) (feedback_type, category, request_action, subject, message, name, email, user_agent, ip_hash)
VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?, ?)`, VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
category,
action,
subject,
details ? JSON.stringify(details) : null,
message,
name || null,
email,
clean(c.req.header("user-agent"), 500) || null,
hashIp(clientIp(c)),
) )
.run(category, action, subject, message, name || null, email, clean(c.req.header("user-agent"), 500) || null, hashIp(clientIp(c)))
.lastInsertRowid, .lastInsertRowid,
); );
@ -179,7 +134,7 @@ requests.post(
const stored = []; const stored = [];
try { try {
for (const file of uploads) { for (const file of uploads) {
stored.push({ ...file, driveId: (await driveUpload(`${DRIVE_FOLDER}/${TYPE_FOLDERS[category]}`, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id }); stored.push({ ...file, driveId: (await driveUpload(DRIVE_FOLDER, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id });
} }
} catch (err) { } catch (err) {
console.warn(`feedback #${id}: Drive upload failed: ${err.message}`); console.warn(`feedback #${id}: Drive upload failed: ${err.message}`);
@ -198,7 +153,6 @@ requests.post(
`${action === "new" ? "New" : "Update"} ${category}: ${subject}`, `${action === "new" ? "New" : "Update"} ${category}: ${subject}`,
`From: ${name ? `${name} <${email}>` : email}`, `From: ${name ? `${name} <${email}>` : email}`,
...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []), ...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []),
...Object.entries(details ?? {}).map(([key, value]) => `${key.replace(/_/g, " ")}: ${value}`),
"", "",
message, message,
], ],

View file

@ -24,9 +24,8 @@
a fold-out of description, media, map); a fold-out of description, media, map);
text is an optional intro. ScheduleBlock text is an optional intro. ScheduleBlock
table text: a row per line, cells split by | table text: a row per line, cells split by |
cards items as link cards, up to three in a row: cards items as link cards: text the title,
text the title, detail, url, media the detail, url, media the picture
picture
divider nothing divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
@ -96,10 +95,10 @@ function LinkCard({ item }: { item: ContentBlockItem }) {
{!img.failed && ( {!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" /> <img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)} )}
<span className="flex flex-1 flex-col gap-1 p-4"> <span className="flex flex-1 flex-col gap-1 p-5">
<span className="truncate text-xs font-semibold text-muted">{where}</span> <span className="text-xs font-semibold text-muted">{where}</span>
<span className="font-display text-base font-bold leading-snug text-ink group-hover:text-link">{item.text}</span> <span className="font-display text-lg font-bold leading-snug text-ink group-hover:text-link">{item.text}</span>
{item.detail && <span className="line-clamp-3 text-sm leading-snug text-body">{item.detail}</span>} {item.detail && <span className="line-clamp-3 text-sm text-body">{item.detail}</span>}
</span> </span>
</Anchor> </Anchor>
) )
@ -225,9 +224,7 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
const cards = (block.items ?? []).filter((item) => item.url && item.text) const cards = (block.items ?? []).filter((item) => item.url && item.text)
if (cards.length === 0) return null if (cards.length === 0) return null
return ( return (
// One grid whatever the count: a lone card takes a column <ul className={cards.length === 1 ? 'max-w-xl' : 'grid gap-4 sm:grid-cols-2'}>
// rather than the width, and more sit up to three in a row.
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{cards.map((item, i) => ( {cards.map((item, i) => (
<li key={i}> <li key={i}>
<LinkCard item={item} /> <LinkCard item={item} />

View file

@ -11,9 +11,6 @@
or an icon for its type or an icon for its type
FilePicker the dialog behind a link field's "Choose a FilePicker the dialog behind a link field's "Choose a
file" (a field with `files: true`, fields.tsx) file" (a field with `files: true`, fields.tsx)
DriveFolderTabs a tab per folder under Media in Drive; both
the picker and the Files tab filter by it, and
upload into the one showing
A link field stores the file's Drive link, a plain URL, so nothing A link field stores the file's Drive link, a plain URL, so nothing
else needs to know where it came from. Files put in the Drive else needs to know where it came from. Files put in the Drive
@ -45,42 +42,10 @@ export type DriveFile = {
bytes: number; bytes: number;
url: string; url: string;
preview: string | null; preview: string | null;
/** Its folder under Media: "" for Media itself. */
folder: string;
uploaded_by: string | null; uploaded_by: string | null;
created_at: string; created_at: string;
}; };
/* Which tab: every file, Media's own (not in a folder), or a folder's. */
export const ALL_FOLDERS = "*";
export function inFolder(files: DriveFile[], tab: string) {
return tab === ALL_FOLDERS ? files : files.filter((f) => f.folder === tab);
}
export function DriveFolderTabs({ folders, value, onChange }: { folders: string[]; value: string; onChange: (tab: string) => void }) {
const tabs: [string, string][] = [[ALL_FOLDERS, "All"], ["", "Not in a folder"], ...folders.map((f): [string, string] => [f, f])];
return (
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
{tabs.map(([tab, label]) => (
<button
key={tab}
type="button"
role="tab"
aria-selected={value === tab}
onClick={() => onChange(tab)}
className={
"rounded-full px-3 py-1 text-sm transition-colors " +
(value === tab ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
}
>
{label}
</button>
))}
</div>
);
}
const button = const button =
"rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " + "rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " +
"transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"; "transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
@ -110,7 +75,6 @@ function TypeIcon({ mime }: { mime: string }) {
export function useDriveFiles(query: string) { export function useDriveFiles(query: string) {
const [items, setItems] = useState<DriveFile[] | null>(null); const [items, setItems] = useState<DriveFile[] | null>(null);
const [folders, setFolders] = useState<string[]>([]);
const [ready, setReady] = useState(true); const [ready, setReady] = useState(true);
// Files in the Drive folder that Drive wouldn't share publicly. // Files in the Drive folder that Drive wouldn't share publicly.
const [refused, setRefused] = useState<string[]>([]); const [refused, setRefused] = useState<string[]>([]);
@ -122,7 +86,6 @@ export function useDriveFiles(query: string) {
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
.then((data) => { .then((data) => {
setItems(data.files); setItems(data.files);
setFolders(data.folders ?? []);
setReady(data.ready); setReady(data.ready);
setRefused(data.refused ?? []); setRefused(data.refused ?? []);
}) })
@ -130,21 +93,12 @@ export function useDriveFiles(query: string) {
}, [query]); }, [query]);
useEffect(reload, [reload]); useEffect(reload, [reload]);
return { items, folders, ready, refused, error, reload, setItems }; return { items, ready, refused, error, reload, setItems };
} }
/* ── Upload ──────────────────────────────────────────────────── */ /* ── Upload ──────────────────────────────────────────────────── */
export function FileUploadButton({ export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) {
onUploaded,
label = "Upload files",
folder = "",
}: {
onUploaded: (file: DriveFile) => void;
label?: string;
/** Under Media; "" for Media itself. */
folder?: string;
}) {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState<string | null>(null); const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -158,7 +112,6 @@ export function FileUploadButton({
setBusy(file.name); setBusy(file.name);
const form = new FormData(); const form = new FormData();
form.append("file", file); form.append("file", file);
form.append("folder", folder);
try { try {
onUploaded((await upload("/admin/files", form)).file); onUploaded((await upload("/admin/files", form)).file);
} catch (err) { } catch (err) {
@ -253,8 +206,7 @@ export function FilePicker({
}) { }) {
const { user } = useAuth(); const { user } = useAuth();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const { items, folders, ready, refused, error, setItems } = useDriveFiles(query); const { items, ready, refused, error, setItems } = useDriveFiles(query);
const [tab, setTab] = useState(ALL_FOLDERS);
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => { useEffect(() => {
@ -273,7 +225,7 @@ export function FilePicker({
onClick={(e) => { onClick={(e) => {
if (e.target === dialogRef.current) dialogRef.current?.close(); if (e.target === dialogRef.current) dialogRef.current?.close();
}} }}
className="m-auto w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" className="w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40"
> >
<div className="flex max-h-[85vh] flex-col"> <div className="flex max-h-[85vh] flex-col">
<div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4"> <div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4">
@ -295,17 +247,10 @@ export function FilePicker({
</button> </button>
</div> </div>
{folders.length > 0 && (
<div className="border-b border-brand/10 px-5 py-3">
<DriveFolderTabs folders={folders} value={tab} onChange={setTab} />
</div>
)}
{roleCanWrite(user) && ready && ( {roleCanWrite(user) && ready && (
<div className="border-b border-brand/10 px-5 py-3"> <div className="border-b border-brand/10 px-5 py-3">
<FileUploadButton <FileUploadButton
label={tab && tab !== ALL_FOLDERS ? `Upload into ${tab}` : "Upload new"} label="Upload new"
folder={tab === ALL_FOLDERS ? "" : tab}
onUploaded={(file) => { onUploaded={(file) => {
setItems((current) => [file, ...(current ?? [])]); setItems((current) => [file, ...(current ?? [])]);
pick(file); pick(file);
@ -323,7 +268,7 @@ export function FilePicker({
) : items === null ? ( ) : items === null ? (
<p className="text-sm text-muted">Loading…</p> <p className="text-sm text-muted">Loading…</p>
) : ( ) : (
<FileList items={inFolder(items, tab)} selected={selected} onPick={pick} /> <FileList items={items} selected={selected} onPick={pick} />
)} )}
</div> </div>
</div> </div>

View file

@ -6,10 +6,7 @@
ImageInput the `widget: "image"` form field. A preview, the ImageInput the `widget: "image"` form field. A preview, the
stored value as editable text, and buttons to stored value as editable text, and buttons to
upload a new file or pick an earlier one. upload a new file or pick an earlier one.
MediaPicker the dialog behind "Choose from library". Its From MediaPicker the dialog behind "Choose from library".
requests tab lists photos sent with the Request
form (in Drive); picking one copies it into the
library first (RequestImages).
MediaGrid the thumbnails both the picker and the Media page MediaGrid the thumbnails both the picker and the Media page
(pages/admin/AdminMedia.tsx) draw. (pages/admin/AdminMedia.tsx) draw.
UploadButton a file input dressed as a button, with the UploadButton a file input dressed as a button, with the
@ -20,11 +17,6 @@
description and preview image (the image lands in description and preview image (the image lands in
the library) and fills the row's empty fields. the library) and fills the row's empty fields.
Images live in folders by what they're for (FOLDERS in
server/src/media.js): Logos, Images, and Previews the site saved
itself. A field's `folder` says where its uploads go (logo fields:
"logos"; default "images"), and its picker opens on that tab.
An image field stores a path, not a media id: '/uploads/<file>' 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 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 public/ directory or a full URL. So the text box stays: old
@ -40,8 +32,6 @@
import { FileAudio, X } from "@phosphor-icons/react"; import { FileAudio, X } from "@phosphor-icons/react";
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useLocation } from "react-router-dom";
import { ApiError, get, post, upload } from "../../lib/api.ts"; import { ApiError, get, post, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite } from "../../lib/roles.ts"; import { canWrite as roleCanWrite } from "../../lib/roles.ts";
@ -57,51 +47,8 @@ export type MediaItem = {
processed: boolean; processed: boolean;
uploaded_by: string | null; uploaded_by: string | null;
created_at: string; created_at: string;
/** logos, images or thumbnails; null for clips and older files in the root. */
folder: string | null;
}; };
/* The folder tabs, as [folder, label]; "" is every image. */
export const IMAGE_FOLDERS = [
["", "All"],
["logos", "Logos"],
["images", "Images"],
["thumbnails", "Previews"],
] as const;
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
/* A tab strip over the folders; `value` is the one showing. `extra`
adds tabs after them (the picker's From requests). */
export function FolderTabs({
value,
onChange,
extra = [],
}: {
value: string;
onChange: (folder: string) => void;
extra?: [string, string][];
}) {
return (
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
{[...IMAGE_FOLDERS, ...extra].map(([folder, label]) => (
<button
key={folder}
type="button"
role="tab"
aria-selected={value === folder}
onClick={() => onChange(folder)}
className={
"rounded-full px-3 py-1 text-sm transition-colors " +
(value === folder ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
}
>
{label}
</button>
))}
</div>
);
}
const button = const button =
"rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " + "rounded-full border border-brand px-3 py-1 text-sm font-medium text-link " +
"transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"; "transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
@ -130,18 +77,17 @@ export function mediaSize(item: MediaItem) {
/* ── Data ────────────────────────────────────────────────────── */ /* ── Data ────────────────────────────────────────────────────── */
export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise<MediaItem> { export function uploadImage(file: File, keepOriginal: boolean): Promise<MediaItem> {
const form = new FormData(); const form = new FormData();
form.append("file", file); form.append("file", file);
if (keepOriginal) form.append("keep_original", "1"); if (keepOriginal) form.append("keep_original", "1");
if (folder) form.append("folder", folder);
return upload("/admin/media", form).then((data) => data.media); return upload("/admin/media", form).then((data) => data.media);
} }
/* `type` narrows to one kind of file: image fields pick images only. /* `type` narrows to one kind of file: image fields pick images only.
Blank lists everything, videos and audio saved from the clip tool Blank lists everything, videos and audio saved from the clip tool
included. */ included. */
export function useMediaLibrary(query: string, type?: "image" | "video" | "audio", folder?: string) { export function useMediaLibrary(query: string, type?: "image" | "video" | "audio") {
const [items, setItems] = useState<MediaItem[] | null>(null); const [items, setItems] = useState<MediaItem[] | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -150,14 +96,13 @@ export function useMediaLibrary(query: string, type?: "image" | "video" | "audio
const params = new URLSearchParams(); const params = new URLSearchParams();
if (q) params.set("q", q); if (q) params.set("q", q);
if (type) params.set("type", type); if (type) params.set("type", type);
if (folder) params.set("folder", folder);
setError(null); setError(null);
get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 }) get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 })
.then((data) => setItems(data.media)) .then((data) => setItems(data.media))
.catch((err) => .catch((err) =>
setError(err instanceof ApiError ? err.message : "Couldn't load the library."), setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
); );
}, [query, type, folder]); }, [query, type]);
useEffect(reload, [reload]); useEffect(reload, [reload]);
@ -170,13 +115,10 @@ export function UploadButton({
onUploaded, onUploaded,
multiple = false, multiple = false,
label = "Upload", label = "Upload",
folder,
}: { }: {
onUploaded: (item: MediaItem) => void; onUploaded: (item: MediaItem) => void;
multiple?: boolean; multiple?: boolean;
label?: string; label?: string;
/** Where it goes; blank: the server's default, images. */
folder?: string;
}) { }) {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const keepId = useId(); const keepId = useId();
@ -193,7 +135,7 @@ export function UploadButton({
// name the file it happened to. // name the file it happened to.
for (const file of Array.from(files)) { for (const file of Array.from(files)) {
try { try {
onUploaded(await uploadImage(file, keepOriginal, folder)); onUploaded(await uploadImage(file, keepOriginal));
} catch (err) { } catch (err) {
const why = err instanceof ApiError ? err.message : "Upload failed."; const why = err instanceof ApiError ? err.message : "Upload failed.";
setError(files.length > 1 ? `${file.name}: ${why}` : why); setError(files.length > 1 ? `${file.name}: ${why}` : why);
@ -319,94 +261,20 @@ export function MediaGrid({
); );
} }
/* ── Photos sent with requests ───────────────────────────────── */
const REQUESTS_TAB = "requests";
/* Photos from the Request form, which live in Drive: the one being
edited from first (Forms → Content requests → Create from this),
then newest. Picking one copies it into the library, into the
field's folder, and that copy is what the field gets. */
function RequestImages({ folder, onPick }: { folder?: string; onPick: (item: MediaItem) => void }) {
const current = (useLocation().state as any)?.fromRequest?.request ?? null;
const [files, setFiles] = useState<any[] | null>(null);
const [busy, setBusy] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
get("/admin/request-files", { ttl: 0 })
.then((data) => {
const photos = data.files.filter((f) => f.mime.startsWith("image/") && !f.missing);
setFiles([...photos.filter((f) => f.feedback_id === current), ...photos.filter((f) => f.feedback_id !== current)]);
})
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files."));
}, [current]);
async function pick(file) {
setBusy(file.id);
setError(null);
try {
const { media } = await post(`/admin/feedback/${file.feedback_id}/files/${file.id}/to-library`, { folder });
onPick(media);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't copy it into the library.");
setBusy(null);
}
}
if (error && !files) return <p className="text-sm text-danger">{error}</p>;
if (!files) return <p className="text-sm text-muted">Loading…</p>;
if (files.length === 0) return <p className="text-sm text-muted">No photos have come in with requests.</p>;
return (
<>
{error && <p className="mb-3 text-sm text-danger">{error}</p>}
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{files.map((file) => (
<li key={file.id} className="rounded-xl border border-muted/20 bg-surface p-2">
<button type="button" disabled={busy !== null} onClick={() => pick(file)} className="block w-full text-left disabled:opacity-60">
<div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}>
{/* Straight from Drive through the server; private to the admin. */}
<img
src={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
alt=""
loading="lazy"
className="h-full w-full object-contain"
/>
</div>
<p className="mt-1.5 truncate text-xs font-medium text-body" title={file.name}>
{busy === file.id ? "Copying…" : file.name}
</p>
<p className="truncate text-xs text-muted/80">
{file.feedback_id === current ? "This request" : `Request #${file.feedback_id}`}
{file.subject ? `: ${file.subject}` : ""}
</p>
</button>
</li>
))}
</ul>
</>
);
}
/* ── Picker dialog ───────────────────────────────────────────── */ /* ── Picker dialog ───────────────────────────────────────────── */
export function MediaPicker({ export function MediaPicker({
selected, selected,
folder = "images",
onPick, onPick,
onClose, onClose,
}: { }: {
selected?: string | null; selected?: string | null;
/** The field's folder: the tab it opens on, where uploads go. */
folder?: string;
onPick: (item: MediaItem) => void; onPick: (item: MediaItem) => void;
onClose: () => void; onClose: () => void;
}) { }) {
const { user } = useAuth(); const { user } = useAuth();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [tab, setTab] = useState<string>(folder); const { items, error, setItems } = useMediaLibrary(query, "image");
const fromRequests = tab === REQUESTS_TAB;
const { items, error, setItems } = useMediaLibrary(query, "image", fromRequests ? undefined : tab);
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free. // showModal gives focus trapping, Escape and the backdrop for free.
@ -422,7 +290,7 @@ export function MediaPicker({
// A click on the backdrop lands on the dialog itself. // A click on the backdrop lands on the dialog itself.
if (e.target === dialogRef.current) dialogRef.current?.close(); if (e.target === dialogRef.current) dialogRef.current?.close();
}} }}
className="m-auto w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" 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 max-h-[85vh] flex-col">
<div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4"> <div className="flex flex-wrap items-center gap-3 border-b border-brand/15 px-5 py-4">
@ -444,15 +312,10 @@ export function MediaPicker({
</button> </button>
</div> </div>
<div className="border-b border-brand/10 px-5 py-3">
<FolderTabs value={tab} onChange={setTab} extra={[[REQUESTS_TAB, "From requests"]]} />
</div>
{roleCanWrite(user) && ( {roleCanWrite(user) && (
<div className="border-b border-brand/10 px-5 py-3"> <div className="border-b border-brand/10 px-5 py-3">
<UploadButton <UploadButton
label="Upload new" label="Upload new"
folder={folder}
onUploaded={(item) => { onUploaded={(item) => {
setItems((current) => [item, ...(current ?? [])]); setItems((current) => [item, ...(current ?? [])]);
onPick(item); onPick(item);
@ -464,16 +327,7 @@ export function MediaPicker({
)} )}
<div className="overflow-y-auto px-5 py-4"> <div className="overflow-y-auto px-5 py-4">
{fromRequests ? ( {error ? (
<RequestImages
folder={folder}
onPick={(item) => {
setItems((current) => [item, ...(current ?? []).filter((m) => m.id !== item.id)]);
onPick(item);
dialogRef.current?.close();
}}
/>
) : error ? (
<p className="text-sm text-danger">{error}</p> <p className="text-sm text-danger">{error}</p>
) : items === null ? ( ) : items === null ? (
<p className="text-sm text-muted">Loading…</p> <p className="text-sm text-muted">Loading…</p>
@ -499,7 +353,6 @@ export function ImageInput({
id, id,
value, value,
resolve, resolve,
folder,
locked, locked,
className, className,
onChange, onChange,
@ -507,8 +360,6 @@ export function ImageInput({
id: string; id: string;
value: string | null | undefined; value: string | null | undefined;
resolve?: (file?: string | null) => string | null; resolve?: (file?: string | null) => string | null;
/** The field's `folder` (logos for logo fields); default images. */
folder?: string;
locked: boolean; locked: boolean;
className: string; className: string;
onChange: (value: string) => void; onChange: (value: string) => void;
@ -548,7 +399,7 @@ export function ImageInput({
/> />
{editable && ( {editable && (
<div className="flex flex-wrap items-start gap-2"> <div className="flex flex-wrap items-start gap-2">
<UploadButton folder={folder} onUploaded={(item) => onChange(item.url)} /> <UploadButton onUploaded={(item) => onChange(item.url)} />
<button type="button" className={button} onClick={() => setPicking(true)}> <button type="button" className={button} onClick={() => setPicking(true)}>
Choose from library Choose from library
</button> </button>
@ -568,7 +419,6 @@ export function ImageInput({
{picking && ( {picking && (
<MediaPicker <MediaPicker
selected={value} selected={value}
folder={folder}
onPick={(item) => onChange(item.url)} onPick={(item) => onChange(item.url)}
onClose={() => setPicking(false)} onClose={() => setPicking(false)}
/> />

View file

@ -69,9 +69,7 @@
`widget: "image"` is a text box with a preview and upload and `widget: "image"` is a text box with a preview and upload and
library buttons beside it (ImageInput in MediaLibrary.tsx). Its library buttons beside it (ImageInput in MediaLibrary.tsx). Its
`resolve` option is the media.ts helper for the field's public/ `resolve` option is the media.ts helper for the field's public/
directory, so a bare filename previews from the right place. Its directory, so a bare filename previews from the right place.
`folder` ("logos" for logo and icon fields) is where uploads go and
the tab the library opens on.
Two options change the box itself rather than what goes in it: Two options change the box itself rather than what goes in it:
@ -349,7 +347,6 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
id={id} id={id}
value={value} value={value}
resolve={field.resolve} resolve={field.resolve}
folder={field.folder}
locked={locked} locked={locked}
className={locked ? inputLocked : common.className} className={locked ? inputLocked : common.className}
onChange={onChange} onChange={onChange}

View file

@ -9,230 +9,29 @@
A link can open the form on one: requestLink("chapter") is A link can open the form on one: requestLink("chapter") is
/request?type=chapter. People, teams and awards have no buttons on /request?type=chapter. People, teams and awards have no buttons on
the site, but are here to pick. the site, but are here to pick.
`fields` are the details the form asks for on top of the name and
message, stored together as JSON on the request (feedback.details,
049). Only here: the server keeps whatever keys come, so adding a
field is a change to this file alone. Each field's `to` says where
it goes when Forms → Content requests opens the record's editor
from the request (EntityEdit's fromRequest):
{ path } a field in the editor, eg. "locality"
{ link, label } a row in the record's links
{ block: "card" } a paragraph of the record's description
(none) shown in the admin only, eg. a region's
name, which the admin picks by hand
`entity` is the admin record it becomes, `preset` the values a new
one starts with (a chapter is an organization of kind chapter), and
`heading` the editor field the request's name fills.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
export type RequestAction = "new" | "update"; export type RequestAction = "new" | "update";
export type RequestField = { export const REQUEST_TYPES: {
key: string;
label: string;
input?: "text" | "date" | "url" | "email" | "textarea";
placeholder?: string;
to?: { path: string } | { link: "website" | "email" | "action"; label: string } | { block: "card" };
};
export type RequestType = {
id: string; id: string;
label: string; label: string;
hint: string; hint: string;
actions: RequestAction[]; actions: RequestAction[];
// What the name field asks, for a new one and for an update. // What the name field asks, for a new one and for an update.
subject: string; subject: string;
entity: string; }[] = [
heading: string; { id: "blog", label: "Blog post", hint: "A story or article for the community blog", actions: ["new"], subject: "Its title" },
preset?: Record<string, string>; { id: "event", label: "Event", hint: "A retreat, gathering or calendar event", actions: ["new", "update"], subject: "The event's name" },
fields: RequestField[]; { id: "chapter", label: "Chapter", hint: "A local NGU chapter", actions: ["new", "update"], subject: "The chapter's name" },
}; { id: "region", label: "Region", hint: "Details for a Unity region", actions: ["update"], subject: "Which region" },
{ id: "partner", label: "Partner", hint: "A partner organization", actions: ["new", "update"], subject: "The organization's name" },
const CITY: RequestField = { key: "city", label: "City", to: { path: "locality" } }; { id: "team", label: "Team", hint: "A team or committee", actions: ["new", "update"], subject: "The team's name" },
const STATE: RequestField = { key: "state", label: "State or province", placeholder: "eg. MO", to: { path: "state_code" } }; { id: "award", label: "Award", hint: "An award and who received it", actions: ["new", "update"], subject: "The award's name" },
const COUNTRY: RequestField = { key: "country", label: "Country", placeholder: "eg. US", to: { path: "country" } }; { id: "person", label: "Person", hint: "Someone's profile", actions: ["new", "update"], subject: "Their name" },
const WEBSITE: RequestField = { key: "website", label: "Website", input: "url", placeholder: "https://", to: { link: "website", label: "Website" } };
const EMAIL: RequestField = { key: "email", label: "Contact email", input: "email", to: { link: "email", label: "Email" } };
const DESCRIPTION: RequestField = { key: "description", label: "Short description", input: "textarea", to: { block: "card" } };
export const REQUEST_TYPES: RequestType[] = [
{
id: "blog",
label: "Blog post",
hint: "A story or article for the community blog",
actions: ["new"],
subject: "Its title",
entity: "blog_posts",
heading: "title",
fields: [
{ key: "author", label: "Author's name, as it should appear", to: { path: "guest_author" } },
{ key: "excerpt", label: "A line or two for the post's card", input: "textarea", to: { path: "excerpt" } },
],
},
{
id: "event",
label: "Event",
hint: "A retreat, gathering or calendar event",
actions: ["new", "update"],
subject: "The event's name",
entity: "events",
heading: "title",
fields: [
{ key: "starts_on", label: "Starts", input: "date", to: { path: "starts_on" } },
{ key: "ends_on", label: "Ends", input: "date", to: { path: "ends_on" } },
{ key: "venue", label: "Venue", placeholder: "eg. Unity Village", to: { path: "venue" } },
CITY,
STATE,
{ key: "register", label: "Registration link", input: "url", placeholder: "https://", to: { link: "action", label: "Register" } },
DESCRIPTION,
],
},
{
id: "chapter",
label: "Chapter",
hint: "A local NGU chapter",
actions: ["new", "update"],
subject: "The chapter's name",
entity: "organizations",
heading: "name",
preset: { kind: "chapter" },
fields: [
{ key: "region", label: "Region it's in", placeholder: "eg. Great Lakes" },
CITY,
STATE,
COUNTRY,
{ key: "meets", label: "When it meets", placeholder: "eg. 2nd Sundays, 6:00pm", to: { path: "chapter.meets" } },
WEBSITE,
EMAIL,
DESCRIPTION,
],
},
{
id: "region",
label: "Region",
hint: "Details for a Unity region",
actions: ["update"],
subject: "Which region",
entity: "organizations",
heading: "name",
preset: { kind: "region" },
fields: [WEBSITE, EMAIL, DESCRIPTION],
},
{
id: "partner",
label: "Partner",
hint: "A partner organization",
actions: ["new", "update"],
subject: "The organization's name",
entity: "organizations",
heading: "name",
preset: { kind: "partner" },
fields: [CITY, STATE, COUNTRY, WEBSITE, EMAIL, DESCRIPTION],
},
{
id: "team",
label: "Team",
hint: "A team or committee",
actions: ["new", "update"],
subject: "The team's name",
entity: "teams",
heading: "name",
fields: [
{ key: "organization", label: "Which organization it belongs to", placeholder: "eg. NGU national" },
{ key: "tagline", label: "What it does, in a line", to: { path: "tagline" } },
EMAIL,
DESCRIPTION,
],
},
{
id: "award",
label: "Award",
hint: "An award and who received it",
actions: ["new", "update"],
subject: "The award's name",
entity: "awards",
heading: "name",
fields: [
{ key: "organization", label: "Who gives it", placeholder: "eg. NGU national" },
{ key: "description", label: "What it's for", input: "textarea", to: { path: "description" } },
{ key: "recipients", label: "Who received it, and when", input: "textarea" },
],
},
{
id: "person",
label: "Person",
hint: "Someone's profile",
actions: ["new", "update"],
subject: "Their name",
entity: "people",
heading: "display_name",
fields: [
{ key: "pronouns", label: "Pronouns", placeholder: "eg. she/her", to: { path: "pronouns" } },
{ key: "tagline", label: "Role or title", to: { path: "tagline" } },
CITY,
STATE,
{ key: "email", label: "Public email", input: "email", to: { path: "public_email" } },
WEBSITE,
{ key: "bio", label: "Short bio", input: "textarea", to: { path: "bio" } },
],
},
]; ];
export const requestLink = (type: string) => `/request?type=${type}`; export const requestLink = (type: string) => `/request?type=${type}`;
const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t])); const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t.label]));
export const requestType = (id: string) => BY_ID.get(id); export const requestTypeLabel = (id: string) => BY_ID.get(id) ?? id;
export const requestTypeLabel = (id: string) => BY_ID.get(id)?.label ?? id;
/* ── Into the admin editor ─────────────────────────────────────── */
/* What EntityEdit applies from a request (location.state.fromRequest):
`set` fields by path, `add` child rows (links, a description
paragraph). A new record gets all of it; an existing one lists each
beside its current value to use or skip. */
export type FromRequest = {
request: number;
set: { path: string; label: string; value: string }[];
add: { child: string; label: string; row: Record<string, unknown> }[];
};
export function fromRequest(
row: { id: number; category: string; request_action: string; subject?: string | null; details?: Record<string, string> | null },
): FromRequest | null {
const type = requestType(row.category);
if (!type) return null;
const details = row.details ?? {};
const set: FromRequest["set"] = [];
const add: FromRequest["add"] = [];
if (row.request_action === "new") {
for (const [path, value] of Object.entries(type.preset ?? {})) set.push({ path, label: path, value });
if (row.subject) set.push({ path: type.heading, label: "Name", value: row.subject });
}
for (const field of type.fields) {
const value = details[field.key]?.trim();
if (!value || !field.to) continue;
if ("path" in field.to) set.push({ path: field.to.path, label: field.label, value });
else if ("link" in field.to) {
add.push({
child: "links",
label: `${field.label}: ${value}`,
row: {
kind: field.to.link,
label: field.to.label,
url: field.to.link === "email" && !value.startsWith("mailto:") ? `mailto:${value}` : value,
is_primary: 0,
},
});
} else {
add.push({
child: "content_blocks",
label: `${field.label} (a paragraph)`,
row: { slot: field.to.block, type: "paragraph", text: value, items: [] },
});
}
}
return { request: row.id, set, add };
}

View file

@ -42,7 +42,7 @@ export 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", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true },
], ],
}, },
{ {

View file

@ -144,8 +144,8 @@ export const events = {
{ {
legend: "Appearance", legend: "Appearance",
fields: [ fields: [
{ path: "event_logo", label: "Event logo", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "event_logo", label: "Event logo", widget: "image", resolve: mediaUrl, full: true },
{ path: "org_logo", label: "Org logo override", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "org_logo", label: "Org logo override", widget: "image", resolve: mediaUrl, full: true },
{ path: "color", label: "Colour", widget: "color" }, { path: "color", label: "Colour", widget: "color" },
{ {
path: "card_image", path: "card_image",

View file

@ -42,7 +42,7 @@ export 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", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true },
], ],
}, },
{ {

View file

@ -279,7 +279,7 @@ export const BLOCK_TYPES = [
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."], ["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."],
["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."], ["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."],
["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."], ["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."],
["cards", "Link cards", "Cards with a picture, title and description, each a link to a page or a file, like a link shared in a chat; up to three in a row. Paste a link and press Fetch preview, or Choose a file."], ["cards", "Link cards", "Cards with a picture, title and description, each a link, like a link shared in a chat. Paste a link and press Fetch preview."],
["divider", "Divider", "A thin line between parts."], ["divider", "Divider", "A thin line between parts."],
]; ];

View file

@ -80,7 +80,6 @@ export const siteSettings = {
path: "favicon", path: "favicon",
label: "Favicon", label: "Favicon",
widget: "image", widget: "image",
folder: "logos",
resolve: mediaUrl, resolve: mediaUrl,
full: true, full: true,
help: "The browser-tab icon: a square PNG (512px) or an SVG. Keep original when uploading an SVG.", help: "The browser-tab icon: a square PNG (512px) or an SVG. Keep original when uploading an SVG.",
@ -89,7 +88,6 @@ export const siteSettings = {
path: "apple_touch_icon", path: "apple_touch_icon",
label: "Home-screen icon", label: "Home-screen icon",
widget: "image", widget: "image",
folder: "logos",
resolve: mediaUrl, resolve: mediaUrl,
full: true, full: true,
help: "For iPhones saving the site to their home screen: a square PNG, 180px, no transparency.", help: "For iPhones saving the site to their home screen: a square PNG, 180px, no transparency.",

View file

@ -47,7 +47,7 @@ export 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", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true },
], ],
}, },
{ legend: "Publishing", fields: PUBLISH_FIELDS }, { legend: "Publishing", fields: PUBLISH_FIELDS },

View file

@ -11,7 +11,6 @@
* hrefs.ts has already logged the component that produced it. * hrefs.ts has already logged the component that produced it.
*/ */
import type { BlogPostSummary } from './useBlog.ts'
import { detailPath } from './hrefs.ts' import { detailPath } from './hrefs.ts'
import { useRecord, type Resource } from './useRecord.ts' import { useRecord, type Resource } from './useRecord.ts'
import type { EventType } from './eventTypes.ts' import type { EventType } from './eventTypes.ts'
@ -357,8 +356,6 @@ export type PersonRecord = {
roles: PersonRole[] roles: PersonRole[]
events: PersonEvent[] events: PersonEvent[]
awards: PersonAward[] awards: PersonAward[]
/** Blog posts they wrote, newest first. */
posts: BlogPostSummary[]
} }
export const usePerson = (id?: string): Resource<PersonRecord> => export const usePerson = (id?: string): Resource<PersonRecord> =>

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later. box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.14-content-display"; export const SITE_VERSION = "NGU-Web.v1.9.11-content-display";

View file

@ -24,7 +24,6 @@ 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 PlatformIcon from '../components/PlatformIcon.tsx'
import ContentBlocks from '../components/ContentBlocks.tsx' import ContentBlocks from '../components/ContentBlocks.tsx'
import { PostCard } from './sections/CommunityBlog.tsx'
import { import {
usePerson, usePerson,
type PersonEvent, type PersonEvent,
@ -191,24 +190,6 @@ export default function PersonDetail() {
}) })
} }
if (person.posts?.length > 0) {
sections.push({
id: 'posts',
title: 'Blog posts',
accent,
background: BACKGROUNDS[sections.length % 2],
content: (
<div className="max-w-6xl mx-auto px-6">
<ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{person.posts.map((post) => (
<PostCard key={post.id} post={post} accent={accent} />
))}
</ul>
</div>
),
})
}
return ( return (
<PageShell title={person.name} intro={person.tagline ?? undefined} sections={sections} /> <PageShell title={person.name} intro={person.tagline ?? undefined} sections={sections} />
) )

View file

@ -38,8 +38,6 @@ type Job = {
has_file: boolean; has_file: boolean;
saved_media_id: number | null; saved_media_id: number | null;
saved_url: string | null; saved_url: string | null;
/** In Drive, under Media (Save to Drive): its Files entry. */
saved_drive: { id: number; url: string; folder: string } | null;
downloaded_at: string | null; downloaded_at: string | null;
}; };
@ -89,80 +87,6 @@ const primary =
const input = const input =
"rounded-lg border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"; "rounded-lg border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
/* Save to Drive: a folder under Media (Tools → Media → Files), then
the clip goes there as a Files entry. Opens on a folder named for
the clip's kind (Videos, Audio) when there is one. */
function SaveToDrive({ clip, onSaved }: { clip: Job; onSaved: () => void }) {
const [folders, setFolders] = useState<string[] | null>(null);
const [folder, setFolder] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const audio = clip.params?.format === "audio";
async function open() {
setError(null);
try {
const data = await get("/admin/files", { ttl: 0 });
if (!data.ready) return setError("Google Drive isn't set up on the server.");
const list: string[] = data.folders ?? [];
setFolders(list);
const wanted = audio ? /^audio$/i : /^videos?$/i;
setFolder(list.find((f) => wanted.test(f)) ?? "");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't load the folders.");
}
}
async function save() {
setBusy(true);
setError(null);
try {
await post(`/admin/clips/${clip.id}/drive`, { folder });
onSaved();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't save it to Drive.");
setBusy(false);
}
}
return (
<>
{folders === null ? (
<button type="button" className={button} onClick={open}>
Save to Drive
</button>
) : (
<span className="flex flex-wrap items-center gap-2">
<label className="sr-only" htmlFor={`drive-folder-${clip.id}`}>
Folder in Drive
</label>
<select
id={`drive-folder-${clip.id}`}
value={folder}
disabled={busy}
onChange={(e) => setFolder(e.target.value)}
className="rounded-lg border border-muted/25 bg-surface px-2 py-1 text-sm text-body"
>
<option value="">Media (not in a folder)</option>
{folders.map((f) => (
<option key={f} value={f}>
Media/{f}
</option>
))}
</select>
<button type="button" className={button} disabled={busy} onClick={save}>
{busy ? "Uploading…" : "Save"}
</button>
<button type="button" className="text-sm" style={{ color: MUTED }} onClick={() => setFolders(null)}>
Cancel
</button>
</span>
)}
{error && <span className="text-sm text-danger">{error}</span>}
</>
);
}
function Card({ title, children }: { title: string; children: ReactNode }) { function Card({ title, children }: { title: string; children: ReactNode }) {
return ( return (
<section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5"> <section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5">
@ -491,26 +415,6 @@ export default function AdminClips() {
{openId === s.id ? "Close" : "Make clips"} {openId === s.id ? "Close" : "Make clips"}
</button> </button>
)} )}
{/* The whole video, before (or without) cutting: it
stays here to cut from either way. */}
{s.status === "done" && s.has_file && !s.saved_url && (
<button type="button" className={button} onClick={() => act(() => post(`/admin/clips/${s.id}/save`, {}))}>
Save to library
</button>
)}
{s.saved_url && (
<Link to="/admin/media" className="text-sm underline" style={{ color: accentText(BRAND) }}>
In the media library
</Link>
)}
{s.status === "done" && !s.saved_drive && (s.has_file || s.saved_url) && (
<SaveToDrive clip={s} onSaved={load} />
)}
{s.saved_drive && (
<a href={s.saved_drive.url} target="_blank" rel="noreferrer" className="text-sm underline" style={{ color: accentText(BRAND) }}>
In Drive: Media{s.saved_drive.folder ? `/${s.saved_drive.folder}` : ""}
</a>
)}
{s.status !== "running" && ( {s.status !== "running" && (
<button <button
type="button" type="button"
@ -580,15 +484,7 @@ export default function AdminClips() {
In the media library In the media library
</Link> </Link>
)} )}
{clip.status === "done" && !clip.saved_drive && (clip.has_file || clip.saved_url) && ( {clip.status === "done" && !clip.has_file && !clip.saved_url && (
<SaveToDrive clip={clip} onSaved={load} />
)}
{clip.saved_drive && (
<a href={clip.saved_drive.url} target="_blank" rel="noreferrer" className="text-sm underline" style={{ color: accentText(BRAND) }}>
In Drive: Media{clip.saved_drive.folder ? `/${clip.saved_drive.folder}` : ""}
</a>
)}
{clip.status === "done" && !clip.has_file && !clip.saved_url && !clip.saved_drive && (
<span className="text-sm" style={{ color: MUTED }}> <span className="text-sm" style={{ color: MUTED }}>
Downloaded, and deleted from the server Downloaded, and deleted from the server
</span> </span>
@ -609,7 +505,7 @@ export default function AdminClips() {
))} ))}
</ul> </ul>
<p className="mt-3 text-xs" style={{ color: MUTED }}> <p className="mt-3 text-xs" style={{ color: MUTED }}>
A clip is deleted from the server once it's downloaded, unless it's saved to the library first. Save to Drive puts a copy in a folder under Media in the shared Drive, as a Files entry pages can link to. A clip is deleted from the server once it's downloaded, unless it's saved to the library first.
Everything here is cleared a day after it's made. Everything here is cleared a day after it's made.
</p> </p>
</Card> </Card>

View file

@ -24,7 +24,7 @@ import { del, get, patch, post, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts"; import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts";
import { feedbackTypeLabel } from "../../data/feedbackTypes.ts"; import { feedbackTypeLabel } from "../../data/feedbackTypes.ts";
import { fromRequest, requestType, requestTypeLabel } from "../../data/requestTypes.ts"; import { requestTypeLabel } from "../../data/requestTypes.ts";
const STATUSES = ["new", "read", "actioned", "archived", "spam"]; const STATUSES = ["new", "read", "actioned", "archived", "spam"];
@ -52,13 +52,10 @@ const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB`
/* A content request's files: each downloads from Drive through the /* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */ (the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite, canRemove }) { function RequestFiles({ row, canWrite }) {
const navigate = useNavigate(); const navigate = useNavigate();
const [files, setFiles] = useState<any[]>(row.files);
const [busy, setBusy] = useState<number | null>(null); const [busy, setBusy] = useState<number | null>(null);
const [confirming, setConfirming] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => setFiles(row.files), [row.files]);
async function makePost(file) { async function makePost(file) {
setBusy(file.id); setBusy(file.id);
@ -72,81 +69,29 @@ function RequestFiles({ row, canWrite, canRemove }) {
} }
} }
async function remove(file) {
setBusy(file.id);
setError(null);
try {
await del(`/admin/feedback/${row.id}/files/${file.id}`);
setFiles((current) => current.filter((f) => f.id !== file.id));
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't remove it.");
} finally {
setBusy(null);
setConfirming(null);
}
}
if (files.length === 0) return null;
const small = "rounded-full border px-3 py-0.5 text-xs font-semibold transition-colors disabled:opacity-60";
return ( return (
<div className="mt-4"> <div className="mt-4">
<ul className="space-y-2"> <ul className="space-y-2">
{files.map((file) => ( {row.files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm"> <li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
{file.missing ? ( <a
// Deleted or moved out of Requests in Drive: nothing to open. href={`/api/admin/feedback/${row.id}/files/${file.id}`}
<span className="font-medium text-muted line-through">{file.name}</span> download={file.name}
) : ( className="font-medium text-link underline underline-offset-2"
<a >
href={`/api/admin/feedback/${row.id}/files/${file.id}`} {file.name}
download={file.name} </a>
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{sizeOf(file.size)}</span> <span className="text-xs text-muted">{sizeOf(file.size)}</span>
{file.missing && ( {canWrite && /\.docx$/i.test(file.name) && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Missing from Drive
</span>
)}
{canWrite && !file.missing && /\.docx$/i.test(file.name) && (
<button <button
type="button" type="button"
disabled={busy !== null} disabled={busy !== null}
onClick={() => makePost(file)} onClick={() => makePost(file)}
className={`${small} border-link text-link hover:bg-tint`} className="rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60"
> >
{busy === file.id ? "Making the post…" : "Make a blog post from it"} {busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button> </button>
)} )}
{canRemove &&
(confirming === file.id ? (
<>
<button
type="button"
disabled={busy !== null}
onClick={() => remove(file)}
className={`${small} border-danger bg-danger text-white`}
>
{busy === file.id ? "Removing…" : "Remove it"}
</button>
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button
type="button"
disabled={busy !== null}
onClick={() => setConfirming(file.id)}
className="text-xs text-muted hover:text-danger"
title={file.missing ? "Take it off this request" : "Into Drive's trash, and off this request"}
>
Remove
</button>
))}
</li> </li>
))} ))}
</ul> </ul>
@ -159,111 +104,6 @@ function RequestFiles({ row, canWrite, canRemove }) {
); );
} }
/* A content request's details (049), labelled from requestTypes.ts;
keys it no longer knows are shown as they are. */
function RequestDetails({ row }) {
const entries = Object.entries(row.details ?? {});
if (entries.length === 0) return null;
const labels = new Map((requestType(row.category)?.fields ?? []).map((f) => [f.key, f.label]));
return (
<dl className="mt-4 grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
{entries.map(([key, value]) => (
<div key={key} className="contents">
<dt className="font-medium text-muted">{labels.get(key) ?? key.replace(/_/g, " ")}</dt>
<dd className="whitespace-pre-wrap text-body">{value as string}</dd>
</div>
))}
</dl>
);
}
/* The record a request is about, in its editor: a new one filled in
from the request, or, for an update, the existing one (picked here,
the closest name first) with the requested values beside its own.
Nothing is saved until Save in the editor. */
function RequestRecord({ row }) {
const navigate = useNavigate();
const type = requestType(row.category);
const [candidates, setCandidates] = useState<any[] | null>(null);
const [picked, setPicked] = useState("");
const [error, setError] = useState<string | null>(null);
if (!type) return null;
const state = { fromRequest: fromRequest(row) };
const button =
"rounded-full border border-link px-4 py-1.5 text-sm font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60";
if (row.request_action === "new") {
return (
<div className="mt-4">
<button type="button" className={button} onClick={() => navigate(`/admin/${type.entity}/new`, { state })}>
Create {type.label.toLowerCase()} from this
</button>
</div>
);
}
async function find() {
if (!type) return;
setError(null);
try {
const params = new URLSearchParams({ limit: "500", ...(type.preset ?? {}) });
const { rows } = await get(`/admin/${type.entity}?${params}`, { ttl: 0 });
const wanted = String(row.subject ?? "").toLowerCase().trim();
const name = (r) => String(r[type.heading] ?? r.id);
// The closest name first: exact, then containing, then the rest.
const score = (r) => {
const n = name(r).toLowerCase();
return n === wanted ? 0 : wanted && (n.includes(wanted) || wanted.includes(n)) ? 1 : 2;
};
const sorted = [...rows].sort((a, b) => score(a) - score(b) || name(a).localeCompare(name(b)));
setCandidates(sorted.map((r) => ({ id: r.id, name: name(r) })));
setPicked(sorted[0]?.id ?? "");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't load the list.");
}
}
return (
<div className="mt-4 flex flex-wrap items-center gap-3">
{candidates === null ? (
<button type="button" className={button} onClick={find}>
Find the {type.label.toLowerCase()} to update
</button>
) : candidates.length === 0 ? (
<span className="text-sm text-muted">No {type.label.toLowerCase()} records yet.</span>
) : (
<>
<label htmlFor={`record-${row.id}`} className="sr-only">
Which {type.label.toLowerCase()}
</label>
<select
id={`record-${row.id}`}
value={picked}
onChange={(e) => setPicked(e.target.value)}
className="rounded-lg border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"
>
{candidates.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<button
type="button"
className={button}
disabled={!picked}
onClick={() => navigate(`/admin/${type.entity}/${encodeURIComponent(picked)}`, { state })}
>
Open it with the requested changes
</button>
</>
)}
{error && <span className="text-sm text-danger">{error}</span>}
</div>
);
}
function locationOf(row) { function locationOf(row) {
if (!row.page_path) return "Not page-specific"; if (!row.page_path) return "Not page-specific";
return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path; return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path;
@ -330,9 +170,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
{row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>} {row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p> <p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.feedback_type === "content" && <RequestDetails row={row} />} {row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />}
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} canRemove={canRemove} />}
{row.feedback_type === "content" && canWrite && <RequestRecord row={row} />}
<p className="mt-4 text-sm text-muted"> <p className="mt-4 text-sm text-muted">
{row.name || row.email ? ( {row.name || row.email ? (

View file

@ -7,9 +7,7 @@
(MediaLibrary.tsx), so this is housekeeping rather than the way (MediaLibrary.tsx), so this is housekeeping rather than the way
images get in. Files: documents, audio and zips in the shared images get in. Files: documents, audio and zips in the shared
Google Drive, for pages to link to (DriveFiles.tsx); link fields' Google Drive, for pages to link to (DriveFiles.tsx); link fields'
"Choose a file" picks from them. Requests: every file sent with "Choose a file" picks from them.
the Request form, by type folder in Drive, each with its request;
a file Drive no longer has is marked missing.
Two ranks, as on the server: editors and up upload, admins and Two ranks, as on the server: editors and up upload, admins and
up delete. A delete first asks the server which records still up delete. A delete first asks the server which records still
@ -17,26 +15,19 @@
a page (an image field stores the path, not a foreign key). a page (an image field stores the path, not a foreign key).
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from "react"; import { useState } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { ApiError, del, get } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts";
import { import {
ALL_FOLDERS,
DriveFolderTabs,
FILE_HELP, FILE_HELP,
FileList, FileList,
FileUploadButton, FileUploadButton,
RefusedNote, RefusedNote,
inFolder,
useDriveFiles, useDriveFiles,
type DriveFile,
} from "../../components/admin/DriveFiles.tsx"; } from "../../components/admin/DriveFiles.tsx";
import { import {
FolderTabs,
formatBytes,
MediaGrid, MediaGrid,
UPLOAD_HELP, UPLOAD_HELP,
UploadButton, UploadButton,
@ -149,153 +140,17 @@ function CopyPath({ url, label = "Copy path" }: { url: string; label?: string })
); );
} }
/* The folder showing: make one inside it, rename it, or delete it
when it's empty. Drive is the source; the list reloads after. */
function FolderControls({ tab, onChanged }: { tab: string; onChanged: (tab: string) => void }) {
const { user } = useAuth();
const [mode, setMode] = useState<"new" | "rename" | null>(null);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const inside = tab === ALL_FOLDERS ? "" : tab;
const button = "rounded-full border border-brand px-3 py-1 text-xs font-medium text-link transition-colors hover:bg-tint disabled:opacity-50";
async function run(work: () => Promise<string>) {
setBusy(true);
setError(null);
try {
onChanged(await work());
setMode(null);
setName("");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
} finally {
setBusy(false);
}
}
const submit = () =>
run(async () =>
mode === "new"
? (await post("/admin/files/folders", { path: inside ? `${inside}/${name}` : name })).path
: (await patch("/admin/files/folders", { path: inside, name })).path,
);
const remove = () =>
run(async () => {
await del(`/admin/files/folders?path=${encodeURIComponent(inside)}`);
return inside.split("/").slice(0, -1).join("/") || ALL_FOLDERS;
});
if (!roleCanWrite(user)) return null;
return (
<div className="mt-3 flex flex-wrap items-center gap-2">
{mode ? (
<>
<label htmlFor="folder-name" className="sr-only">
Folder name
</label>
<input
id="folder-name"
value={name}
autoFocus
maxLength={60}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && name.trim()) submit();
if (e.key === "Escape") setMode(null);
}}
placeholder={mode === "new" ? "New folder's name" : "New name"}
className="rounded-lg border border-muted/25 bg-surface px-3 py-1 text-sm text-body outline-none focus:border-brand"
/>
<button type="button" className={button} disabled={busy || !name.trim()} onClick={submit}>
{mode === "new" ? (inside ? `Make it in ${inside}` : "Make folder") : "Rename"}
</button>
<button type="button" className="text-xs text-muted hover:underline" onClick={() => setMode(null)}>
Cancel
</button>
</>
) : (
<>
<button type="button" className={button} onClick={() => setMode("new")}>
New folder{inside ? ` in ${inside}` : ""}
</button>
{inside && (
<button
type="button"
className={button}
onClick={() => {
setMode("rename");
setName(inside.split("/").pop() ?? "");
}}
>
Rename {inside}
</button>
)}
{inside && canDelete(user) && (
<button type="button" className={`${button} border-danger/40 text-danger`} disabled={busy} onClick={remove}>
Delete {inside} (if empty)
</button>
)}
</>
)}
{error && <span className="text-xs text-danger">{error}</span>}
</div>
);
}
/* A file's folder, changed in place. */
function MoveControl({ file, folders, onMoved }: { file: DriveFile; folders: string[]; onMoved: (file: DriveFile) => void }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<div className="w-full">
<label className="flex items-center gap-2 text-xs text-muted">
Folder
<select
value={file.folder}
disabled={busy}
onChange={async (e) => {
setBusy(true);
setError(null);
try {
onMoved((await patch(`/admin/files/${file.id}`, { folder: e.target.value })).file);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't move it.");
} finally {
setBusy(false);
}
}}
className="rounded border border-muted/25 bg-surface px-1.5 py-0.5 text-xs text-body"
>
<option value="">Not in a folder</option>
{folders.map((f) => (
<option key={f} value={f}>
{f}
</option>
))}
</select>
</label>
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
</div>
);
}
function FilesTab() { function FilesTab() {
const { user } = useAuth(); const { user } = useAuth();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const { items, folders, ready, refused, error, reload, setItems } = useDriveFiles(query); const { items, ready, refused, error, setItems } = useDriveFiles(query);
const [tab, setTab] = useState(ALL_FOLDERS);
const replace = (file: DriveFile) => setItems((current) => (current ?? []).map((f) => (f.id === file.id ? file : f)));
return ( return (
<> <>
<div className="mt-6 flex flex-wrap items-start gap-6"> <div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && ready && ( {roleCanWrite(user) && ready && (
<div className="max-w-md"> <div className="max-w-md">
<FileUploadButton <FileUploadButton onUploaded={(file) => setItems((current) => [file, ...(current ?? [])])} />
label={tab && tab !== ALL_FOLDERS ? `Upload files into ${tab}` : "Upload files"}
folder={tab === ALL_FOLDERS ? "" : tab}
onUploaded={(file) => setItems((current) => [file, ...(current ?? [])])}
/>
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p> <p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
</div> </div>
)} )}
@ -312,19 +167,6 @@ function FilesTab() {
Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded. Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.
</p> </p>
)} )}
{ready && (
<div className="mt-6">
<DriveFolderTabs folders={folders} value={tab} onChange={setTab} />
<FolderControls
tab={tab}
onChanged={(next) => {
setTab(next);
reload();
}}
/>
</div>
)}
<div className="mt-6"> <div className="mt-6">
<RefusedNote names={refused} /> <RefusedNote names={refused} />
{error ? ( {error ? (
@ -333,10 +175,9 @@ function FilesTab() {
<p className="text-sm text-muted">Loading…</p> <p className="text-sm text-muted">Loading…</p>
) : ( ) : (
<FileList <FileList
items={inFolder(items, tab)} items={items}
renderActions={(file) => ( renderActions={(file) => (
<div className="flex flex-wrap items-start gap-x-3 gap-y-1"> <div className="flex flex-wrap items-start gap-x-3 gap-y-1">
{roleCanWrite(user) && <MoveControl file={file} folders={folders} onMoved={replace} />}
<CopyPath url={file.url} label="Copy link" /> <CopyPath url={file.url} label="Copy link" />
<a href={file.url} target="_blank" rel="noreferrer" className="text-xs text-link hover:underline"> <a href={file.url} target="_blank" rel="noreferrer" className="text-xs text-link hover:underline">
Open in Drive Open in Drive
@ -360,135 +201,16 @@ function FilesTab() {
); );
} }
/* Request form files, by their type's folder in Drive (Requests/…). */
function RequestFilesTab() {
const { user } = useAuth();
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);
const [folder, setFolder] = useState("*");
const [confirming, setConfirming] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
get("/admin/request-files", { ttl: 0 })
.then(setData)
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files."));
}, []);
async function remove(file) {
setBusy(true);
setError(null);
try {
await del(`/admin/feedback/${file.feedback_id}/files/${file.id}`);
setData((current) => ({ ...current, files: current.files.filter((f) => f.id !== file.id) }));
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't remove it.");
} finally {
setBusy(false);
setConfirming(null);
}
}
if (error && !data) return <p className="mt-6 text-sm text-danger">{error}</p>;
if (!data) return <p className="mt-6 text-sm text-muted">Loading…</p>;
const counts = new Map<string, number>();
for (const f of data.files) counts.set(f.folder, (counts.get(f.folder) ?? 0) + 1);
const shown = folder === "*" ? data.files : data.files.filter((f) => f.folder === folder);
return (
<div className="mt-6">
<div role="tablist" aria-label="Request folders" className="flex flex-wrap gap-1">
{[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => (
<button
key={id}
type="button"
role="tab"
aria-selected={folder === id}
onClick={() => setFolder(id)}
className={
"rounded-full px-3 py-1 text-sm transition-colors " +
(folder === id ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
}
>
{label}
{id !== "*" && counts.get(id) ? ` (${counts.get(id)})` : ""}
</button>
))}
</div>
{!data.checked && (
<p className="mt-3 text-sm text-muted">Drive couldn't be asked just now, so missing files aren't marked.</p>
)}
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
{shown.length === 0 ? (
<p className="mt-6 text-sm text-muted">No request files here.</p>
) : (
<ul className="mt-6 divide-y divide-brand/10 rounded-2xl border border-brand/20 bg-surface">
{shown.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-3 text-sm">
{file.missing ? (
<span className="font-medium text-muted line-through">{file.name}</span>
) : (
<a
href={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{formatBytes(file.size)}</span>
{file.missing && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">Missing from Drive</span>
)}
<Link to="/admin/requests" className="text-xs text-muted hover:text-link hover:underline">
Request #{file.feedback_id}
{file.subject ? `: ${file.subject}` : ""} ({file.status})
</Link>
{canDelete(user) && (
<span className="ml-auto">
{confirming === file.id ? (
<>
<button
type="button"
disabled={busy}
onClick={() => remove(file)}
className="rounded-full bg-danger px-3 py-0.5 text-xs font-semibold text-white disabled:opacity-60"
>
{busy ? "Removing…" : "Remove it"}
</button>{" "}
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button type="button" onClick={() => setConfirming(file.id)} className="text-xs text-muted hover:text-danger">
Remove
</button>
)}
</span>
)}
</li>
))}
</ul>
)}
</div>
);
}
const TABS = [ const TABS = [
["images", "Images"], ["images", "Images"],
["files", "Files"], ["files", "Files"],
["requests", "Requests"],
] as const; ] as const;
export default function AdminMedia() { export default function AdminMedia() {
const { user } = useAuth(); const { user } = useAuth();
const [tab, setTab] = useState<(typeof TABS)[number][0]>("images"); const [tab, setTab] = useState<"images" | "files">("images");
// The image folder showing; "" is all of them, clips included.
const [folder, setFolder] = useState("");
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query, undefined, folder); const { items, error, setItems } = useMediaLibrary(query);
return ( return (
<div> <div>
@ -497,9 +219,7 @@ export default function AdminMedia() {
<p className="text-sm text-muted"> <p className="text-sm text-muted">
{tab === "images" {tab === "images"
? "Uploaded images. Image fields in every editor pick from here." ? "Uploaded images. Image fields in every editor pick from here."
: tab === "files" : "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."}
? "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."
: "Files sent with the Request form, in the shared Google Drive's Requests folder. Removing one takes it off its request too."}
</p> </p>
</div> </div>
@ -520,24 +240,17 @@ export default function AdminMedia() {
))} ))}
</nav> </nav>
{tab === "requests" ? ( {tab === "files" ? (
<RequestFilesTab />
) : tab === "files" ? (
<FilesTab /> <FilesTab />
) : ( ) : (
<> <>
<div className="mt-6">
<FolderTabs value={folder} onChange={setFolder} />
</div>
<div className="mt-6 flex flex-wrap items-start gap-6"> <div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && ( {roleCanWrite(user) && (
<div className="max-w-md"> <div className="max-w-md">
<UploadButton <UploadButton
multiple multiple
label={folder === "logos" ? "Upload logos" : "Upload images"} label="Upload images"
folder={folder || undefined}
onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])} onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])}
/> />
<p className="mt-1 text-xs text-muted">{UPLOAD_HELP}</p> <p className="mt-1 text-xs text-muted">{UPLOAD_HELP}</p>

View file

@ -88,10 +88,6 @@ export default function EntityEdit() {
useWideAdminPage(); useWideAdminPage();
const isNew = id === "new"; const isNew = id === "new";
// From Forms → Content requests (requestTypes.ts, fromRequest): a
// new record starts filled in with it; an existing one shows it in
// RequestedChanges to use value by value.
const fromRequest = (useLocation().state as any)?.fromRequest ?? null;
// Editor, unless the entity asks for more (site settings: // Editor, unless the entity asks for more (site settings:
// superadmin), matching the server's writeRole. // superadmin), matching the server's writeRole.
const canWrite = atLeast(user, manifest?.writeRole ?? "editor"); const canWrite = atLeast(user, manifest?.writeRole ?? "editor");
@ -176,18 +172,8 @@ export default function EntityEdit() {
// sending "" would be an explicit value rather than an absence. // sending "" would be an explicit value rather than an absence.
const blank = autoId ? {} : { id: "" }; const blank = autoId ? {} : { id: "" };
for (const child of manifest.children ?? []) blank[child.key] = []; for (const child of manifest.children ?? []) blank[child.key] = [];
// The baseline stays the empty form, so a filled-in one counts setForm(blank);
// as unsaved until Create.
baseline.current = JSON.stringify(blank); baseline.current = JSON.stringify(blank);
let start: any = blank;
if (fromRequest) {
for (const item of fromRequest.set) start = setPath(start, item.path, item.value);
for (const item of fromRequest.add) start = { ...start, [item.child]: [...(start[item.child] ?? []), item.row] };
if (!autoId && headingPath) {
start = { ...start, id: `${prefixOf(start)}${slugify(getPath(start, headingPath) ?? "")}` };
}
}
setForm(start);
} else { } else {
const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 }); const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 });
setForm(data.row); setForm(data.row);
@ -203,8 +189,7 @@ export default function EntityEdit() {
} finally { } finally {
setLoading(false); setLoading(false);
} }
// prefixOf and headingPath follow the manifest, already a dependency. }, [manifest, id, isNew, autoId, navigate]);
}, [manifest, id, isNew, autoId, navigate, fromRequest]);
useEffect(() => { useEffect(() => {
load(); load();
@ -383,15 +368,6 @@ export default function EntityEdit() {
</h1> </h1>
<ImportedNote /> <ImportedNote />
{fromRequest && (
<RequestedChanges
request={fromRequest}
isNew={isNew}
form={form}
onUse={change}
onAdd={(child, row) => setForm((prev) => ({ ...prev, [child]: [...(prev[child] ?? []), row] }))}
/>
)}
{/* Straight in the page, not wrapped: a sticky element only {/* Straight in the page, not wrapped: a sticky element only
travels within its parent, so its parent has to be tall. */} travels within its parent, so its parent has to be tall. */}
@ -575,74 +551,3 @@ function ImportedNote() {
</p> </p>
); );
} }
/* From a content request (Forms → Content requests). A new record
is already filled in: this says so. An existing one lists each
requested value beside the current one, to use or leave; nothing
changes until it's used, and nothing is saved until Save. */
function RequestedChanges({ request, isNew, form, onUse, onAdd }: any) {
const [done, setDone] = useState<Set<string>>(() => new Set());
const mark = (key: string) => setDone((prev) => new Set(prev).add(key));
const button = "rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint";
if (isNew) {
return (
<p role="status" className="mt-4 rounded-xl border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Filled in from content request #{request.request}. Check it, fill in the rest, then Create. It isn't saved yet.
</p>
);
}
const items = [
...request.set.map((item) => ({ key: `set:${item.path}`, ...item, current: getPath(form, item.path) })),
...request.add.map((item, i) => ({ key: `add:${i}`, ...item })),
];
if (items.length === 0) {
return (
<p className="mt-4 rounded-xl border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
Content request #{request.request} has no details to copy; its message is in Forms → Content requests.
</p>
);
}
return (
<div className="mt-4 rounded-xl border border-brand/20 bg-tint px-4 py-3 text-sm text-body">
<p className="font-semibold">Requested in content request #{request.request}</p>
<p className="mt-0.5 text-xs text-muted">Use what should change, then Save changes.</p>
<ul className="mt-3 space-y-2">
{items.map((item) => (
<li key={item.key} className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="font-medium">{item.label}</span>
{"path" in item ? (
<>
<span className="text-muted">
now {item.current ? <q>{String(item.current)}</q> : "blank"}, requested <q>{item.value}</q>
</span>
{done.has(item.key) || String(item.current ?? "") === item.value ? (
<span className="text-xs text-muted">in the form</span>
) : (
<button type="button" className={button} onClick={() => {
onUse(item.path, item.value);
mark(item.key);
}}>
Use this
</button>
)}
</>
) : done.has(item.key) ? (
<span className="text-xs text-muted">added below</span>
) : (
<button type="button" className={button} onClick={() => {
onAdd(item.child, item.row);
mark(item.key);
}}>
Add it
</button>
)}
</li>
))}
</ul>
</div>
);
}

View file

@ -36,8 +36,7 @@ const DEFAULTS = {
const EXCERPT_CHARS = 180 const EXCERPT_CHARS = 180
/* One post as a card; person pages list their posts with it too. */ function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) {
export function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) {
const cover = useSmallImage(mediaUrl(post.cover_image)) const cover = useSmallImage(mediaUrl(post.cover_image))
const date = postDate(post.published_on) const date = postDate(post.published_on)
const authors = post.authors.map((author) => author.name).join(', ') const authors = post.authors.map((author) => author.name).join(', ')

View file

@ -51,26 +51,6 @@ export function OptionalTag() {
); );
} }
/* On a field the send button waits for. */
export function RequiredTag() {
return (
<span className="ml-2 rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Required
</span>
);
}
/* Under a message box: how many more characters it needs, until it
has them (the send button stays off until then). */
export function MinimumNote({ length, min }: { length: number; min: number }) {
if (length >= min) return null;
return (
<span className="text-xs" style={{ color: MUTED }}>
{length === 0 ? `At least ${min} characters` : `${min - length} more character${min - length === 1 ? "" : "s"} needed`}
</span>
);
}
export function FieldError({ id, children }) { export function FieldError({ id, children }) {
if (!children) return null; if (!children) return null;
return ( return (
@ -376,7 +356,6 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
className="text-base font-semibold text-body" className="text-base font-semibold text-body"
> >
{request ? "Your request" : "Tell us more"} {request ? "Your request" : "Tell us more"}
<RequiredTag />
</label> </label>
<p className="mt-1 text-sm" style={{ color: MUTED }}> <p className="mt-1 text-sm" style={{ color: MUTED }}>
{request {request
@ -402,7 +381,6 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
/> />
<div className="mt-2 flex items-start justify-between gap-4"> <div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="feedback-message-error">{fieldErrors.message}</FieldError> <FieldError id="feedback-message-error">{fieldErrors.message}</FieldError>
{!fieldErrors.message && <MinimumNote length={message.trim().length} min={MIN_MESSAGE} />}
<span <span
className="ml-auto shrink-0 text-xs tabular-nums" className="ml-auto shrink-0 text-xs tabular-nums"
style={{ color: MUTED }} style={{ color: MUTED }}
@ -504,8 +482,8 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
{!ready && !sending && ( {!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}> <p className="text-sm" style={{ color: MUTED }}>
{request {request
? `Write at least ${MIN_MESSAGE} characters and give an email address to send.` ? "Write at least a sentence and give an email address to send."
: `Choose a type and write at least ${MIN_MESSAGE} characters to send.`} : "Choose a type and write at least a sentence to send."}
</p> </p>
)} )}
</div> </div>

View file

@ -6,10 +6,6 @@
?type=chapter in the address picks one to start with, which is how ?type=chapter in the address picks one to start with, which is how
the site's "Request" buttons open it. the site's "Request" buttons open it.
Each type's details (its `fields` in requestTypes.ts: a chapter's
city and meeting time, an event's dates) go as one JSON field; the
admin opens the record's editor filled in from them.
Files go to Google Drive on the server; when Drive isn't set up Files go to Google Drive on the server; when Drive isn't set up
(REQUEST_FILES) the file field isn't shown. The limits here match (REQUEST_FILES) the file field isn't shown. The limits here match
the server's, so nobody waits on an upload that will be refused. the server's, so nobody waits on an upload that will be refused.
@ -22,7 +18,7 @@ import { ApiError, upload } from "../../lib/api.ts";
import { accentText, BRAND } from "../../lib/color.ts"; import { accentText, BRAND } from "../../lib/color.ts";
import { REQUEST_FILES } from "../../lib/site.ts"; import { REQUEST_FILES } from "../../lib/site.ts";
import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts"; import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts";
import { FieldError, MinimumNote, OptionalTag, RequiredTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx"; import { FieldError, OptionalTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
const MUTED = "var(--color-muted)"; const MUTED = "var(--color-muted)";
const MAX_CHARS = 5000; const MAX_CHARS = 5000;
@ -52,8 +48,6 @@ export default function RequestForm() {
const [files, setFiles] = useState<File[]>([]); const [files, setFiles] = useState<File[]>([]);
const [name, setName] = useState(""); const [name, setName] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
// By field key; kept when the type changes, since types share keys.
const [details, setDetails] = useState<Record<string, string>>({});
const [website, setWebsite] = useState(""); // honeypot const [website, setWebsite] = useState(""); // honeypot
const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle"); const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");
@ -98,15 +92,6 @@ export default function RequestForm() {
form.set("message", message.trim()); form.set("message", message.trim());
form.set("name", name.trim()); form.set("name", name.trim());
form.set("email", email.trim()); form.set("email", email.trim());
// Only the chosen type's fields, and only filled ones.
form.set(
"details",
JSON.stringify(
Object.fromEntries(
(type?.fields ?? []).map((f) => [f.key, (details[f.key] ?? "").trim()]).filter(([, value]) => value),
),
),
);
form.set("website", website); form.set("website", website);
for (const file of files) form.append("files", file); for (const file of files) form.append("files", file);
@ -126,7 +111,6 @@ export default function RequestForm() {
function reset() { function reset() {
setSubject(""); setSubject("");
setDetails({});
setMessage(""); setMessage("");
setFiles([]); setFiles([]);
setStatus("idle"); setStatus("idle");
@ -206,7 +190,6 @@ export default function RequestForm() {
<div className="mt-8"> <div className="mt-8">
<label htmlFor="request-subject" className="text-base font-semibold text-body"> <label htmlFor="request-subject" className="text-base font-semibold text-body">
{action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject} {action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject}
<RequiredTag />
</label> </label>
<input <input
id="request-subject" id="request-subject"
@ -221,49 +204,9 @@ export default function RequestForm() {
<FieldError id="request-subject-error">{fieldErrors.subject}</FieldError> <FieldError id="request-subject-error">{fieldErrors.subject}</FieldError>
</div> </div>
{type.fields.length > 0 && (
<fieldset className="mt-8">
<legend className="flex flex-wrap items-center text-base font-semibold text-body">
Details
<OptionalTag />
</legend>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
{action === "update"
? "Only what should change; leave the rest blank."
: "Whatever you know. Blanks are fine, and the rest can go in the message or a document."}
</p>
<div className="mt-4 grid gap-4 sm:grid-cols-2">
{type.fields.map((f) => {
const id = `request-detail-${f.key}`;
const common = {
id,
value: details[f.key] ?? "",
placeholder: f.placeholder,
maxLength: 2000,
className: fieldClass,
};
const set = (value: string) => setDetails((prev) => ({ ...prev, [f.key]: value }));
return (
<div key={f.key} className={f.input === "textarea" ? "sm:col-span-2" : ""}>
<label htmlFor={id} className="block text-sm font-medium text-body">
{f.label}
</label>
{f.input === "textarea" ? (
<textarea {...common} rows={3} onChange={(e) => set(e.target.value)} className={`mt-2 resize-y ${fieldClass}`} />
) : (
<input {...common} type={f.input ?? "text"} onChange={(e) => set(e.target.value)} className={`mt-2 ${fieldClass}`} />
)}
</div>
);
})}
</div>
</fieldset>
)}
<div className="mt-8"> <div className="mt-8">
<label htmlFor="request-message" className="text-base font-semibold text-body"> <label htmlFor="request-message" className="text-base font-semibold text-body">
{action === "update" ? "What should change?" : "Tell us about it"} {action === "update" ? "What should change?" : "Tell us about it"}
<RequiredTag />
</label> </label>
<textarea <textarea
id="request-message" id="request-message"
@ -282,7 +225,6 @@ export default function RequestForm() {
/> />
<div className="mt-2 flex items-start justify-between gap-4"> <div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="request-message-error">{fieldErrors.message}</FieldError> <FieldError id="request-message-error">{fieldErrors.message}</FieldError>
{!fieldErrors.message && <MinimumNote length={message.trim().length} min={MIN_MESSAGE} />}
<span className="ml-auto shrink-0 text-xs tabular-nums" style={{ color: MUTED }}> <span className="ml-auto shrink-0 text-xs tabular-nums" style={{ color: MUTED }}>
{message.length} / {MAX_CHARS} {message.length} / {MAX_CHARS}
</span> </span>
@ -385,7 +327,7 @@ export default function RequestForm() {
</button> </button>
{!ready && !sending && ( {!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}> <p className="text-sm" style={{ color: MUTED }}>
Choose what it's about, give it a name, write at least {MIN_MESSAGE} characters and give an email address to send. Choose what it's about, give it a name, write at least a sentence and give an email address to send.
</p> </p>
)} )}
</div> </div>