Request details, Drive folders, image folders, clip tool to Drive (v1.9.12 to v1.9.14-content-display) #16
40 changed files with 2058 additions and 181 deletions
|
|
@ -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/<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, 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`).
|
||||
|
||||
## 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.
|
||||
|
|
|
|||
|
|
@ -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/<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` |
|
||||
| `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("<Folder>", name, mime, bytes)` from
|
||||
`server/src/googleService.js`; a path such as `"Media/2026"` makes each
|
||||
|
|
@ -78,7 +78,22 @@ 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.
|
||||
|
||||
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)
|
||||
|
||||
|
|
@ -201,7 +216,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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 `<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, 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`). |
|
||||
| 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. |
|
||||
|
|
|
|||
|
|
@ -9,11 +9,26 @@ Facebook links; the server downloads it, then you cut clips from it:
|
|||
the crop; the white box over the video shows what's kept.
|
||||
- **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
|
||||
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
|
||||
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
|
||||
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`.
|
||||
|
|
|
|||
|
|
@ -490,9 +490,10 @@ export function kick(db = dbRef) {
|
|||
|
||||
export const fileOf = (job) => (job?.file ? filePath(job.file) : null);
|
||||
|
||||
/* A finished clip into the media library: copied into the uploads
|
||||
directory under a random name, given a media row, and its working
|
||||
file deleted. Returns the media row's id. */
|
||||
/* A finished clip, or a whole downloaded video, into the media
|
||||
library: copied into the uploads directory under a random name and
|
||||
given a media row. A clip's working file is deleted; a video's is
|
||||
kept for cutting. Returns the media row's id. */
|
||||
export async function saveToLibrary(db, job, userId) {
|
||||
const from = fileOf(job);
|
||||
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
|
||||
|
|
@ -528,7 +529,11 @@ export async function saveToLibrary(db, job, userId) {
|
|||
const { size } = await stat(from);
|
||||
const params = JSON.parse(job.params ?? "{}");
|
||||
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
|
||||
const label = `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`;
|
||||
// A whole download is named for itself; a clip for its span.
|
||||
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", () =>
|
||||
Number(
|
||||
|
|
@ -546,8 +551,14 @@ export async function saveToLibrary(db, job, userId) {
|
|||
throw err;
|
||||
}
|
||||
|
||||
await rm(from, { force: true });
|
||||
update(db, job.id, { saved_media_id: id, file: null });
|
||||
// A clip's working file goes; a downloaded video's stays, to cut
|
||||
// clips from (the day's sweep clears it).
|
||||
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}` };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,9 @@
|
|||
Setup: docs/google-drive-and-mail.md.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createReadStream, readFileSync } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { createSign } from "node:crypto";
|
||||
|
||||
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
|
||||
|
|
@ -99,11 +101,11 @@ async function accessToken(scope, subject) {
|
|||
return data.access_token;
|
||||
}
|
||||
|
||||
async function call(url, init, scope, subject) {
|
||||
async function call(url, init, scope, subject, timeoutMs = 60_000) {
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.json().catch(() => null);
|
||||
|
|
@ -124,6 +126,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,10 +136,21 @@ 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;
|
||||
const walked = [];
|
||||
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 query = new URLSearchParams({
|
||||
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,
|
||||
|
|
@ -187,16 +201,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 +225,88 @@ 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,
|
||||
);
|
||||
}
|
||||
|
||||
/* 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.
|
||||
Refused when the shared drive (or the Workspace) doesn't allow
|
||||
sharing outside the organization. */
|
||||
|
|
@ -244,8 +339,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 ───────────────────────────────────────────────────── */
|
||||
|
|
|
|||
|
|
@ -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`))
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
12
server/src/migrations/049_request_details.sql
Normal file
12
server/src/migrations/049_request_details.sql
Normal file
|
|
@ -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));
|
||||
10
server/src/migrations/050_drive_file_folders.sql
Normal file
10
server/src/migrations/050_drive_file_folders.sql
Normal file
|
|
@ -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 '';
|
||||
10
server/src/migrations/051_clip_drive.sql
Normal file
10
server/src/migrations/051_clip_drive.sql
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 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;
|
||||
|
|
@ -11,7 +11,9 @@
|
|||
import { Hono } from "hono";
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
import { driveDelete, driveDownload } from "../googleService.js";
|
||||
import { driveDelete, driveDownload, driveReady, driveTree } 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 { importDocx } from "./import.js";
|
||||
|
||||
|
|
@ -30,20 +32,43 @@ 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) {
|
||||
/* The ids of every file under Requests in Drive (any type folder),
|
||||
looked up at most every 30 seconds; null when Drive isn't set up or
|
||||
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;
|
||||
const files = db
|
||||
.prepare(
|
||||
`SELECT id, feedback_id, name, mime, size FROM feedback_files
|
||||
`SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files
|
||||
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
|
||||
)
|
||||
.all(...rows.map((r) => r.id));
|
||||
return rows.map((row) => ({
|
||||
...row,
|
||||
files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
|
||||
// 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, drive_id, ...f }) => ({ ...f, missing: ids ? !ids.has(drive_id) : false })),
|
||||
}));
|
||||
}
|
||||
const MAX_LIMIT = 200;
|
||||
|
|
@ -60,7 +85,7 @@ const NOTE_LIMIT = 2000;
|
|||
?limit=50
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
admin.get("/feedback", (c) => {
|
||||
admin.get("/feedback", async (c) => {
|
||||
const db = c.get("db");
|
||||
const { status, type, kind, q, before, limit } = c.req.query();
|
||||
|
||||
|
|
@ -100,7 +125,7 @@ admin.get("/feedback", (c) => {
|
|||
.all(...params, take + 1); // one extra to detect a next page
|
||||
|
||||
const hasMore = rows.length > take;
|
||||
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
|
||||
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null);
|
||||
|
||||
// Status counts cover this queue (kind) but ignore the other
|
||||
// filters: the tabs show what's waiting, not what's left after a
|
||||
|
|
@ -170,7 +195,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
|
|||
|
||||
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
|
||||
|
||||
const result = db_update(c.get("db"), id, sets, params);
|
||||
const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive());
|
||||
if (!result) return c.json({ error: "No such feedback." }, 404);
|
||||
|
||||
console.log(`feedback #${id} updated by ${c.get("user").email}`);
|
||||
|
|
@ -178,14 +203,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
|
|||
return c.json({ feedback: result }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
function db_update(db, id, sets, params) {
|
||||
function db_update(db, id, sets, params, ids) {
|
||||
const changed = db
|
||||
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
|
||||
.run(...params, id);
|
||||
|
||||
if (changed.changes === 0) return null;
|
||||
|
||||
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
|
||||
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0];
|
||||
}
|
||||
|
||||
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
|
||||
|
|
@ -219,9 +244,16 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
|
|||
});
|
||||
|
||||
/* ── A content request's files ───────────────────────────────────
|
||||
GET /feedback/:id/files/:file download, from Drive
|
||||
POST /feedback/:id/files/:file/blog-post a .docx as a new
|
||||
unpublished blog post (import.js), editors and up
|
||||
GET /feedback/:id/files/:file download, from Drive
|
||||
POST /feedback/:id/files/:file/blog-post a .docx as a new
|
||||
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) {
|
||||
|
|
@ -256,6 +288,29 @@ 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) => {
|
||||
const file = fileOf(c);
|
||||
if (!file) return c.json({ error: "No such file." }, 404);
|
||||
|
|
@ -268,4 +323,45 @@ 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;
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -11,8 +11,13 @@
|
|||
GET /clips/:id/download a finished clip, as an attachment;
|
||||
its file is deleted once it has
|
||||
gone out in full, unless saved
|
||||
POST /clips/:id/save a finished clip into the media
|
||||
POST /clips/:id/save a finished clip, or a whole
|
||||
downloaded video, into the media
|
||||
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
|
||||
takes its clips)
|
||||
|
||||
|
|
@ -23,6 +28,7 @@
|
|||
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
|
@ -40,6 +46,9 @@ import {
|
|||
toolVersions,
|
||||
} from "../clips.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();
|
||||
|
||||
|
|
@ -71,15 +80,19 @@ function shape(job) {
|
|||
has_file: Boolean(job.file),
|
||||
saved_media_id: job.saved_media_id,
|
||||
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,
|
||||
created_at: job.created_at,
|
||||
finished_at: job.finished_at,
|
||||
};
|
||||
}
|
||||
|
||||
const SELECT = `SELECT j.*, m.filename AS saved_filename
|
||||
const SELECT = `SELECT j.*, m.filename AS saved_filename, d.url AS saved_drive_url, d.folder AS saved_drive_folder
|
||||
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) {
|
||||
const id = Number(c.req.param("id"));
|
||||
|
|
@ -203,13 +216,61 @@ clips.get("/clips/:id/download", async (c) => {
|
|||
clips.post("/clips/:id/save", async (c) => {
|
||||
const db = c.get("db");
|
||||
const job = findOr404(c);
|
||||
if (job.kind !== "clip" || job.status !== "done") throw new ClipError(400, "Only a finished clip can be saved.");
|
||||
if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved.");
|
||||
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);
|
||||
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);
|
||||
});
|
||||
|
||||
/* 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) => {
|
||||
const job = findOr404(c);
|
||||
if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish.");
|
||||
|
|
|
|||
|
|
@ -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,53 @@ 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";
|
||||
export 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_LIST = 500;
|
||||
// Seconds after upload to ask Drive for the preview again.
|
||||
|
|
@ -88,6 +137,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 +150,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 +169,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 +202,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 +217,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 +257,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);
|
||||
|
|
@ -212,15 +282,10 @@ 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}`);
|
||||
|
||||
// The first try is waited for; Drive often has the picture already.
|
||||
await fetchPreview(db, row, user.id);
|
||||
return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE);
|
||||
// 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 });
|
||||
return c.json({ file: saved }, 201, NO_STORE);
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -229,6 +294,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);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -54,12 +58,13 @@ let lastScan = 0;
|
|||
/* 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"]);
|
||||
|
||||
function shape(row) {
|
||||
export function shape(row) {
|
||||
return {
|
||||
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,
|
||||
]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
const DRIVE_FOLDER = "Requests";
|
||||
// Where in the shared drive the files go (googleService.js): a
|
||||
// folder per type under Requests, eg. Requests/Chapters.
|
||||
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_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,
|
||||
],
|
||||
|
|
|
|||
|
|
@ -24,8 +24,9 @@
|
|||
a fold-out of description, media, map);
|
||||
text is an optional intro. ScheduleBlock
|
||||
table text: a row per line, cells split by |
|
||||
cards items as link cards: text the title,
|
||||
detail, url, media the picture
|
||||
cards items as link cards, up to three in a row:
|
||||
text the title, detail, url, media the
|
||||
picture
|
||||
divider nothing
|
||||
|
||||
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
|
||||
|
|
@ -95,10 +96,10 @@ function LinkCard({ item }: { item: ContentBlockItem }) {
|
|||
{!img.failed && (
|
||||
<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-5">
|
||||
<span className="text-xs font-semibold text-muted">{where}</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 text-body">{item.detail}</span>}
|
||||
<span className="flex flex-1 flex-col gap-1 p-4">
|
||||
<span className="truncate 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>
|
||||
{item.detail && <span className="line-clamp-3 text-sm leading-snug text-body">{item.detail}</span>}
|
||||
</span>
|
||||
</Anchor>
|
||||
)
|
||||
|
|
@ -224,7 +225,9 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
|
|||
const cards = (block.items ?? []).filter((item) => item.url && item.text)
|
||||
if (cards.length === 0) return null
|
||||
return (
|
||||
<ul className={cards.length === 1 ? 'max-w-xl' : 'grid gap-4 sm:grid-cols-2'}>
|
||||
// One grid whatever the count: a lone card takes a column
|
||||
// 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) => (
|
||||
<li key={i}>
|
||||
<LinkCard item={item} />
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<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 =
|
||||
"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<DriveFile[] | null>(null);
|
||||
const [folders, setFolders] = useState<string[]>([]);
|
||||
const [ready, setReady] = useState(true);
|
||||
// Files in the Drive folder that Drive wouldn't share publicly.
|
||||
const [refused, setRefused] = useState<string[]>([]);
|
||||
|
|
@ -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<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(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<HTMLDialogElement>(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"
|
||||
>
|
||||
<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">
|
||||
|
|
@ -247,10 +295,17 @@ export function FilePicker({
|
|||
</button>
|
||||
</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 && (
|
||||
<div className="border-b border-brand/10 px-5 py-3">
|
||||
<FileUploadButton
|
||||
label="Upload new"
|
||||
label={tab && tab !== ALL_FOLDERS ? `Upload into ${tab}` : "Upload new"}
|
||||
folder={tab === ALL_FOLDERS ? "" : tab}
|
||||
onUploaded={(file) => {
|
||||
setItems((current) => [file, ...(current ?? [])]);
|
||||
pick(file);
|
||||
|
|
@ -268,7 +323,7 @@ export function FilePicker({
|
|||
) : items === null ? (
|
||||
<p className="text-sm text-muted">Loading…</p>
|
||||
) : (
|
||||
<FileList items={items} selected={selected} onPick={pick} />
|
||||
<FileList items={inFolder(items, tab)} selected={selected} onPick={pick} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,10 @@
|
|||
ImageInput the `widget: "image"` form field. A preview, the
|
||||
stored value as editable text, and buttons to
|
||||
upload a new file or pick an earlier one.
|
||||
MediaPicker the dialog behind "Choose from library".
|
||||
MediaPicker the dialog behind "Choose from library". Its From
|
||||
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
|
||||
(pages/admin/AdminMedia.tsx) draw.
|
||||
UploadButton a file input dressed as a button, with the
|
||||
|
|
@ -17,6 +20,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/<file>'
|
||||
for an upload, or, as before, a bare filename in the field's
|
||||
public/ directory or a full URL. So the text box stays: old
|
||||
|
|
@ -32,6 +40,8 @@
|
|||
import { FileAudio, X } from "@phosphor-icons/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 { useAuth } from "../../lib/auth.tsx";
|
||||
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||||
|
|
@ -47,8 +57,51 @@ 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. `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 =
|
||||
"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 +130,18 @@ export function mediaSize(item: MediaItem) {
|
|||
|
||||
/* ── Data ────────────────────────────────────────────────────── */
|
||||
|
||||
export function uploadImage(file: File, keepOriginal: boolean): Promise<MediaItem> {
|
||||
export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise<MediaItem> {
|
||||
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<MediaItem[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
|
|
@ -96,13 +150,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 +170,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<HTMLInputElement>(null);
|
||||
const keepId = useId();
|
||||
|
|
@ -135,7 +193,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);
|
||||
|
|
@ -261,20 +319,94 @@ 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 ───────────────────────────────────────────── */
|
||||
|
||||
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<string>(folder);
|
||||
const fromRequests = tab === REQUESTS_TAB;
|
||||
const { items, error, setItems } = useMediaLibrary(query, "image", fromRequests ? undefined : tab);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
// showModal gives focus trapping, Escape and the backdrop for free.
|
||||
|
|
@ -290,7 +422,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"
|
||||
>
|
||||
<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">
|
||||
|
|
@ -312,10 +444,15 @@ export function MediaPicker({
|
|||
</button>
|
||||
</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) && (
|
||||
<div className="border-b border-brand/10 px-5 py-3">
|
||||
<UploadButton
|
||||
label="Upload new"
|
||||
folder={folder}
|
||||
onUploaded={(item) => {
|
||||
setItems((current) => [item, ...(current ?? [])]);
|
||||
onPick(item);
|
||||
|
|
@ -327,7 +464,16 @@ export function MediaPicker({
|
|||
)}
|
||||
|
||||
<div className="overflow-y-auto px-5 py-4">
|
||||
{error ? (
|
||||
{fromRequests ? (
|
||||
<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>
|
||||
) : items === null ? (
|
||||
<p className="text-sm text-muted">Loading…</p>
|
||||
|
|
@ -353,6 +499,7 @@ export function ImageInput({
|
|||
id,
|
||||
value,
|
||||
resolve,
|
||||
folder,
|
||||
locked,
|
||||
className,
|
||||
onChange,
|
||||
|
|
@ -360,6 +507,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 +548,7 @@ export function ImageInput({
|
|||
/>
|
||||
{editable && (
|
||||
<div className="flex flex-wrap items-start gap-2">
|
||||
<UploadButton onUploaded={(item) => onChange(item.url)} />
|
||||
<UploadButton folder={folder} onUploaded={(item) => onChange(item.url)} />
|
||||
<button type="button" className={button} onClick={() => setPicking(true)}>
|
||||
Choose from library
|
||||
</button>
|
||||
|
|
@ -419,6 +568,7 @@ export function ImageInput({
|
|||
{picking && (
|
||||
<MediaPicker
|
||||
selected={value}
|
||||
folder={folder}
|
||||
onPick={(item) => onChange(item.url)}
|
||||
onClose={() => setPicking(false)}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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<string, string>;
|
||||
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<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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -279,7 +279,7 @@ export const BLOCK_TYPES = [
|
|||
["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."],
|
||||
["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, like a link shared in a chat. Paste a link and press Fetch preview."],
|
||||
["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."],
|
||||
["divider", "Divider", "A thin line between parts."],
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
|
|
|
|||
|
|
@ -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<PersonRecord> =>
|
||||
|
|
|
|||
|
|
@ -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.14-content-display";
|
||||
|
|
|
|||
|
|
@ -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: (
|
||||
<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 (
|
||||
<PageShell title={person.name} intro={person.tagline ?? undefined} sections={sections} />
|
||||
)
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ type Job = {
|
|||
has_file: boolean;
|
||||
saved_media_id: number | 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;
|
||||
};
|
||||
|
||||
|
|
@ -87,6 +89,80 @@ const primary =
|
|||
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";
|
||||
|
||||
/* 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 }) {
|
||||
return (
|
||||
<section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5">
|
||||
|
|
@ -415,6 +491,26 @@ export default function AdminClips() {
|
|||
{openId === s.id ? "Close" : "Make clips"}
|
||||
</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" && (
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -484,7 +580,15 @@ export default function AdminClips() {
|
|||
In the media library
|
||||
</Link>
|
||||
)}
|
||||
{clip.status === "done" && !clip.has_file && !clip.saved_url && (
|
||||
{clip.status === "done" && !clip.saved_drive && (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 }}>
|
||||
Downloaded, and deleted from the server
|
||||
</span>
|
||||
|
|
@ -505,7 +609,7 @@ export default function AdminClips() {
|
|||
))}
|
||||
</ul>
|
||||
<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.
|
||||
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.
|
||||
Everything here is cleared a day after it's made.
|
||||
</p>
|
||||
</Card>
|
||||
|
|
|
|||
|
|
@ -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"];
|
||||
|
||||
|
|
@ -52,10 +52,13 @@ const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB`
|
|||
/* A content request's files: each downloads from Drive through the
|
||||
server, and a Word document can become a draft blog post
|
||||
(the same import as Blog posts → Import from Word). */
|
||||
function RequestFiles({ row, canWrite }) {
|
||||
function RequestFiles({ row, canWrite, canRemove }) {
|
||||
const navigate = useNavigate();
|
||||
const [files, setFiles] = useState<any[]>(row.files);
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
const [confirming, setConfirming] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => setFiles(row.files), [row.files]);
|
||||
|
||||
async function makePost(file) {
|
||||
setBusy(file.id);
|
||||
|
|
@ -69,29 +72,81 @@ function RequestFiles({ row, canWrite }) {
|
|||
}
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="mt-4">
|
||||
<ul className="space-y-2">
|
||||
{row.files.map((file) => (
|
||||
{files.map((file) => (
|
||||
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
|
||||
<a
|
||||
href={`/api/admin/feedback/${row.id}/files/${file.id}`}
|
||||
download={file.name}
|
||||
className="font-medium text-link underline underline-offset-2"
|
||||
>
|
||||
{file.name}
|
||||
</a>
|
||||
{file.missing ? (
|
||||
// Deleted or moved out of Requests in Drive: nothing to open.
|
||||
<span className="font-medium text-muted line-through">{file.name}</span>
|
||||
) : (
|
||||
<a
|
||||
href={`/api/admin/feedback/${row.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">{sizeOf(file.size)}</span>
|
||||
{canWrite && /\.docx$/i.test(file.name) && (
|
||||
{file.missing && (
|
||||
<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
|
||||
type="button"
|
||||
disabled={busy !== null}
|
||||
onClick={() => makePost(file)}
|
||||
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"
|
||||
className={`${small} border-link text-link hover:bg-tint`}
|
||||
>
|
||||
{busy === file.id ? "Making the post…" : "Make a blog post from it"}
|
||||
</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>
|
||||
))}
|
||||
</ul>
|
||||
|
|
@ -104,6 +159,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 (
|
||||
<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) {
|
||||
if (!row.page_path) return "Not page-specific";
|
||||
return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path;
|
||||
|
|
@ -170,7 +330,9 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
|
|||
|
||||
{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>
|
||||
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />}
|
||||
{row.feedback_type === "content" && <RequestDetails row={row} />}
|
||||
{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">
|
||||
{row.name || row.email ? (
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@
|
|||
(MediaLibrary.tsx), so this is housekeeping rather than the way
|
||||
images get in. Files: documents, audio and zips in the shared
|
||||
Google Drive, for pages to link to (DriveFiles.tsx); link fields'
|
||||
"Choose a file" picks from them.
|
||||
"Choose a file" picks from them. Requests: every file sent with
|
||||
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
|
||||
up delete. A delete first asks the server which records still
|
||||
|
|
@ -15,19 +17,26 @@
|
|||
a page (an image field stores the path, not a foreign key).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
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,
|
||||
formatBytes,
|
||||
MediaGrid,
|
||||
UPLOAD_HELP,
|
||||
UploadButton,
|
||||
|
|
@ -140,17 +149,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<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() {
|
||||
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 (
|
||||
<>
|
||||
<div className="mt-6 flex flex-wrap items-start gap-6">
|
||||
{roleCanWrite(user) && ready && (
|
||||
<div className="max-w-md">
|
||||
<FileUploadButton onUploaded={(file) => setItems((current) => [file, ...(current ?? [])])} />
|
||||
<FileUploadButton
|
||||
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>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -167,6 +312,19 @@ function FilesTab() {
|
|||
Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.
|
||||
</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">
|
||||
<RefusedNote names={refused} />
|
||||
{error ? (
|
||||
|
|
@ -175,9 +333,10 @@ function FilesTab() {
|
|||
<p className="text-sm text-muted">Loading…</p>
|
||||
) : (
|
||||
<FileList
|
||||
items={items}
|
||||
items={inFolder(items, tab)}
|
||||
renderActions={(file) => (
|
||||
<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" />
|
||||
<a href={file.url} target="_blank" rel="noreferrer" className="text-xs text-link hover:underline">
|
||||
Open in Drive
|
||||
|
|
@ -201,16 +360,135 @@ 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 = [
|
||||
["images", "Images"],
|
||||
["files", "Files"],
|
||||
["requests", "Requests"],
|
||||
] as const;
|
||||
|
||||
export default function AdminMedia() {
|
||||
const { user } = useAuth();
|
||||
const [tab, setTab] = useState<"images" | "files">("images");
|
||||
const [tab, setTab] = useState<(typeof TABS)[number][0]>("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 (
|
||||
<div>
|
||||
|
|
@ -219,7 +497,9 @@ export default function AdminMedia() {
|
|||
<p className="text-sm text-muted">
|
||||
{tab === "images"
|
||||
? "Uploaded images. Image fields in every editor pick from here."
|
||||
: "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."}
|
||||
: 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 sent with the Request form, in the shared Google Drive's Requests folder. Removing one takes it off its request too."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
@ -240,17 +520,24 @@ export default function AdminMedia() {
|
|||
))}
|
||||
</nav>
|
||||
|
||||
{tab === "files" ? (
|
||||
{tab === "requests" ? (
|
||||
<RequestFilesTab />
|
||||
) : tab === "files" ? (
|
||||
<FilesTab />
|
||||
) : (
|
||||
<>
|
||||
|
||||
<div className="mt-6">
|
||||
<FolderTabs value={folder} onChange={setFolder} />
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex flex-wrap items-start gap-6">
|
||||
{roleCanWrite(user) && (
|
||||
<div className="max-w-md">
|
||||
<UploadButton
|
||||
multiple
|
||||
label="Upload images"
|
||||
label={folder === "logos" ? "Upload logos" : "Upload images"}
|
||||
folder={folder || undefined}
|
||||
onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-muted">{UPLOAD_HELP}</p>
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
</h1>
|
||||
|
||||
<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
|
||||
travels within its parent, so its parent has to be tall. */}
|
||||
|
|
@ -551,3 +575,74 @@ function ImportedNote() {
|
|||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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(', ')
|
||||
|
|
|
|||
|
|
@ -51,6 +51,26 @@ 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 }) {
|
||||
if (!children) return null;
|
||||
return (
|
||||
|
|
@ -356,6 +376,7 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
|
|||
className="text-base font-semibold text-body"
|
||||
>
|
||||
{request ? "Your request" : "Tell us more"}
|
||||
<RequiredTag />
|
||||
</label>
|
||||
<p className="mt-1 text-sm" style={{ color: MUTED }}>
|
||||
{request
|
||||
|
|
@ -381,6 +402,7 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
|
|||
/>
|
||||
<div className="mt-2 flex items-start justify-between gap-4">
|
||||
<FieldError id="feedback-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 }}
|
||||
|
|
@ -482,8 +504,8 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
|
|||
{!ready && !sending && (
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
{request
|
||||
? "Write at least a sentence and give an email address to send."
|
||||
: "Choose a type and write at least a sentence to send."}
|
||||
? `Write at least ${MIN_MESSAGE} characters and give an email address to send.`
|
||||
: `Choose a type and write at least ${MIN_MESSAGE} characters to send.`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
@ -18,7 +22,7 @@ import { ApiError, upload } from "../../lib/api.ts";
|
|||
import { accentText, BRAND } from "../../lib/color.ts";
|
||||
import { REQUEST_FILES } from "../../lib/site.ts";
|
||||
import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts";
|
||||
import { FieldError, OptionalTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
|
||||
import { FieldError, MinimumNote, OptionalTag, RequiredTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
const MAX_CHARS = 5000;
|
||||
|
|
@ -48,6 +52,8 @@ export default function RequestForm() {
|
|||
const [files, setFiles] = useState<File[]>([]);
|
||||
const [name, setName] = 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 [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");
|
||||
|
|
@ -190,6 +206,7 @@ export default function RequestForm() {
|
|||
<div className="mt-8">
|
||||
<label htmlFor="request-subject" className="text-base font-semibold text-body">
|
||||
{action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject}
|
||||
<RequiredTag />
|
||||
</label>
|
||||
<input
|
||||
id="request-subject"
|
||||
|
|
@ -204,9 +221,49 @@ export default function RequestForm() {
|
|||
<FieldError id="request-subject-error">{fieldErrors.subject}</FieldError>
|
||||
</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">
|
||||
<label htmlFor="request-message" className="text-base font-semibold text-body">
|
||||
{action === "update" ? "What should change?" : "Tell us about it"}
|
||||
<RequiredTag />
|
||||
</label>
|
||||
<textarea
|
||||
id="request-message"
|
||||
|
|
@ -225,6 +282,7 @@ export default function RequestForm() {
|
|||
/>
|
||||
<div className="mt-2 flex items-start justify-between gap-4">
|
||||
<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 }}>
|
||||
{message.length} / {MAX_CHARS}
|
||||
</span>
|
||||
|
|
@ -327,7 +385,7 @@ export default function RequestForm() {
|
|||
</button>
|
||||
{!ready && !sending && (
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
Choose what it's about, give it a name, write at least a sentence and give an email address to send.
|
||||
Choose what it's about, give it a name, write at least {MIN_MESSAGE} characters and give an email address to send.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue