NGU-Web/src/pages/admin/AdminMedia.tsx
Zaldimmar 934598f954 Add a file library in Google Drive for pages to link to
Tools → Media → Files uploads PDF, Office (.docx, .xlsx, .pptx), MP3,
M4A and zip files, up to 50 MB, to the shared drive's Blog folder and
shares each as anyone with the link can view (migration 048). A file's
name and contents must agree.

Content block links get "Choose a file" (paragraph, button and image
links, list and link items, link cards). A link card also takes the
file's name and Drive's picture of its first page, fetched after
upload and saved into the image library; cards to Drive say "Google
Drive". Deleting a file says first what still links to it.

Setup and the nginx block: docs/google-drive-and-mail.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:37:15 -05:00

304 lines
9.5 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
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 } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx";
import { canDelete, canWrite as roleCanWrite } from "../../lib/roles.ts";
import {
FILE_HELP,
FileList,
FileUploadButton,
useDriveFiles,
} from "../../components/admin/DriveFiles.tsx";
import {
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<Use[] | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 (
<>
<button
type="button"
onClick={ask}
disabled={busy}
className="text-xs text-muted hover:text-danger"
>
Delete
</button>
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
</>
);
}
return (
<div className="rounded-lg bg-danger-tint p-2 text-xs text-body">
{uses.length > 0 ? (
<p>
Still used by{" "}
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}
</p>
) : (
<p>Nothing uses this file.</p>
)}
<div className="mt-2 flex gap-3">
<button
type="button"
onClick={remove}
disabled={busy}
className="font-medium text-danger hover:underline"
>
{busy ? "Deleting…" : "Delete for good"}
</button>
<button type="button" onClick={() => setUses(null)} className="text-muted hover:underline">
Cancel
</button>
</div>
{error && <p className="mt-1 text-danger">{error}</p>}
</div>
);
}
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
<button
type="button"
onClick={() => {
navigator.clipboard?.writeText(url).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
}}
className="text-xs text-link hover:underline"
>
{copied ? "Copied" : label}
</button>
);
}
function FilesTab() {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, ready, error, setItems } = useDriveFiles(query);
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 ?? [])])} />
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
</div>
)}
<input
type="search"
value={query}
onChange={(e) => 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"
/>
</div>
{!ready && (
<p className="mt-4 text-sm text-danger">
Google Drive isn't set up on the server (docs/google-drive-and-mail.md), so files can't be uploaded.
</p>
)}
<div className="mt-6">
{error ? (
<p className="text-sm text-danger">{error}</p>
) : items === null ? (
<p className="text-sm text-muted">Loading…</p>
) : (
<FileList
items={items}
renderActions={(file) => (
<div className="flex flex-wrap items-start gap-x-3 gap-y-1">
<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
</a>
{canDelete(user) && (
<div className="w-full">
<DeleteControl
item={file}
base="/admin/files"
broken="Those links will stop working."
onDeleted={() => setItems((current) => (current ?? []).filter((f) => f.id !== file.id))}
/>
</div>
)}
</div>
)}
/>
)}
</div>
</>
);
}
const TABS = [
["images", "Images"],
["files", "Files"],
] as const;
export default function AdminMedia() {
const { user } = useAuth();
const [tab, setTab] = useState<"images" | "files">("images");
const [query, setQuery] = useState("");
const { items, error, setItems } = useMediaLibrary(query);
return (
<div>
<div className="flex flex-wrap items-baseline gap-3">
<h1 className="text-2xl font-bold text-link">Media</h1>
<p className="text-sm text-muted">
{tab === "images"
? "Uploaded images. Image fields in every editor pick from here."
: "Files in the shared Google Drive, for pages to link to. Link fields pick from here with Choose a file."}
</p>
</div>
<nav aria-label="Media" className="mt-4 flex gap-1 border-b border-brand/15">
{TABS.map(([id, label]) => (
<button
key={id}
type="button"
aria-current={tab === id ? "page" : undefined}
onClick={() => setTab(id)}
className={
"-mb-px border-b-2 px-4 py-2 text-sm font-semibold transition-colors " +
(tab === id ? "border-link text-link" : "border-transparent text-muted hover:text-link")
}
>
{label}
</button>
))}
</nav>
{tab === "files" ? (
<FilesTab />
) : (
<>
<div className="mt-6 flex flex-wrap items-start gap-6">
{roleCanWrite(user) && (
<div className="max-w-md">
<UploadButton
multiple
label="Upload images"
onUploaded={(item) => setItems((current) => [item, ...(current ?? [])])}
/>
<p className="mt-1 text-xs text-muted">{UPLOAD_HELP}</p>
</div>
)}
<input
type="search"
value={query}
onChange={(e) => 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"
/>
</div>
<div className="mt-6">
{error ? (
<p className="text-sm text-danger">{error}</p>
) : items === null ? (
<p className="text-sm text-muted">Loading…</p>
) : (
<MediaGrid
items={items}
renderActions={(item) => (
<div className="flex flex-wrap items-start gap-x-3 gap-y-1">
<CopyPath url={item.url} />
<a
href={item.url}
target="_blank"
rel="noreferrer"
className="text-xs text-link hover:underline"
>
Open
</a>
{canDelete(user) && (
<div className="w-full">
<DeleteControl
item={item}
onDeleted={() =>
setItems((current) => (current ?? []).filter((m) => m.id !== item.id))
}
/>
</div>
)}
</div>
)}
/>
)}
</div>
</>
)}
</div>
);
}