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

@ -79,7 +79,9 @@ function LinkCard({ item }: { item: ContentBlockItem }) {
const where = isExternalUrl(url)
? (() => {
try {
return new URL(url).hostname.replace(/^www\./, '')
const host = new URL(url).hostname.replace(/^www\./, '')
// A file from Tools → Media → Files (routes/files.js).
return /^(drive|docs)\.google\.com$/.test(host) ? 'Google Drive' : host
} catch {
return url
}

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)} />}
</>
);
}

View file

@ -56,6 +56,12 @@
(LinkPreviewInput in MediaLibrary.tsx) that fills the row's empty
title, blurb and image through `onPatch`.
`files: true` on a link field adds "Choose a file" (FilePicker in
DriveFiles.tsx): the field takes the file's Drive link, and with
`previewFills` (a link card) the row's empty title and picture take
the file's name and first-page preview. `filesWhen` limits it to
rows that match, as `when` does for the field.
`widget: "testNotice"` is a text box of email addresses with a
"Send a test notice" button (TestNoticeInput below), for Site
settings → Notices.
@ -85,6 +91,7 @@ import { useRef, useState } from "react";
import { ApiError, post } from "../../lib/api.ts";
import ContentBlocks from "../ContentBlocks.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
import { ChooseFileButton } from "./DriveFiles.tsx";
/* Live previews a collection can name with `preview`. Each gets the
row as the form holds it, which is the API's shape. */
@ -235,6 +242,17 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
!list.some(([optionId]) => String(optionId) === String(value));
}
// A file from the Drive library into this link field (`files`).
const pickFile = (file) => {
const fills = field.previewFills;
const patch = { [field.path]: file.url };
if (fills && !row?.[fills.title]) patch[fills.title] = file.title;
if (fills && !row?.[fills.image] && file.preview) patch[fills.image] = file.preview;
if (onPatch && !field.path.includes(".")) onPatch(patch);
else onChange(file.url);
};
const showFiles = field.files && !locked && (!field.filesWhen || fieldShown({ when: field.filesWhen }, row));
const common = {
id,
className: `${input} ${error ? inputError : ""}`,
@ -371,6 +389,11 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
className={locked ? inputLocked : common.className}
/>
)}
{showFiles && (
<div className="mt-2">
<ChooseFileButton value={value} onPick={pickFile} />
</div>
)}
</div>
{error ? (

View file

@ -362,6 +362,8 @@ export const blocksChild = {
path: "href",
label: "Link",
full: true,
files: true,
filesWhen: { path: "type", value: ["paragraph", "button", "image"] },
when: { path: "type", value: ["paragraph", "button", "image", "video"] },
help: (row) => HREF_HELP[row?.type],
},
@ -405,8 +407,9 @@ export const blocksChild = {
label: "Link",
widget: "linkPreview",
previewFills: { title: "text", blurb: "detail", image: "media" },
files: true,
full: true,
help: "A page on this site (eg. /retreats) or anywhere else. Fetch preview fills the title, description and picture.",
help: "A page on this site (eg. /retreats), anywhere else, or a file (Choose a file). Fetch preview fills the title, description and picture from a page; a file fills its name and first-page picture.",
when: CARD_ITEM,
},
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title. Cards: the card's title" },
@ -427,7 +430,7 @@ export const blocksChild = {
},
{ path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text", when: NOT_CARD_ITEM },
{ path: "detail", label: "Description", widget: "textarea", full: true, when: CARD_ITEM },
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", when: NOT_CARD_ITEM },
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", files: true, when: NOT_CARD_ITEM },
{
path: "media",
label: "Picture",

View file

@ -1,10 +1,13 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN: MEDIA
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
page is for housekeeping rather than the way images get in.
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
@ -17,6 +20,12 @@ 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,
@ -27,7 +36,18 @@ import {
type Use = { table: string; count: number };
function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () => void }) {
/* `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);
@ -36,7 +56,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
setBusy(true);
setError(null);
try {
const data = await get(`/admin/media/${item.id}/uses`, { ttl: 0 });
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.");
@ -49,7 +69,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
setBusy(true);
setError(null);
try {
await del(`/admin/media/${item.id}`);
await del(`${base}/${item.id}`);
onDeleted();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't delete that.");
@ -78,8 +98,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
{uses.length > 0 ? (
<p>
Still used by{" "}
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. Those
will show no image.
{uses.map((use) => `${use.count} in ${use.table.replace(/_/g, " ")}`).join(", ")}. {broken}
</p>
) : (
<p>Nothing uses this file.</p>
@ -102,7 +121,7 @@ function DeleteControl({ item, onDeleted }: { item: MediaItem; onDeleted: () =>
);
}
function CopyPath({ url }: { url: string }) {
function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
<button
@ -115,13 +134,79 @@ function CopyPath({ url }: { url: string }) {
}}
className="text-xs text-link hover:underline"
>
{copied ? "Copied" : "Copy path"}
{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);
@ -130,10 +215,34 @@ export default function AdminMedia() {
<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">
Uploaded images. Image fields in every editor pick from here.
{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">
@ -188,6 +297,8 @@ export default function AdminMedia() {
/>
)}
</div>
</>
)}
</div>
);
}