/* ═══════════════════════════════════════════════════════════════ 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. 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 { useState } from "react"; import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts"; import { ALL_FOLDERS, DriveFolderTabs, FILE_HELP, FileList, FileUploadButton, RefusedNote, inFolder, useDriveFiles, type DriveFile, } from "../../components/admin/DriveFiles.tsx"; import { FolderTabs, MediaGrid, UPLOAD_HELP, UploadButton, 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}

}
); } 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 = "rounded-full border border-brand px-3 py-1 text-xs font-medium text-link transition-colors hover:bg-tint disabled:opacity-50"; async function run(work: () => Promise) { setBusy(true); setError(null); try { onChanged(await work()); setMode(null); setName(""); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't reach the server."); } finally { setBusy(false); } } const submit = () => run(async () => mode === "new" ? (await post("/admin/files/folders", { path: inside ? `${inside}/${name}` : name })).path : (await patch("/admin/files/folders", { path: inside, name })).path, ); const remove = () => run(async () => { await del(`/admin/files/folders?path=${encodeURIComponent(inside)}`); return inside.split("/").slice(0, -1).join("/") || ALL_FOLDERS; }); if (!roleCanWrite(user)) return null; return (
{mode ? ( <> setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && name.trim()) submit(); if (e.key === "Escape") setMode(null); }} placeholder={mode === "new" ? "New folder's name" : "New name"} className="rounded-lg border border-muted/25 bg-surface px-3 py-1 text-sm text-body outline-none focus:border-brand" /> ) : ( <> {inside && ( )} {inside && canDelete(user) && ( )} )} {error && {error}}
); } /* A file's folder, changed in place. */ function MoveControl({ file, folders, onMoved }: { file: DriveFile; folders: string[]; onMoved: (file: DriveFile) => void }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); return (
{error &&

{error}

}
); } function FilesTab() { const { user } = useAuth(); const [query, setQuery] = useState(""); const { items, 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" className="ml-auto w-64 rounded-lg 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))} />
)}
)} /> )}
); } const TABS = [ ["images", "Images"], ["files", "Files"], ] as const; 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, undefined, folder); return (

Media

{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" ? ( ) : ( <>
{roleCanWrite(user) && (
setItems((current) => [item, ...(current ?? [])])} />

{UPLOAD_HELP}

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

{error}

) : items === null ? (

Loading…

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