/* ═══════════════════════════════════════════════════════════════
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 (
{tabs.map(([tab, label]) => (
))}
);
}
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 ;
}
/* ── Data ────────────────────────────────────────────────────── */
export function useDriveFiles(query: string) {
const [items, setItems] = useState(null);
const [folders, setFolders] = useState([]);
const [ready, setReady] = useState(true);
// Files in the Drive folder that Drive wouldn't share publicly.
const [refused, setRefused] = useState([]);
const [error, setError] = useState(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(null);
const [busy, setBusy] = useState(null);
const [error, setError] = useState(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 (
);
}
/* ── 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(null);
useEffect(() => {
dialogRef.current?.showModal();
}, []);
const pick = (file: DriveFile) => {
onPick(file);
dialogRef.current?.close();
};
return (
);
}
/* 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 (
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.
);
}
/* "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 (
<>
{open && setOpen(false)} />}
>
);
}