Request files go in Requests/<type> (Chapters, Events...). Media → Files shows a tab per folder under Media, up to three deep, and can make, rename (files follow) and delete empty folders, move a file with its Folder dropdown, and upload into the folder showing; Choose a file has the same tabs. A folder made, or a file moved, in Drive by hand is followed on the next look (migration 050 records each file's folder). Deletes now move to Drive's trash: a shared drive's Content manager, the service account's role, can't delete outright, so request and file deletes would have failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358 lines
13 KiB
TypeScript
358 lines
13 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)
|
|
DriveFolderTabs a tab per folder under Media in Drive; both
|
|
the picker and the Files tab filter by it, and
|
|
upload into the one showing
|
|
|
|
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;
|
|
/** Its folder under Media: "" for Media itself. */
|
|
folder: string;
|
|
uploaded_by: string | null;
|
|
created_at: string;
|
|
};
|
|
|
|
/* Which tab: every file, Media's own (not in a folder), or a folder's. */
|
|
export const ALL_FOLDERS = "*";
|
|
|
|
export function inFolder(files: DriveFile[], tab: string) {
|
|
return tab === ALL_FOLDERS ? files : files.filter((f) => f.folder === tab);
|
|
}
|
|
|
|
export function DriveFolderTabs({ folders, value, onChange }: { folders: string[]; value: string; onChange: (tab: string) => void }) {
|
|
const tabs: [string, string][] = [[ALL_FOLDERS, "All"], ["", "Not in a folder"], ...folders.map((f): [string, string] => [f, f])];
|
|
return (
|
|
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
|
|
{tabs.map(([tab, label]) => (
|
|
<button
|
|
key={tab}
|
|
type="button"
|
|
role="tab"
|
|
aria-selected={value === tab}
|
|
onClick={() => onChange(tab)}
|
|
className={
|
|
"rounded-full px-3 py-1 text-sm transition-colors " +
|
|
(value === tab ? "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";
|
|
|
|
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 [folders, setFolders] = useState<string[]>([]);
|
|
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);
|
|
setFolders(data.folders ?? []);
|
|
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, folders, ready, refused, error, reload, setItems };
|
|
}
|
|
|
|
/* ── Upload ──────────────────────────────────────────────────── */
|
|
|
|
export function FileUploadButton({
|
|
onUploaded,
|
|
label = "Upload files",
|
|
folder = "",
|
|
}: {
|
|
onUploaded: (file: DriveFile) => void;
|
|
label?: string;
|
|
/** Under Media; "" for Media itself. */
|
|
folder?: 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);
|
|
form.append("folder", folder);
|
|
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, folders, ready, refused, error, setItems } = useDriveFiles(query);
|
|
const [tab, setTab] = useState(ALL_FOLDERS);
|
|
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>
|
|
|
|
{folders.length > 0 && (
|
|
<div className="border-b border-brand/10 px-5 py-3">
|
|
<DriveFolderTabs folders={folders} value={tab} onChange={setTab} />
|
|
</div>
|
|
)}
|
|
|
|
{roleCanWrite(user) && ready && (
|
|
<div className="border-b border-brand/10 px-5 py-3">
|
|
<FileUploadButton
|
|
label={tab && tab !== ALL_FOLDERS ? `Upload into ${tab}` : "Upload new"}
|
|
folder={tab === ALL_FOLDERS ? "" : tab}
|
|
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={inFolder(items, tab)} 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)} />}
|
|
</>
|
|
);
|
|
}
|