NGU-Web/src/components/admin/DriveFiles.tsx
Zaldimmar 4b249c9e52 Let a content request carry the record's details, and open its editor
The Request form asks each type for its main details (a chapter's
city, meeting time, website and email; an event's dates, venue and
registration link...), stored as one JSON column (migration 049). The
server only checks the shape; the fields are src/data/requestTypes.ts.

Forms → Content requests shows them, and for a new record opens the
New editor filled in (URL ID from the name, links and a description
paragraph added); for an update, picks the record (closest name
first) and opens it with each requested value beside the current one
to use or skip. Nothing is saved until Save.

Also centres the image and file pickers, which Tailwind's reset had
pinned to the top left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:21:33 -05:00

303 lines
11 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
DRIVE FILES
Files for the site to link to (server/src/routes/files.js), kept in
the shared Google Drive and shared as "anyone with the link can
view". The admin side, in one file:
FileUploadButton upload one or more files
FileList the list both the picker and Tools → Media →
Files draw, each with its first-page preview
or an icon for its type
FilePicker the dialog behind a link field's "Choose a
file" (a field with `files: true`, fields.tsx)
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
folder by hand are listed too (the server picks them up).
═══════════════════════════════════════════════════════════════ */
import {
File as FileIcon,
FileAudio,
FileDoc,
FilePdf,
FilePpt,
FileXls,
FileZip,
X,
} from "@phosphor-icons/react";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { ApiError, get, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
import { formatBytes } from "./MediaLibrary.tsx";
export type DriveFile = {
id: number;
name: string;
title: string;
mime: string;
bytes: number;
url: string;
preview: string | null;
uploaded_by: string | null;
created_at: string;
};
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";
export const FILE_HELP =
"PDF, Word, Excel, PowerPoint (.docx, .xlsx, .pptx), MP3, M4A or zip, up to 50 MB. Stored in the shared Google Drive and viewable by anyone with the link.";
const ACCEPT = ".pdf,.docx,.xlsx,.pptx,.mp3,.m4a,.zip";
/* An icon per kind of file; Google's own Docs, Sheets and Slides
(application/vnd.google-apps.*) count as their Office kin. */
const TYPE_ICONS: [RegExp, typeof FileIcon][] = [
[/pdf$/, FilePdf],
[/wordprocessing|google-apps\.document$/, FileDoc],
[/spreadsheet/, FileXls],
[/presentation/, FilePpt],
[/^audio\//, FileAudio],
[/zip$/, FileZip],
];
function TypeIcon({ mime }: { mime: string }) {
const Icon = TYPE_ICONS.find(([test]) => test.test(mime))?.[1] ?? FileIcon;
return <Icon aria-hidden="true" weight="bold" className="h-8 w-8 text-link" />;
}
/* ── Data ────────────────────────────────────────────────────── */
export function useDriveFiles(query: string) {
const [items, setItems] = useState<DriveFile[] | null>(null);
const [ready, setReady] = useState(true);
// Files in the Drive folder that Drive wouldn't share publicly.
const [refused, setRefused] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
const q = query.trim();
setError(null);
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
.then((data) => {
setItems(data.files);
setReady(data.ready);
setRefused(data.refused ?? []);
})
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
}, [query]);
useEffect(reload, [reload]);
return { items, ready, refused, error, reload, setItems };
}
/* ── Upload ──────────────────────────────────────────────────── */
export function FileUploadButton({ onUploaded, label = "Upload files" }: { onUploaded: (file: DriveFile) => void; label?: string }) {
const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function send(list: FileList | null) {
if (!list?.length) return;
setError(null);
try {
// One at a time, so a failure names its file.
for (const file of Array.from(list)) {
setBusy(file.name);
const form = new FormData();
form.append("file", file);
try {
onUploaded((await upload("/admin/files", form)).file);
} catch (err) {
const why = err instanceof ApiError ? err.message : "Upload failed.";
setError(list.length > 1 ? `${file.name}: ${why}` : why);
break;
}
}
} finally {
setBusy(null);
if (inputRef.current) inputRef.current.value = "";
}
}
return (
<div>
<button type="button" className={button} disabled={busy !== null} onClick={() => inputRef.current?.click()}>
{busy ? `Uploading ${busy}…` : label}
</button>
<input ref={inputRef} type="file" accept={ACCEPT} multiple className="hidden" onChange={(e) => send(e.target.files)} />
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
</div>
);
}
/* ── List ────────────────────────────────────────────────────── */
export function FileList({
items,
selected,
onPick,
renderActions,
}: {
items: DriveFile[];
selected?: string | null;
onPick?: (file: DriveFile) => void;
renderActions?: (file: DriveFile) => ReactNode;
}) {
if (items.length === 0) return <p className="text-sm text-muted">No files yet.</p>;
return (
<ul className="grid gap-3 sm:grid-cols-2">
{items.map((file) => {
const isSelected = selected === file.url;
const body = (
<span className="flex items-center gap-3">
<span className="flex h-16 w-14 shrink-0 items-center justify-center overflow-hidden rounded-md border border-muted/20 bg-tint">
{file.preview ? (
<img src={file.preview} alt="" loading="lazy" className="h-full w-full object-cover object-top" />
) : (
<TypeIcon mime={file.mime} />
)}
</span>
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-body" title={file.name}>
{file.name}
</span>
<span className="block text-xs text-muted/80">{formatBytes(file.bytes)}</span>
</span>
</span>
);
return (
<li
key={file.id}
className={`rounded-xl border bg-surface p-2 ${isSelected ? "border-brand ring-2 ring-brand/30" : "border-muted/20"}`}
>
{onPick ? (
<button type="button" onClick={() => onPick(file)} className="block w-full text-left" aria-pressed={isSelected}>
{body}
</button>
) : (
body
)}
{renderActions && <div className="mt-2">{renderActions(file)}</div>}
</li>
);
})}
</ul>
);
}
/* ── Picker dialog ───────────────────────────────────────────── */
export function FilePicker({
selected,
onPick,
onClose,
}: {
selected?: string | null;
onPick: (file: DriveFile) => void;
onClose: () => void;
}) {
const { user } = useAuth();
const [query, setQuery] = useState("");
const { items, ready, refused, error, setItems } = useDriveFiles(query);
const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => {
dialogRef.current?.showModal();
}, []);
const pick = (file: DriveFile) => {
onPick(file);
dialogRef.current?.close();
};
return (
<dialog
ref={dialogRef}
onClose={onClose}
onClick={(e) => {
if (e.target === dialogRef.current) dialogRef.current?.close();
}}
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">
<h2 className="text-lg font-semibold text-link">Choose a file</h2>
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search by file name"
className="ml-auto w-56 rounded-lg border border-muted/25 px-3 py-1.5 text-sm outline-none focus:border-brand"
/>
<button
type="button"
onClick={() => dialogRef.current?.close()}
aria-label="Close"
className="flex h-8 w-8 items-center justify-center rounded-full text-muted hover:bg-tint"
>
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
</button>
</div>
{roleCanWrite(user) && ready && (
<div className="border-b border-brand/10 px-5 py-3">
<FileUploadButton
label="Upload new"
onUploaded={(file) => {
setItems((current) => [file, ...(current ?? [])]);
pick(file);
}}
/>
<p className="mt-1 text-xs text-muted">{FILE_HELP}</p>
</div>
)}
<div className="overflow-y-auto px-5 py-4">
{!ready && <p className="mb-3 text-sm text-danger">Google Drive isn't set up on the server, so nothing can be uploaded.</p>}
<RefusedNote names={refused} />
{error ? (
<p className="text-sm text-danger">{error}</p>
) : items === null ? (
<p className="text-sm text-muted">Loading…</p>
) : (
<FileList items={items} selected={selected} onPick={pick} />
)}
</div>
</div>
</dialog>
);
}
/* Files someone put in the Drive folder that Drive wouldn't share
with anyone who has the link, so they aren't listed. */
export function RefusedNote({ names }: { names: string[] }) {
if (names.length === 0) return null;
return (
<p className="mb-3 text-sm text-danger">
In the Drive folder but not listed, because Drive wouldn't share {names.length === 1 ? "it" : "them"} with anyone
who has the link: {names.join(", ")}. Check the sharing settings (docs/google-drive-and-mail.md); they're tried
again every ten minutes.
</p>
);
}
/* "Choose a file" under a link field. */
export function ChooseFileButton({ value, onPick }: { value?: string | null; onPick: (file: DriveFile) => void }) {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" className={button} onClick={() => setOpen(true)}>
Choose a file
</button>
{open && <FilePicker selected={value} onPick={onPick} onClose={() => setOpen(false)} />}
</>
);
}