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>
This commit is contained in:
Zaldimmar 2026-09-29 18:37:15 -05:00
parent 36c9226bd9
commit 934598f954
13 changed files with 772 additions and 33 deletions

View file

@ -0,0 +1,286 @@
/* ═══════════════════════════════════════════════════════════════
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.
═══════════════════════════════════════════════════════════════ */
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";
function TypeIcon({ mime }: { mime: string }) {
const Icon = mime === "application/pdf"
? FilePdf
: mime.includes("wordprocessing")
? FileDoc
: mime.includes("spreadsheet")
? FileXls
: mime.includes("presentation")
? FilePpt
: mime.startsWith("audio/")
? FileAudio
: mime === "application/zip"
? FileZip
: 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);
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);
})
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
}, [query]);
useEffect(reload, [reload]);
return { items, ready, 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, 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="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>}
{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>
);
}
/* "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)} />}
</>
);
}