Request details, Drive folders, image folders, clip tool to Drive (v1.9.12 to v1.9.14-content-display) #16

Merged
ngu-git-admin merged 13 commits from content-display into main 2026-09-30 19:05:26 +01:00
14 changed files with 283 additions and 51 deletions
Showing only changes of commit 9854da965e - Show all commits

View file

@ -62,7 +62,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
- `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.

View file

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

View file

@ -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`))

View file

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

View file

@ -37,6 +37,7 @@ import { bodyLimit } from "hono/body-limit";
import { requireAuth, requireRole } from "../auth.js";
import { driveDelete, driveList, driveReady, driveShareWithAnyone, driveThumbnail, driveUpload } from "../googleService.js";
import { addToLibrary, recordsNaming } from "./media.js";
import { publicPath } from "../media.js";
import { NO_STORE } from "../shape.js";
const files = new Hono();
@ -100,8 +101,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) {

View file

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

View file

@ -17,6 +17,11 @@
description and preview image (the image lands in
the library) and fills the row's empty fields.
Images live in folders by what they're for (FOLDERS in
server/src/media.js): Logos, Images, and Previews the site saved
itself. A field's `folder` says where its uploads go (logo fields:
"logos"; default "images"), and its picker opens on that tab.
An image field stores a path, not a media id: '/uploads/<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
@ -47,8 +52,42 @@ export type MediaItem = {
processed: boolean;
uploaded_by: string | null;
created_at: string;
/** logos, images or thumbnails; null for clips and older files in the root. */
folder: string | null;
};
/* The folder tabs, as [folder, label]; "" is every image. */
export const IMAGE_FOLDERS = [
["", "All"],
["logos", "Logos"],
["images", "Images"],
["thumbnails", "Previews"],
] as const;
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
/* A tab strip over the folders; `value` is the one showing. */
export function FolderTabs({ value, onChange }: { value: string; onChange: (folder: ImageFolder) => void }) {
return (
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
{IMAGE_FOLDERS.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 +116,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 +136,14 @@ export function useMediaLibrary(query: string, type?: "image" | "video" | "audio
const params = new URLSearchParams();
if (q) params.set("q", q);
if (type) params.set("type", type);
if (folder) params.set("folder", folder);
setError(null);
get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 })
.then((data) => setItems(data.media))
.catch((err) =>
setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
);
}, [query, type]);
}, [query, type, folder]);
useEffect(reload, [reload]);
@ -115,10 +156,13 @@ export function UploadButton({
onUploaded,
multiple = false,
label = "Upload",
folder,
}: {
onUploaded: (item: MediaItem) => void;
multiple?: boolean;
label?: string;
/** Where it goes; blank: the server's default, images. */
folder?: string;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const keepId = useId();
@ -135,7 +179,7 @@ export function UploadButton({
// name the file it happened to.
for (const file of Array.from(files)) {
try {
onUploaded(await uploadImage(file, keepOriginal));
onUploaded(await uploadImage(file, keepOriginal, folder));
} catch (err) {
const why = err instanceof ApiError ? err.message : "Upload failed.";
setError(files.length > 1 ? `${file.name}: ${why}` : why);
@ -265,16 +309,20 @@ export function MediaGrid({
export function MediaPicker({
selected,
folder = "images",
onPick,
onClose,
}: {
selected?: string | null;
/** The field's folder: the tab it opens on, where uploads go. */
folder?: string;
onPick: (item: MediaItem) => void;
onClose: () => void;
}) {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query, "image");
const [tab, setTab] = useState<string>(folder);
const { items, error, setItems } = useMediaLibrary(query, "image", tab);
const dialogRef = useRef<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free.
@ -312,10 +360,15 @@ export function MediaPicker({
</button>
</div>
<div className="border-b border-brand/10 px-5 py-3">
<FolderTabs value={tab} onChange={setTab} />
</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);
@ -353,6 +406,7 @@ export function ImageInput({
id,
value,
resolve,
folder,
locked,
className,
onChange,
@ -360,6 +414,8 @@ export function ImageInput({
id: string;
value: string | null | undefined;
resolve?: (file?: string | null) => string | null;
/** The field's `folder` (logos for logo fields); default images. */
folder?: string;
locked: boolean;
className: string;
onChange: (value: string) => void;
@ -399,7 +455,7 @@ export function ImageInput({
/>
{editable && (
<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 +475,7 @@ export function ImageInput({
{picking && (
<MediaPicker
selected={value}
folder={folder}
onPick={(item) => onChange(item.url)}
onClose={() => setPicking(false)}
/>

View file

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

View file

@ -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 },
],
},
{

View file

@ -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",

View file

@ -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 },
],
},
{

View file

@ -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.",

View file

@ -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 },

View file

@ -28,6 +28,7 @@ import {
useDriveFiles,
} from "../../components/admin/DriveFiles.tsx";
import {
FolderTabs,
MediaGrid,
UPLOAD_HELP,
UploadButton,
@ -209,8 +210,10 @@ const TABS = [
export default function AdminMedia() {
const { user } = useAuth();
const [tab, setTab] = useState<"images" | "files">("images");
// The image folder showing; "" is all of them, clips included.
const [folder, setFolder] = useState("");
const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query);
const { items, error, setItems } = useMediaLibrary(query, undefined, folder);
return (
<div>
@ -245,12 +248,17 @@ export default function AdminMedia() {
) : (
<>
<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>