/* ═══════════════════════════════════════════════════════════════ ADMIN: MEDIA Two tabs. Images: the uploaded-image library: search it, add to it, copy a file's path, delete what nothing needs. Image fields in the editors upload and pick from the same library (MediaLibrary.tsx), so this 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. 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 name the file, since nothing stops one being removed from under a page (an image field stores the path, not a foreign key). ═══════════════════════════════════════════════════════════════ */ import { useEffect, useState, type FormEvent } from "react"; import { Link } from "react-router-dom"; 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, NameBox, UPLOAD_HELP, UploadButton, useMediaLibrary, type MediaItem, } from "../../components/admin/MediaLibrary.tsx"; type Use = { table: string; count: number }; /* `base` is where the item lives: /admin/media or /admin/files. */ function DeleteControl({ item, base = "/admin/media", broken = "Those will show no image.", onDeleted, }: { item: { id: number }; base?: string; broken?: string; onDeleted: () => void; }) { const [uses, setUses] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function ask() { setBusy(true); setError(null); try { const data = await get(`${base}/${item.id}/uses`, { ttl: 0 }); setUses(data.uses); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't check where it's used."); } finally { setBusy(false); } } async function remove() { setBusy(true); setError(null); try { await del(`${base}/${item.id}`); onDeleted(); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't delete that."); setBusy(false); } } if (uses === null) { return ( <> {error &&

{error}

} ); } return (
{uses.length > 0 ? (

Still used by{" "} {uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}

) : (

Nothing uses this file.

)}
{error &&

{error}

}
); } /* Rename: the library's name and the file's own. Opening it asks what uses the file first, since the server repoints those records at the new address and anything outside the site (a sent newsletter, a shared link) keeps the old one, which stops working. */ function RenameControl({ item, onRenamed }: { item: MediaItem; onRenamed: (item: MediaItem) => void }) { const [name, setName] = useState(null); const [uses, setUses] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function open() { setName(item.original_name); setError(null); setUses(null); try { setUses((await get(`/admin/media/${item.id}/uses`, { ttl: 0 })).uses); } catch { setUses([]); } } async function save(e: FormEvent) { e.preventDefault(); if (!name?.trim()) return; setBusy(true); setError(null); try { const { media } = await patch(`/admin/media/${item.id}`, { name }); onRenamed(media); setName(null); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't rename that."); } finally { setBusy(false); } } if (name === null) { return ( ); } const count = uses?.reduce((sum, use) => sum + use.count, 0) ?? 0; return (

{uses === null ? "Checking what uses it…" : `Also renames the file${count > 0 ? `, and updates the ${count} record${count === 1 ? "" : "s"} using it` : ""}. Links to the old address outside the site (eg. a sent newsletter) will stop working.`}

{error &&

{error}

} ); } function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) { const [copied, setCopied] = useState(false); return ( ); } /* The folder showing: make one inside it, rename it, or delete it when it's empty. Drive is the source; the list reloads after. */ function FolderControls({ tab, onChanged }: { tab: string; onChanged: (tab: string) => void }) { const { user } = useAuth(); const [mode, setMode] = useState<"new" | "rename" | null>(null); const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const inside = tab === ALL_FOLDERS ? "" : tab; const button = "btn border border-brand px-3 py-1 text-xs text-link transition-colors hover:bg-tint disabled:opacity-50"; async function run(work: () => Promise) { setBusy(true); setError(null); try { onChanged(await work()); setMode(null); setName(""); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't reach the server."); } finally { setBusy(false); } } const submit = () => run(async () => mode === "new" ? (await post("/admin/files/folders", { path: inside ? `${inside}/${name}` : name })).path : (await patch("/admin/files/folders", { path: inside, name })).path, ); const remove = () => run(async () => { await del(`/admin/files/folders?path=${encodeURIComponent(inside)}`); return inside.split("/").slice(0, -1).join("/") || ALL_FOLDERS; }); if (!roleCanWrite(user)) return null; return (
{mode ? ( <> setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && name.trim()) submit(); if (e.key === "Escape") setMode(null); }} placeholder={mode === "new" ? "New folder's name" : "New name"} className="border border-muted/25 bg-surface px-3 py-1 text-sm text-body outline-none focus:border-brand" /> ) : ( <> {inside && ( )} {inside && canDelete(user) && ( )} )} {error && {error}}
); } /* A file's folder, changed in place. */ function MoveControl({ file, folders, onMoved }: { file: DriveFile; folders: string[]; onMoved: (file: DriveFile) => void }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); return (
{error &&

{error}

}
); } function FilesTab() { const { user } = useAuth(); const [query, setQuery] = useState(""); const { items, folders, ready, refused, error, reload, setItems } = useDriveFiles(query); const [tab, setTab] = useState(ALL_FOLDERS); const replace = (file: DriveFile) => setItems((current) => (current ?? []).map((f) => (f.id === file.id ? file : f))); return ( <>
{roleCanWrite(user) && ready && (
setItems((current) => [file, ...(current ?? [])])} />

{FILE_HELP}

)} setQuery(e.target.value)} placeholder="Search by file name" aria-label="Search by file name" className="ml-auto w-64 border border-muted/25 px-3 py-2 text-sm outline-none focus:border-brand" />
{!ready && (

Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.

)} {ready && (
{ setTab(next); reload(); }} />
)}
{error ? (

{error}

) : items === null ? (

Loading…

) : ( (
{roleCanWrite(user) && } Open in Drive {canDelete(user) && (
setItems((current) => (current ?? []).filter((f) => f.id !== file.id))} />
)}
)} /> )}
); } /* Request form files, by their type's folder in Drive (Requests/…). */ function RequestFilesTab() { const { user } = useAuth(); const [data, setData] = useState(null); const [error, setError] = useState(null); const [folder, setFolder] = useState("*"); const [confirming, setConfirming] = useState(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

{error}

; if (!data) return

Loading…

; const counts = new Map(); 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 (
{[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => ( ))}
{!data.checked && (

Drive couldn't be asked just now, so missing files aren't marked.

)} {error &&

{error}

} {shown.length === 0 ? (

No request files here.

) : (
    {shown.map((file) => (
  • {file.missing ? ( {file.name} ) : ( {file.name} )} {formatBytes(file.size)} {file.missing && ( Missing from Drive )} Request #{file.feedback_id} {file.subject ? `: ${file.subject}` : ""} ({file.status}) {canDelete(user) && ( {confirming === file.id ? ( <> {" "} ) : ( )} )}
  • ))}
)}
); } const TABS = [ ["images", "Images"], ["files", "Files"], ["requests", "Requests"], ] as const; export default function AdminMedia() { const { user } = useAuth(); 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, undefined, folder); return (

Media

{tab === "images" ? "Uploaded images. Image fields in every editor pick from here." : tab === "files" ? "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file." : "Files sent with the Request form, in the shared Google Drive's Requests folder. Removing one takes it off its request too."}

{tab === "requests" ? ( ) : tab === "files" ? ( ) : ( <>
{roleCanWrite(user) && (
setItems((current) => [item, ...(current ?? [])])} />

{UPLOAD_HELP}

)} setQuery(e.target.value)} placeholder="Search by file name" aria-label="Search by file name" className="ml-auto w-64 border border-muted/25 px-3 py-2 text-sm outline-none focus:border-brand" />
{error ? (

{error}

) : items === null ? (

Loading…

) : ( (
Open {roleCanWrite(user) && ( setItems((current) => (current ?? []).map((m) => (m.id === renamed.id ? renamed : m))) } /> )} {canDelete(user) && (
setItems((current) => (current ?? []).filter((m) => m.id !== item.id)) } />
)}
)} /> )}
)}
); }