diff --git a/CLAUDE.md b/CLAUDE.md index 8b009f1..f6beba4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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). - `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. -- Images: every record image (logos, photos, backgrounds, block images) is an upload. A bare filename resolves to `/uploads/` (`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, 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/` (`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 - **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. diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index c105d45..6b72b78 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -60,8 +60,8 @@ hand. | Folder | Used by | Set in | | --- | --- | --- | -| `Requests` | Files sent with the Request form | `DRIVE_FOLDER` in `server/src/routes/requests.js` | -| `Media` | Files for pages to link to (Tools → Media → Files) | `FOLDER` in `server/src/routes/files.js` | +| `Requests/` | 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` | +| `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` | A new use calls `driveUpload("", name, mime, bytes)` from `server/src/googleService.js`; a path such as `"Media/2026"` makes each @@ -78,7 +78,14 @@ folders to the drive; the site ignores them. Request files are named `Request 12 - original name.docx`, so the number matches the one in Forms → Content requests. Deleting a request in the -admin deletes its files from Drive too. +admin deletes its files from Drive too. Request files from before the +per-type folders stay where they are, in `Requests` itself. + +**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) @@ -201,7 +208,14 @@ Drive" above the title. 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 ten minutes. -- Deleting a file in the admin deletes it from Drive; the delete says +- **Folders:** Media → Files has a tab per folder under `Media` (up to + 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). Deleting it in Drive by hand leaves a broken link and a list entry that can still be deleted. diff --git a/docs/media-uploads.md b/docs/media-uploads.md index 86cc907..bb2bfe3 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -23,10 +23,37 @@ in the `media` table (`server/src/migrations/028_media.sql`). 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 -A file put straight into the uploads directory (with `scp`, say) shows -up in the library the next time the Media page or an image picker opens: +A file put straight into the uploads directory, or into one of its +folders (with `scp`, say), shows 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 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 diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index a7578d0..28939bc 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -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. | | 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. | -| 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 `` (`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, 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 `` (`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 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. | diff --git a/server/src/googleService.js b/server/src/googleService.js index 15f5406..31bf976 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -124,6 +124,7 @@ const folders = new Map(); "Media/2026", made if it isn't there. Found by name, so a folder renamed in Drive is made again under the old name. */ export function driveFolder(path) { + path = path.split("/").filter(Boolean).join("/"); let pending = folders.get(path); if (!pending) { pending = findOrMakeFolder(path); @@ -133,6 +134,12 @@ export function driveFolder(path) { 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) { const drive = process.env.GOOGLE_SHARED_DRIVE; let parent = drive; @@ -187,16 +194,15 @@ export async function driveUpload(folder, name, mime, buffer) { return await res.json(); } -/* The files (not folders) directly in a folder of the shared drive: - [{ id, name, mimeType, size, webViewLink }]. size is missing for - Google's own Docs, Sheets and Slides. */ -export async function driveList(folder) { - const parent = await driveFolder(folder); +/* Everything directly in a folder: [{ id, name, mimeType, size, + webViewLink }]. size is missing for Google's own Docs, Sheets and + Slides. */ +async function driveChildren(parent) { const found = []; let pageToken = ""; do { const query = new URLSearchParams({ - q: `'${parent}' in parents and trashed = false and mimeType != '${FOLDER}'`, + q: `'${parent}' in parents and trashed = false`, corpora: "drive", driveId: process.env.GOOGLE_SHARED_DRIVE, includeItemsFromAllDrives: "true", @@ -212,6 +218,53 @@ export async function driveList(folder) { 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, + ); +} + /* Anyone with the link can view: for files the public site links to. Refused when the shared drive (or the Workspace) doesn't allow sharing outside the organization. */ @@ -244,8 +297,15 @@ export async function driveDownload(id) { 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) { - await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE); + await call( + `${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, + { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) }, + DRIVE_SCOPE, + ); } /* ── Gmail ───────────────────────────────────────────────────── */ diff --git a/server/src/index.js b/server/src/index.js index f9c99f1..546041a 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -38,7 +38,7 @@ import clips from "./routes/clips.js"; import imports from "./routes/import.js"; import files from "./routes/files.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js"; -import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; +import { UPLOADS_DIR, sortIntoFolders, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { startGroupSync } from "./accessGroups.js"; @@ -57,6 +57,9 @@ syncDescriptorsWithSchema(db, ENTITIES); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); await mkdir(UPLOADS_DIR, { recursive: true }); 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. writeMissingThumbs() .then((made) => made && console.log(`uploads: made ${made} small copies`)) diff --git a/server/src/media.js b/server/src/media.js index d7580f2..e85941a 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -30,6 +30,15 @@ Names are random, so two uploads of "logo.png" can't collide 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 ── A file put straight into UPLOADS_DIR has no media row, so the library wouldn't know it. registerLooseFiles() gives each image @@ -41,6 +50,8 @@ ═══════════════════════════════════════════════════════════════ */ import { randomBytes } from "node:crypto"; + +import { tx } from "./db.js"; import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -56,6 +67,42 @@ const MB = 1024 * 1024; /* The largest file accepted at all, before processing: room for a 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; /* The largest file kept as uploaded, unprocessed. */ @@ -116,7 +163,7 @@ function sniff(buf) { and leave nothing behind. ───────────────────────────────────────────────────────────── */ -export async function store(buf, { keepOriginal = false } = {}) { +export async function store(buf, { keepOriginal = false, folder } = {}) { if (buf.length === 0) throw new MediaError(400, "The file is empty."); if (buf.length > MAX_UPLOAD_BYTES) { throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`); @@ -164,12 +211,14 @@ export async function store(buf, { keepOriginal = false } = {}) { throw new MediaError(415, "That image couldn't be read. It may be damaged."); } - const filename = `${randomBytes(12).toString("hex")}${type.ext}`; + const dir = folderOf(folder); + const base = `${randomBytes(12).toString("hex")}${type.ext}`; + const filename = `${dir}/${base}`; - await mkdir(UPLOADS_DIR, { recursive: true }); + await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true }); // Written under a temporary name and renamed, so a half-written // file is never served under its real one. - const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`); + const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); await writeFile(tmp, out); await rename(tmp, path.join(UPLOADS_DIR, filename)); if (kind !== "svg") await writeThumb(filename, out); @@ -200,7 +249,7 @@ export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640. async function writeThumb(filename, buf) { const name = thumbName(filename); - const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`); + const tmp = path.join(UPLOADS_DIR, path.dirname(name), `.${path.basename(name)}.tmp`); try { await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS }) .rotate() @@ -218,17 +267,11 @@ async function writeThumb(filename, buf) { /* Makes the small copy for every raster upload that lacks one. Returns how many it made. */ export async function writeMissingThumbs() { - let names; - try { - names = await readdir(UPLOADS_DIR); - } catch (err) { - if (err.code === "ENOENT") return 0; - throw err; - } + const names = await listStored(); const present = new Set(names); let made = 0; for (const name of names) { - if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue; + if (THUMB.test(name) || /\.svg$/i.test(name)) continue; if (present.has(thumbName(name))) continue; const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; @@ -242,8 +285,8 @@ export async function writeMissingThumbs() { gone is not an error: the row is what's being removed. */ export async function remove(filename) { // filename comes from our own table, but it's joined onto a - // directory, so refuse anything that isn't a bare name. - if (path.basename(filename) !== filename) return; + // directory, so refuse anything that isn't a stored name. + if (!isStoredName(filename)) return; for (const name of [filename, thumbName(filename)]) { try { await unlink(path.join(UPLOADS_DIR, name)); @@ -292,13 +335,7 @@ async function describe(filename) { how many it added. Safe to run often: it only reads the folder and the table, and inserts nothing twice (filename is UNIQUE). */ export async function registerLooseFiles(db) { - let names; - try { - names = await readdir(UPLOADS_DIR); - } catch (err) { - if (err.code === "ENOENT") return 0; - throw err; - } + const names = await listStored(); const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename)); const insert = db.prepare( @@ -309,7 +346,7 @@ export async function registerLooseFiles(db) { let added = 0; for (const name of names) { - if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue; + if (known.has(name) || THUMB.test(name) || !isStoredName(name)) continue; let row; try { row = await describe(name); @@ -319,7 +356,7 @@ export async function registerLooseFiles(db) { if (!row) continue; const result = insert.run( row.filename, - row.filename, + path.basename(row.filename), row.content_type, row.bytes, row.width, @@ -331,3 +368,88 @@ export async function registerLooseFiles(db) { if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`); 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; +} + diff --git a/server/src/migrations/049_request_details.sql b/server/src/migrations/049_request_details.sql new file mode 100644 index 0000000..178a324 --- /dev/null +++ b/server/src/migrations/049_request_details.sql @@ -0,0 +1,12 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 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)); diff --git a/server/src/migrations/050_drive_file_folders.sql b/server/src/migrations/050_drive_file_folders.sql new file mode 100644 index 0000000..146a8cf --- /dev/null +++ b/server/src/migrations/050_drive_file_folders.sql @@ -0,0 +1,10 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 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 ''; diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 239cf97..85ec0ff 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -30,7 +30,7 @@ const KIND_WHERE = { content: "feedback_type = 'content'", }; const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id, - status, admin_note, category, request_action, subject`; + status, admin_note, category, request_action, subject, details`; /* Each row with its files (content requests), in one query. */ function withFiles(db, rows) { @@ -43,6 +43,8 @@ function withFiles(db, rows) { .all(...rows.map((r) => r.id)); return rows.map((row) => ({ ...row, + // Stored as JSON text (049); the admin wants the object. + details: row.details ? JSON.parse(row.details) : null, files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f), })); } diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js index 9407477..d6c890a 100644 --- a/server/src/routes/blog.js +++ b/server/src/routes/blog.js @@ -80,6 +80,24 @@ 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 ──────────────────────────────────────────────── */ blog.get("/blog/:id", (c) => { diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 0c72958..08388f5 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -5,9 +5,19 @@ Picks up files put in the folder in Drive by hand first (pickUp, at most every SCAN_EVERY_MS) - POST /files upload one (multipart: file) + POST /files upload one (multipart: file, folder) + PATCH /files/:id { folder }: move it to another folder GET /files/:id/uses which records link to it - DELETE /files/:id out of Drive and the list + DELETE /files/:id into Drive's trash, out of 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 FOLDER (googleService.js) and shared as "anyone with the link can @@ -35,14 +45,41 @@ import { Hono } from "hono"; import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; -import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js"; +import { + driveDelete, + driveFolder, + driveFolderEmpty, + driveMove, + driveReady, + driveRename, + driveShareWithAnyone, + driveThumbnail, + driveTree, + driveUpload, + forgetFolders, +} from "../googleService.js"; import { addToLibrary, recordsNaming } from "./media.js"; +import { publicPath } from "../media.js"; import { NO_STORE } from "../shape.js"; const files = new Hono(); files.use("*", requireAuth); 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("/"); +} +const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER); const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_LIST = 500; // Seconds after upload to ask Drive for the preview again. @@ -88,6 +125,7 @@ const shape = (row) => ({ bytes: row.bytes, url: row.url, preview: row.preview, + folder: row.folder, uploaded_by: row.uploaded_by_name ?? row.uploaded_by_email ?? null, created_at: row.created_at, }); @@ -100,8 +138,8 @@ function fetchPreview(db, row, userId) { try { const image = await driveThumbnail(row.drive_id); if (image) { - const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId }); - db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(`/uploads/${saved.filename}`, row.id); + const saved = await addToLibrary(db, image, { originalName: `${shape(row).title} (preview)`, userId, folder: "thumbnails" }); + db.prepare(`UPDATE drive_files SET preview = ? WHERE id = ?`).run(publicPath(saved.filename), row.id); return; } } catch (err) { @@ -119,20 +157,29 @@ function fetchPreview(db, row, userId) { Never throws: the list still shows what's known. */ const RETRY_MS = 10 * 60 * 1000; let lastScan = 0; +let folderPaths = []; const refused = new Map(); // drive id → { name, at } -async function pickUp(db) { - if (!driveReady() || Date.now() - lastScan < SCAN_EVERY_MS) return; +async function pickUp(db, force = false) { + if (!driveReady() || (!force && Date.now() - lastScan < SCAN_EVERY_MS)) return; lastScan = Date.now(); - let found; + let tree; try { - found = await driveList(FOLDER); + tree = await driveTree(FOLDER, MAX_DEPTH); } catch (err) { console.warn(`files: couldn't list the ${FOLDER} folder: ${err.message}`); return; } - const known = new Set(db.prepare(`SELECT drive_id FROM drive_files`).all().map((r) => r.drive_id)); - for (const file of found) { - if (known.has(file.id) || SKIP_TYPES.has(file.mimeType)) continue; + folderPaths = tree.folders.map((f) => f.path).filter(Boolean).sort((a, b) => a.localeCompare(b)); + 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 tree.files) { + // 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; try { await driveShareWithAnyone(file.id); @@ -143,8 +190,8 @@ async function pickUp(db) { } refused.delete(file.id); const id = db - .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).lastInsertRowid; + .prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder) VALUES (?, ?, ?, ?, ?, ?)`) + .run(file.id, safeName(file.name), file.mimeType, Number(file.size ?? 0), file.webViewLink, file.folder).lastInsertRowid; console.log(`files: ${file.name} picked up from Drive`); // 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); @@ -158,7 +205,16 @@ files.get("/files", async (c) => { .get("db") .prepare(`${SELECT} ${q ? "WHERE f.name LIKE ?" : ""} ORDER BY f.created_at DESC, f.id DESC LIMIT ${MAX_LIST}`) .all(...(q ? [`%${q}%`] : [])); - return c.json({ files: rows.map(shape), ready: driveReady(), refused: [...refused.values()].map((r) => r.name) }, 200, NO_STORE); + // Every folder Drive has, and any a file names that the last look + // 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( @@ -189,10 +245,12 @@ files.post( return c.json({ error: "Only PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A and zip files." }, 415); } 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; try { - uploaded = await driveUpload(FOLDER, name, mime, buffer); + uploaded = await driveUpload(inDrive(folder), name, mime, buffer); } catch (err) { console.warn(`files: upload of ${name} failed: ${err.message}`); return c.json({ error: `Google Drive didn't take it: ${err.message}` }, 502); @@ -213,8 +271,8 @@ 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; + .prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`) + .run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, folder, user.id).lastInsertRowid; const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id); console.log(`files: ${name} uploaded by ${user.email}`); @@ -229,6 +287,86 @@ function findOr404(c) { 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) => { const row = findOr404(c); if (!row) return c.json({ error: "No such file." }, 404); diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 07a55c1..c845079 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -2,13 +2,15 @@ MEDIA ROUTES: mounted under /api/admin 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 uploads folder by hand first (registerLooseFiles, at most every SCAN_EVERY_MS) POST /media upload one image (multipart: file, - keep_original) + keep_original, folder: FOLDERS in + media.js, default images) GET /media/:id/uses which records name this file DELETE /media/:id remove the row and the file POST /link-preview a page's title, description and @@ -29,9 +31,11 @@ import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; import { + FOLDERS, MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, + publicPath, registerLooseFiles, remove, store, @@ -59,7 +63,8 @@ function shape(row) { id: row.id, // A hand-copied file keeps its own name, which may need escaping // in a URL (a space, say); uploads' random names never do. - url: `${PUBLIC_PREFIX}${encodeURIComponent(row.filename)}`, + url: publicPath(row.filename), + folder: row.filename.includes("/") ? row.filename.split("/")[0] : null, original_name: row.original_name, content_type: row.content_type, bytes: row.bytes, @@ -77,8 +82,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 back out so nothing is left on disk that the library can't see. */ -export async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) { - const stored = await store(buf, { keepOriginal }); +export async function addToLibrary(db, buf, { originalName, keepOriginal, userId, folder }) { + const stored = await store(buf, { keepOriginal, folder }); try { const { lastInsertRowid } = db .prepare( @@ -113,7 +118,8 @@ media.get("/media", async (c) => { // ?type=image (what image fields pick from), video or audio // (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 where = [q && "m.original_name LIKE ?", type && "m.content_type LIKE ?"].filter(Boolean); + 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 ?", folder && "m.filename LIKE ?"].filter(Boolean); const rows = c .get("db") .prepare( @@ -122,7 +128,7 @@ media.get("/media", async (c) => { ORDER BY m.created_at DESC, m.id DESC LIMIT ${MAX_LIST}`, ) - .all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : [])); + .all(...(q ? [`%${q}%`] : []), ...(type ? [`${type}/%`] : []), ...(folder ? [`${folder}/%`] : [])); return c.json({ media: rows.map(shape) }, 200, NO_STORE); }); @@ -151,6 +157,7 @@ media.post( const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), { originalName: file.name, keepOriginal: body.keep_original === "1", + folder: body.folder, userId: user.id, }); @@ -179,6 +186,7 @@ media.post("/link-preview", requireRole("editor"), async (c) => { try { const row = await addToLibrary(c.get("db"), await fetchImage(page.image), { originalName: `preview ${new URL(page.image).hostname}`, + folder: "thumbnails", keepOriginal: false, userId: user.id, }); @@ -206,6 +214,7 @@ function usesOf(db, filename) { return recordsNaming(db, [ `${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, + publicPath(filename), filename, ]); } diff --git a/server/src/routes/people.js b/server/src/routes/people.js index 8200c24..38cb92f 100644 --- a/server/src/routes/people.js +++ b/server/src/routes/people.js @@ -22,6 +22,7 @@ import { Hono } from "hono"; import { asBool, json, loadOwned, marks, paragraphs, splitLinks } from "../shape.js"; +import { postsBy } from "./blog.js"; const people = new Hono(); @@ -284,6 +285,8 @@ people.get("/people/:id", (c) => { roles, events: [...byEvent.values()], awards, + // Blog posts they wrote (published and listed). + posts: postsBy(db, id), }, }); }); diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js index 9412837..7a4aa98 100644 --- a/server/src/routes/requests.js +++ b/server/src/routes/requests.js @@ -39,9 +39,43 @@ const CATEGORIES = { }; 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; -// Where in the shared drive the files go (googleService.js). +// Where in the shared drive the files go (googleService.js): a +// folder per type under Requests, eg. Requests/Chapters. const DRIVE_FOLDER = "Requests"; +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_FILE_BYTES = 10 * 1024 * 1024; @@ -87,6 +121,7 @@ requests.post( const message = field("message", LIMITS.message); const name = field("name", LIMITS.name); 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 errors = {}; @@ -122,10 +157,20 @@ requests.post( db .prepare( `INSERT INTO feedback - (feedback_type, category, request_action, subject, message, name, email, user_agent, ip_hash) - VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?)`, + (feedback_type, category, request_action, subject, details, message, name, email, user_agent, ip_hash) + 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, ); @@ -134,7 +179,7 @@ requests.post( const stored = []; try { for (const file of uploads) { - stored.push({ ...file, driveId: (await driveUpload(DRIVE_FOLDER, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id }); + stored.push({ ...file, driveId: (await driveUpload(`${DRIVE_FOLDER}/${TYPE_FOLDERS[category]}`, `Request ${id} - ${file.name}`, file.mime, file.buffer)).id }); } } catch (err) { console.warn(`feedback #${id}: Drive upload failed: ${err.message}`); @@ -153,6 +198,7 @@ requests.post( `${action === "new" ? "New" : "Update"} ${category}: ${subject}`, `From: ${name ? `${name} <${email}>` : email}`, ...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []), + ...Object.entries(details ?? {}).map(([key, value]) => `${key.replace(/_/g, " ")}: ${value}`), "", message, ], diff --git a/src/components/admin/DriveFiles.tsx b/src/components/admin/DriveFiles.tsx index c81b163..ef53e90 100644 --- a/src/components/admin/DriveFiles.tsx +++ b/src/components/admin/DriveFiles.tsx @@ -11,6 +11,9 @@ or an icon for its type FilePicker the dialog behind a link field's "Choose a 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 else needs to know where it came from. Files put in the Drive @@ -42,10 +45,42 @@ export type DriveFile = { bytes: number; url: string; preview: string | null; + /** Its folder under Media: "" for Media itself. */ + folder: string; uploaded_by: string | null; 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 ( +
+ {tabs.map(([tab, label]) => ( + + ))} +
+ ); +} + const button = "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"; @@ -75,6 +110,7 @@ function TypeIcon({ mime }: { mime: string }) { export function useDriveFiles(query: string) { const [items, setItems] = useState(null); + const [folders, setFolders] = useState([]); const [ready, setReady] = useState(true); // Files in the Drive folder that Drive wouldn't share publicly. const [refused, setRefused] = useState([]); @@ -86,6 +122,7 @@ export function useDriveFiles(query: string) { get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 }) .then((data) => { setItems(data.files); + setFolders(data.folders ?? []); setReady(data.ready); setRefused(data.refused ?? []); }) @@ -93,12 +130,21 @@ export function useDriveFiles(query: string) { }, [query]); useEffect(reload, [reload]); - return { items, ready, refused, error, reload, setItems }; + return { items, folders, ready, refused, error, reload, setItems }; } /* ── Upload ──────────────────────────────────────────────────── */ -export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) { +export function FileUploadButton({ + onUploaded, + label = "Upload files", + folder = "", +}: { + onUploaded: (file: DriveFile) => void; + label?: string; + /** Under Media; "" for Media itself. */ + folder?: string; +}) { const inputRef = useRef(null); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); @@ -112,6 +158,7 @@ export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUpl setBusy(file.name); const form = new FormData(); form.append("file", file); + form.append("folder", folder); try { onUploaded((await upload("/admin/files", form)).file); } catch (err) { @@ -206,7 +253,8 @@ export function FilePicker({ }) { const { user } = useAuth(); const [query, setQuery] = useState(""); - const { items, ready, refused, error, setItems } = useDriveFiles(query); + const { items, folders, ready, refused, error, setItems } = useDriveFiles(query); + const [tab, setTab] = useState(ALL_FOLDERS); const dialogRef = useRef(null); useEffect(() => { @@ -225,7 +273,7 @@ export function FilePicker({ onClick={(e) => { if (e.target === dialogRef.current) dialogRef.current?.close(); }} - className="w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" + className="m-auto w-[min(48rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" >
@@ -247,10 +295,17 @@ export function FilePicker({
+ {folders.length > 0 && ( +
+ +
+ )} + {roleCanWrite(user) && ready && (
{ setItems((current) => [file, ...(current ?? [])]); pick(file); @@ -268,7 +323,7 @@ export function FilePicker({ ) : items === null ? (

Loading…

) : ( - + )}
diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx index c0c2c88..86c12b2 100644 --- a/src/components/admin/MediaLibrary.tsx +++ b/src/components/admin/MediaLibrary.tsx @@ -17,6 +17,11 @@ description and preview image (the image lands in 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/' 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 @@ -47,8 +52,42 @@ export type MediaItem = { processed: boolean; uploaded_by: string | null; 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. */ +export function FolderTabs({ value, onChange }: { value: string; onChange: (folder: ImageFolder) => void }) { + return ( +
+ {IMAGE_FOLDERS.map(([folder, label]) => ( + + ))} +
+ ); +} + const button = "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"; @@ -77,17 +116,18 @@ export function mediaSize(item: MediaItem) { /* ── Data ────────────────────────────────────────────────────── */ -export function uploadImage(file: File, keepOriginal: boolean): Promise { +export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise { const form = new FormData(); form.append("file", file); if (keepOriginal) form.append("keep_original", "1"); + if (folder) form.append("folder", folder); return upload("/admin/media", form).then((data) => data.media); } /* `type` narrows to one kind of file: image fields pick images only. Blank lists everything, videos and audio saved from the clip tool included. */ -export function useMediaLibrary(query: string, type?: "image" | "video" | "audio") { +export function useMediaLibrary(query: string, type?: "image" | "video" | "audio", folder?: string) { const [items, setItems] = useState(null); const [error, setError] = useState(null); @@ -96,13 +136,14 @@ export function useMediaLibrary(query: string, type?: "image" | "video" | "audio const params = new URLSearchParams(); if (q) params.set("q", q); if (type) params.set("type", type); + if (folder) params.set("folder", folder); setError(null); get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 }) .then((data) => setItems(data.media)) .catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the library."), ); - }, [query, type]); + }, [query, type, folder]); useEffect(reload, [reload]); @@ -115,10 +156,13 @@ export function UploadButton({ onUploaded, multiple = false, label = "Upload", + folder, }: { onUploaded: (item: MediaItem) => void; multiple?: boolean; label?: string; + /** Where it goes; blank: the server's default, images. */ + folder?: string; }) { const inputRef = useRef(null); const keepId = useId(); @@ -135,7 +179,7 @@ export function UploadButton({ // name the file it happened to. for (const file of Array.from(files)) { try { - onUploaded(await uploadImage(file, keepOriginal)); + onUploaded(await uploadImage(file, keepOriginal, folder)); } catch (err) { const why = err instanceof ApiError ? err.message : "Upload failed."; setError(files.length > 1 ? `${file.name}: ${why}` : why); @@ -265,16 +309,20 @@ export function MediaGrid({ export function MediaPicker({ selected, + folder = "images", onPick, onClose, }: { selected?: string | null; + /** The field's folder: the tab it opens on, where uploads go. */ + folder?: string; onPick: (item: MediaItem) => void; onClose: () => void; }) { const { user } = useAuth(); const [query, setQuery] = useState(""); - const { items, error, setItems } = useMediaLibrary(query, "image"); + const [tab, setTab] = useState(folder); + const { items, error, setItems } = useMediaLibrary(query, "image", tab); const dialogRef = useRef(null); // showModal gives focus trapping, Escape and the backdrop for free. @@ -290,7 +338,7 @@ export function MediaPicker({ // A click on the backdrop lands on the dialog itself. if (e.target === dialogRef.current) dialogRef.current?.close(); }} - className="w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" + className="m-auto w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" >
@@ -312,10 +360,15 @@ export function MediaPicker({
+
+ +
+ {roleCanWrite(user) && (
{ setItems((current) => [item, ...(current ?? [])]); onPick(item); @@ -353,6 +406,7 @@ export function ImageInput({ id, value, resolve, + folder, locked, className, onChange, @@ -360,6 +414,8 @@ export function ImageInput({ id: string; value: string | null | undefined; resolve?: (file?: string | null) => string | null; + /** The field's `folder` (logos for logo fields); default images. */ + folder?: string; locked: boolean; className: string; onChange: (value: string) => void; @@ -399,7 +455,7 @@ export function ImageInput({ /> {editable && (
- onChange(item.url)} /> + onChange(item.url)} /> @@ -419,6 +475,7 @@ export function ImageInput({ {picking && ( onChange(item.url)} onClose={() => setPicking(false)} /> diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 5dbb331..a8f0371 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -69,7 +69,9 @@ `widget: "image"` is a text box with a preview and upload and library buttons beside it (ImageInput in MediaLibrary.tsx). Its `resolve` option is the media.ts helper for the field's public/ - directory, so a bare filename previews from the right place. + directory, so a bare filename previews from the right place. Its + `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: @@ -347,6 +349,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: id={id} value={value} resolve={field.resolve} + folder={field.folder} locked={locked} className={locked ? inputLocked : common.className} onChange={onChange} diff --git a/src/data/requestTypes.ts b/src/data/requestTypes.ts index dc6ef8e..5dff828 100644 --- a/src/data/requestTypes.ts +++ b/src/data/requestTypes.ts @@ -9,29 +9,230 @@ A link can open the form on one: requestLink("chapter") is /request?type=chapter. People, teams and awards have no buttons on 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 const REQUEST_TYPES: { +export type RequestField = { + 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; label: string; hint: string; actions: RequestAction[]; // What the name field asks, for a new one and for an update. subject: string; -}[] = [ - { id: "blog", label: "Blog post", hint: "A story or article for the community blog", actions: ["new"], subject: "Its title" }, - { id: "event", label: "Event", hint: "A retreat, gathering or calendar event", actions: ["new", "update"], subject: "The event's name" }, - { 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" }, - { id: "team", label: "Team", hint: "A team or committee", actions: ["new", "update"], subject: "The team's name" }, - { id: "award", label: "Award", hint: "An award and who received it", actions: ["new", "update"], subject: "The award's name" }, - { id: "person", label: "Person", hint: "Someone's profile", actions: ["new", "update"], subject: "Their name" }, + entity: string; + heading: string; + preset?: Record; + fields: RequestField[]; +}; + +const CITY: RequestField = { key: "city", label: "City", to: { path: "locality" } }; +const STATE: RequestField = { key: "state", label: "State or province", placeholder: "eg. MO", to: { path: "state_code" } }; +const COUNTRY: RequestField = { key: "country", label: "Country", placeholder: "eg. US", to: { path: "country" } }; +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}`; -const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t.label])); -export const requestTypeLabel = (id: string) => BY_ID.get(id) ?? id; +const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t])); +export const requestType = (id: string) => BY_ID.get(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 }[]; +}; + +export function fromRequest( + row: { id: number; category: string; request_action: string; subject?: string | null; details?: Record | 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 }; +} diff --git a/src/lib/adminSchema/awards.ts b/src/lib/adminSchema/awards.ts index 02c83d7..645587c 100644 --- a/src/lib/adminSchema/awards.ts +++ b/src/lib/adminSchema/awards.ts @@ -42,7 +42,7 @@ export const awards = { }, { path: "name", label: "Name", required: true }, { path: "description", label: "Description", widget: "textarea", full: true }, - { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true }, + { path: "logo", label: "Logo", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, ], }, { diff --git a/src/lib/adminSchema/events.ts b/src/lib/adminSchema/events.ts index ec19dc7..f382b7a 100644 --- a/src/lib/adminSchema/events.ts +++ b/src/lib/adminSchema/events.ts @@ -144,8 +144,8 @@ export const events = { { legend: "Appearance", fields: [ - { path: "event_logo", label: "Event logo", widget: "image", resolve: mediaUrl, full: true }, - { path: "org_logo", label: "Org logo override", widget: "image", resolve: mediaUrl, full: true }, + { path: "event_logo", label: "Event logo", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, + { path: "org_logo", label: "Org logo override", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, { path: "color", label: "Colour", widget: "color" }, { path: "card_image", diff --git a/src/lib/adminSchema/organizations.ts b/src/lib/adminSchema/organizations.ts index 0de2da6..39403f7 100644 --- a/src/lib/adminSchema/organizations.ts +++ b/src/lib/adminSchema/organizations.ts @@ -42,7 +42,7 @@ export const organizations = { { path: "short_name", label: "Short name" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true }, + { path: "logo", label: "Logo", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, ], }, { diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts index ed49905..ddf5ab6 100644 --- a/src/lib/adminSchema/siteSettings.ts +++ b/src/lib/adminSchema/siteSettings.ts @@ -80,6 +80,7 @@ export const siteSettings = { path: "favicon", label: "Favicon", widget: "image", + folder: "logos", resolve: mediaUrl, full: true, help: "The browser-tab icon: a square PNG (512px) or an SVG. Keep original when uploading an SVG.", @@ -88,6 +89,7 @@ export const siteSettings = { path: "apple_touch_icon", label: "Home-screen icon", widget: "image", + folder: "logos", resolve: mediaUrl, full: true, help: "For iPhones saving the site to their home screen: a square PNG, 180px, no transparency.", diff --git a/src/lib/adminSchema/teams.ts b/src/lib/adminSchema/teams.ts index 805bdbe..dd1ba3d 100644 --- a/src/lib/adminSchema/teams.ts +++ b/src/lib/adminSchema/teams.ts @@ -47,7 +47,7 @@ export const teams = { { path: "name", label: "Name", required: true, help: "Board, Leadership Team" }, { path: "tagline", label: "Tagline", full: true }, { path: "color", label: "Colour", widget: "color" }, - { path: "logo", label: "Logo", widget: "image", resolve: mediaUrl, full: true }, + { path: "logo", label: "Logo", widget: "image", folder: "logos", resolve: mediaUrl, full: true }, ], }, { legend: "Publishing", fields: PUBLISH_FIELDS }, diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts index b7b483f..34a31b5 100644 --- a/src/lib/useContent.ts +++ b/src/lib/useContent.ts @@ -11,6 +11,7 @@ * hrefs.ts has already logged the component that produced it. */ +import type { BlogPostSummary } from './useBlog.ts' import { detailPath } from './hrefs.ts' import { useRecord, type Resource } from './useRecord.ts' import type { EventType } from './eventTypes.ts' @@ -356,6 +357,8 @@ export type PersonRecord = { roles: PersonRole[] events: PersonEvent[] awards: PersonAward[] + /** Blog posts they wrote, newest first. */ + posts: BlogPostSummary[] } export const usePerson = (id?: string): Resource => diff --git a/src/lib/version.ts b/src/lib/version.ts index c3580b3..63e522a 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.9.11-content-display"; +export const SITE_VERSION = "NGU-Web.v1.9.12-content-display"; diff --git a/src/pages/PersonDetail.tsx b/src/pages/PersonDetail.tsx index 274eab7..b3eab74 100644 --- a/src/pages/PersonDetail.tsx +++ b/src/pages/PersonDetail.tsx @@ -24,6 +24,7 @@ import PageShell, { type ShellSection } from '../components/PageShell.tsx' import PageState from '../components/PageState.tsx' import PlatformIcon from '../components/PlatformIcon.tsx' import ContentBlocks from '../components/ContentBlocks.tsx' +import { PostCard } from './sections/CommunityBlog.tsx' import { usePerson, type PersonEvent, @@ -190,6 +191,24 @@ export default function PersonDetail() { }) } + if (person.posts?.length > 0) { + sections.push({ + id: 'posts', + title: 'Blog posts', + accent, + background: BACKGROUNDS[sections.length % 2], + content: ( +
+
    + {person.posts.map((post) => ( + + ))} +
+
+ ), + }) + } + return ( ) diff --git a/src/pages/admin/AdminFeedback.tsx b/src/pages/admin/AdminFeedback.tsx index 4535deb..83b2129 100644 --- a/src/pages/admin/AdminFeedback.tsx +++ b/src/pages/admin/AdminFeedback.tsx @@ -24,7 +24,7 @@ import { del, get, patch, post, ApiError } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts"; import { feedbackTypeLabel } from "../../data/feedbackTypes.ts"; -import { requestTypeLabel } from "../../data/requestTypes.ts"; +import { fromRequest, requestType, requestTypeLabel } from "../../data/requestTypes.ts"; const STATUSES = ["new", "read", "actioned", "archived", "spam"]; @@ -104,6 +104,111 @@ function RequestFiles({ row, canWrite }) { ); } +/* 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 ( +
+ {entries.map(([key, value]) => ( +
+
{labels.get(key) ?? key.replace(/_/g, " ")}
+
{value as string}
+
+ ))} +
+ ); +} + +/* 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(null); + const [picked, setPicked] = useState(""); + const [error, setError] = useState(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 ( +
+ +
+ ); + } + + 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 ( +
+ {candidates === null ? ( + + ) : candidates.length === 0 ? ( + No {type.label.toLowerCase()} records yet. + ) : ( + <> + + + + + )} + {error && {error}} +
+ ); +} + function locationOf(row) { if (!row.page_path) return "Not page-specific"; return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path; @@ -170,7 +275,9 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) { {row.subject &&

{row.subject}

}

{row.message}

+ {row.feedback_type === "content" && } {row.files?.length > 0 && } + {row.feedback_type === "content" && canWrite && }

{row.name || row.email ? ( diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index f8d2ed8..2f91851 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -17,17 +17,22 @@ import { useState } from "react"; -import { ApiError, del, get } from "../../lib/api.ts"; +import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; import { + ALL_FOLDERS, + DriveFolderTabs, FILE_HELP, FileList, FileUploadButton, RefusedNote, + inFolder, useDriveFiles, + type DriveFile, } from "../../components/admin/DriveFiles.tsx"; import { + FolderTabs, MediaGrid, UPLOAD_HELP, UploadButton, @@ -140,17 +145,153 @@ 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(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) { + 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 ( +

+ {mode ? ( + <> + + 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" + /> + + + + ) : ( + <> + + {inside && ( + + )} + {inside && canDelete(user) && ( + + )} + + )} + {error && {error}} +
+ ); +} + +/* 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(null); + return ( +
+ + {error &&

{error}

} +
+ ); +} + function FilesTab() { const { user } = useAuth(); const [query, setQuery] = useState(""); - const { items, ready, refused, error, setItems } = useDriveFiles(query); + const { items, folders, ready, refused, error, reload, 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 ( <>
{roleCanWrite(user) && ready && (
- setItems((current) => [file, ...(current ?? [])])} /> + setItems((current) => [file, ...(current ?? [])])} + />

{FILE_HELP}

)} @@ -167,6 +308,19 @@ function FilesTab() { Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.

)} + {ready && ( +
+ + { + setTab(next); + reload(); + }} + /> +
+ )} +
{error ? ( @@ -175,9 +329,10 @@ function FilesTab() {

Loading…

) : ( (
+ {roleCanWrite(user) && } Open in Drive @@ -209,8 +364,10 @@ const TABS = [ export default function AdminMedia() { const { user } = useAuth(); 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 { items, error, setItems } = useMediaLibrary(query); + const { items, error, setItems } = useMediaLibrary(query, undefined, folder); return (
@@ -245,12 +402,17 @@ export default function AdminMedia() { ) : ( <> +
+ +
+
{roleCanWrite(user) && (
setItems((current) => [item, ...(current ?? [])])} />

{UPLOAD_HELP}

diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx index 05180a4..9292588 100644 --- a/src/pages/admin/EntityEdit.tsx +++ b/src/pages/admin/EntityEdit.tsx @@ -88,6 +88,10 @@ export default function EntityEdit() { useWideAdminPage(); 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: // superadmin), matching the server's writeRole. const canWrite = atLeast(user, manifest?.writeRole ?? "editor"); @@ -172,8 +176,18 @@ export default function EntityEdit() { // sending "" would be an explicit value rather than an absence. const blank = autoId ? {} : { id: "" }; for (const child of manifest.children ?? []) blank[child.key] = []; - setForm(blank); + // The baseline stays the empty form, so a filled-in one counts + // as unsaved until Create. 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 { const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 }); setForm(data.row); @@ -189,7 +203,8 @@ export default function EntityEdit() { } finally { setLoading(false); } - }, [manifest, id, isNew, autoId, navigate]); + // prefixOf and headingPath follow the manifest, already a dependency. + }, [manifest, id, isNew, autoId, navigate, fromRequest]); useEffect(() => { load(); @@ -368,6 +383,15 @@ export default function EntityEdit() { + {fromRequest && ( + setForm((prev) => ({ ...prev, [child]: [...(prev[child] ?? []), row] }))} + /> + )} {/* Straight in the page, not wrapped: a sticky element only travels within its parent, so its parent has to be tall. */} @@ -551,3 +575,74 @@ function ImportedNote() {

); } + +/* 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>(() => 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 ( +

+ Filled in from content request #{request.request}. Check it, fill in the rest, then Create. It isn't saved yet. +

+ ); + } + + 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 ( +

+ Content request #{request.request} has no details to copy; its message is in Forms → Content requests. +

+ ); + } + + return ( +
+

Requested in content request #{request.request}

+

Use what should change, then Save changes.

+
    + {items.map((item) => ( +
  • + {item.label} + {"path" in item ? ( + <> + + now {item.current ? {String(item.current)} : "blank"}, requested {item.value} + + {done.has(item.key) || String(item.current ?? "") === item.value ? ( + in the form + ) : ( + + )} + + ) : done.has(item.key) ? ( + added below + ) : ( + + )} +
  • + ))} +
+
+ ); +} + diff --git a/src/pages/sections/CommunityBlog.tsx b/src/pages/sections/CommunityBlog.tsx index dd7e4f0..3d733a0 100644 --- a/src/pages/sections/CommunityBlog.tsx +++ b/src/pages/sections/CommunityBlog.tsx @@ -36,7 +36,8 @@ const DEFAULTS = { const EXCERPT_CHARS = 180 -function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) { +/* One post as a card; person pages list their posts with it too. */ +export function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) { const cover = useSmallImage(mediaUrl(post.cover_image)) const date = postDate(post.published_on) const authors = post.authors.map((author) => author.name).join(', ') diff --git a/src/pages/sections/RequestForm.tsx b/src/pages/sections/RequestForm.tsx index 7392ec0..7df43ad 100644 --- a/src/pages/sections/RequestForm.tsx +++ b/src/pages/sections/RequestForm.tsx @@ -6,6 +6,10 @@ ?type=chapter in the address picks one to start with, which is how 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 (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. @@ -48,6 +52,8 @@ export default function RequestForm() { const [files, setFiles] = useState([]); const [name, setName] = useState(""); const [email, setEmail] = useState(""); + // By field key; kept when the type changes, since types share keys. + const [details, setDetails] = useState>({}); const [website, setWebsite] = useState(""); // honeypot const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle"); @@ -92,6 +98,15 @@ export default function RequestForm() { form.set("message", message.trim()); form.set("name", name.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); for (const file of files) form.append("files", file); @@ -111,6 +126,7 @@ export default function RequestForm() { function reset() { setSubject(""); + setDetails({}); setMessage(""); setFiles([]); setStatus("idle"); @@ -204,6 +220,45 @@ export default function RequestForm() { {fieldErrors.subject}
+ {type.fields.length > 0 && ( +
+ + Details + + +

+ {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."} +

+
+ {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 ( +
+ + {f.input === "textarea" ? ( +