/* ═══════════════════════════════════════════════════════════════ MEDIA LIBRARY Everything the admin does with uploaded images, in one file: ImageInput the `widget: "image"` form field. A preview, the stored value as editable text, and buttons to upload a new file or pick an earlier one. MediaPicker the dialog behind "Choose from library". MediaGrid the thumbnails both the picker and the Media page (pages/admin/AdminMedia.tsx) draw. UploadButton a file input dressed as a button, with the "keep original" choice beside it. LinkPreviewInput the `widget: "linkPreview"` field: a URL box and a "Fetch preview" button that reads the page's title, description and preview image (the image lands in the library) and fills the row's empty fields. Images live in folders by what they're for (FOLDERS in server/src/media.js): Logos, Images, and Previews the site saved itself. A field's `folder` says where its uploads go (logo fields: "logos"; default "images"), and its picker opens on that tab. An image field stores a path, not a media id: '/uploads/' for an upload, or, as before, a bare filename in the field's public/ directory or a full URL. So the text box stays: old values keep working, and a URL from elsewhere can be pasted in. `resolve` on the field (a media.ts helper) turns a bare filename into something the preview can load. Uploading is editor and up; the server says the same. Reads use ttl: 0 because two people uploading at once is exactly when a cached list would lie. ═══════════════════════════════════════════════════════════════ */ import { FileAudio, X } from "@phosphor-icons/react"; import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; import { ApiError, get, post, upload } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; import { canWrite as roleCanWrite } from "../../lib/roles.ts"; export type MediaItem = { id: number; url: string; original_name: string; content_type: string; bytes: number; width: number | null; height: number | null; processed: boolean; uploaded_by: string | null; created_at: string; /** logos, images or thumbnails; null for clips and older files in the root. */ folder: string | null; }; /* The folder tabs, as [folder, label]; "" is every image. */ export const IMAGE_FOLDERS = [ ["", "All"], ["logos", "Logos"], ["images", "Images"], ["thumbnails", "Previews"], ] as const; export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0]; /* A tab strip over the folders; `value` is the one showing. */ export function FolderTabs({ value, onChange }: { value: string; onChange: (folder: ImageFolder) => void }) { return (
{IMAGE_FOLDERS.map(([folder, 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"; /* A light checkerboard, so a white logo on a transparent background is still visible in its thumbnail. */ const CHECKER = { backgroundColor: "#fff", backgroundImage: "linear-gradient(45deg,#e6eef0 25%,transparent 25%),linear-gradient(-45deg,#e6eef0 25%,transparent 25%)," + "linear-gradient(45deg,transparent 75%,#e6eef0 75%),linear-gradient(-45deg,transparent 75%,#e6eef0 75%)", backgroundSize: "12px 12px", backgroundPosition: "0 0,0 6px,6px -6px,-6px 0", }; export function formatBytes(bytes: number) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } export function mediaSize(item: MediaItem) { const dims = item.width && item.height ? `${item.width} × ${item.height}, ` : ""; return `${dims}${formatBytes(item.bytes)}`; } /* ── Data ────────────────────────────────────────────────────── */ export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise { const form = new FormData(); form.append("file", file); if (keepOriginal) form.append("keep_original", "1"); if (folder) form.append("folder", folder); return upload("/admin/media", form).then((data) => data.media); } /* `type` narrows to one kind of file: image fields pick images only. Blank lists everything, videos and audio saved from the clip tool included. */ export function useMediaLibrary(query: string, type?: "image" | "video" | "audio", folder?: string) { const [items, setItems] = useState(null); const [error, setError] = useState(null); const reload = useCallback(() => { const q = query.trim(); const params = new URLSearchParams(); if (q) params.set("q", q); if (type) params.set("type", type); if (folder) params.set("folder", folder); setError(null); get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 }) .then((data) => setItems(data.media)) .catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the library."), ); }, [query, type, folder]); useEffect(reload, [reload]); return { items, error, reload, setItems }; } /* ── Upload button ───────────────────────────────────────────── */ export function UploadButton({ onUploaded, multiple = false, label = "Upload", folder, }: { onUploaded: (item: MediaItem) => void; multiple?: boolean; label?: string; /** Where it goes; blank: the server's default, images. */ folder?: string; }) { const inputRef = useRef(null); const keepId = useId(); const [keepOriginal, setKeepOriginal] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function send(files: FileList | null) { if (!files || files.length === 0) return; setBusy(true); setError(null); try { // One at a time: each is up to 25 MB, and a failure should // name the file it happened to. for (const file of Array.from(files)) { try { onUploaded(await uploadImage(file, keepOriginal, folder)); } catch (err) { const why = err instanceof ApiError ? err.message : "Upload failed."; setError(files.length > 1 ? `${file.name}: ${why}` : why); break; } } } finally { setBusy(false); if (inputRef.current) inputRef.current.value = ""; } } return (
send(e.target.files)} />
{error &&

{error}

}
); } export const UPLOAD_HELP = "Photos are shrunk to 2400px and saved as WebP, which also removes their location data. " + "Keep original stores the file exactly as it is (up to 10 MB), including any location a phone saved in a photo; shrinking removes it. SVGs are always kept as they are."; /* ── Grid ────────────────────────────────────────────────────── */ export function MediaGrid({ items, selected, onPick, renderActions, }: { items: MediaItem[]; selected?: string | null; onPick?: (item: MediaItem) => void; renderActions?: (item: MediaItem) => ReactNode; }) { if (items.length === 0) { return

Nothing here yet.

; } return (
    {items.map((item) => { const isSelected = selected === item.url; const thumb = ( <>
    {item.content_type.startsWith("video/") ? ( // A still of the first frame; metadata only, not the file.

    {item.original_name}

    {mediaSize(item)}

    ); return (
  • {onPick ? ( ) : ( thumb )} {renderActions &&
    {renderActions(item)}
    }
  • ); })}
); } /* ── Picker dialog ───────────────────────────────────────────── */ export function MediaPicker({ selected, folder = "images", onPick, onClose, }: { selected?: string | null; /** The field's folder: the tab it opens on, where uploads go. */ folder?: string; onPick: (item: MediaItem) => void; onClose: () => void; }) { const { user } = useAuth(); const [query, setQuery] = useState(""); const [tab, setTab] = useState(folder); const { items, error, setItems } = useMediaLibrary(query, "image", tab); const dialogRef = useRef(null); // showModal gives focus trapping, Escape and the backdrop for free. useEffect(() => { dialogRef.current?.showModal(); }, []); return ( { // A click on the backdrop lands on the dialog itself. if (e.target === dialogRef.current) dialogRef.current?.close(); }} className="m-auto w-[min(56rem,calc(100vw-2rem))] rounded-2xl p-0 backdrop:bg-[#0f2f36]/40" >

Choose an image

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" />
{roleCanWrite(user) && (
{ setItems((current) => [item, ...(current ?? [])]); onPick(item); dialogRef.current?.close(); }} />

{UPLOAD_HELP}

)}
{error ? (

{error}

) : items === null ? (

Loading…

) : ( { onPick(item); dialogRef.current?.close(); }} /> )}
); } /* ── The form field ──────────────────────────────────────────── */ export function ImageInput({ id, value, resolve, folder, locked, className, onChange, }: { id: string; value: string | null | undefined; resolve?: (file?: string | null) => string | null; /** The field's `folder` (logos for logo fields); default images. */ folder?: string; locked: boolean; className: string; onChange: (value: string) => void; }) { const { user } = useAuth(); const [picking, setPicking] = useState(false); const [broken, setBroken] = useState(false); const src = value ? (resolve ? resolve(value) : value) : null; useEffect(() => setBroken(false), [src]); const editable = !locked && roleCanWrite(user); return (
{src && !broken ? ( setBroken(true)} /> ) : ( {src ? "Not found" : "No image"} )}
onChange(e.target.value)} className={className} /> {editable && (
onChange(item.url)} /> {value && ( )}
)}
{picking && ( onChange(item.url)} onClose={() => setPicking(false)} /> )}
); } /* ── Link preview field ──────────────────────────────────────── */ /* Fills only what's empty: a title somebody already typed is theirs, not the page's. Which fields it fills is the row's title, blurb and image, the featured card's names. */ export function LinkPreviewInput({ id, value, row, locked, className, showButton, fills = { title: "title", blurb: "blurb", image: "image" }, onChange, onPatch, }: { id: string; value: string | null | undefined; row: Record; locked: boolean; className: string; showButton: boolean; onChange: (value: string) => void; onPatch?: (patch: Record) => void; /** Which of the row's fields the preview fills (a list item's are * text, detail and media). */ fills?: { title: string; blurb: string; image: string }; }) { const { user } = useAuth(); const [busy, setBusy] = useState(false); const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null); async function fetchPreview() { if (!value || !onPatch) return; setBusy(true); setNote(null); try { const { preview } = await post("/admin/link-preview", { url: value }); const patch: Record = {}; if (!row[fills.title] && preview.title) patch[fills.title] = preview.title; if (!row[fills.blurb] && preview.description) patch[fills.blurb] = preview.description; if (!row[fills.image] && preview.image) patch[fills.image] = preview.image.url; onPatch(patch); const filled = Object.keys(patch).length; setNote( preview.image_error ? { tone: "error", text: `Filled ${filled} field${filled === 1 ? "" : "s"}. ${preview.image_error}` } : filled ? { tone: "ok", text: `Filled ${filled} empty field${filled === 1 ? "" : "s"}.` } : { tone: "ok", text: "Nothing to fill: those fields already have values, or the page has none." }, ); } catch (err) { setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't read that page." }); } finally { setBusy(false); } } return (
onChange(e.target.value)} placeholder="https://" className={className} /> {showButton && !locked && roleCanWrite(user) && (
{note && ( {note.text} )}
)}
); }