Front page → Featured cards (migration 030) holds cards of three kinds: a record on the site, whose title, picture and link fill in from the record; a link, with a Fetch preview button that reads the page's title, description and preview image into the media library; and a video, drawn as a thumbnail that loads the player when pressed. A 'featured' section draws them. The cards are shared: featured_cards is owned polymorphically and FeaturedCards.tsx draws them, ready for the Community blog. Deleting a record removes its cards; an unpublished record's card is hidden. The preview fetch only goes to public http(s) addresses on standard ports, pinned to the vetted IP, with each redirect checked again. Along the way: repeater fields can show by another field's value (a hidden one is cleared), a CHECK named as a sentence is shown as the error, and the timeline's record list is now record_refs for both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
494 lines
16 KiB
TypeScript
494 lines
16 KiB
TypeScript
/* ═══════════════════════════════════════════════════════════════
|
||
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.
|
||
|
||
An image field stores a path, not a media id: '/uploads/<file>'
|
||
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 { 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;
|
||
};
|
||
|
||
const button =
|
||
"rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] " +
|
||
"transition-colors hover:bg-[#eef9fb] 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): Promise<MediaItem> {
|
||
const form = new FormData();
|
||
form.append("file", file);
|
||
if (keepOriginal) form.append("keep_original", "1");
|
||
return upload("/admin/media", form).then((data) => data.media);
|
||
}
|
||
|
||
export function useMediaLibrary(query: string) {
|
||
const [items, setItems] = useState<MediaItem[] | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
const reload = useCallback(() => {
|
||
const q = query.trim();
|
||
setError(null);
|
||
get(`/admin/media${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
|
||
.then((data) => setItems(data.media))
|
||
.catch((err) =>
|
||
setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
|
||
);
|
||
}, [query]);
|
||
|
||
useEffect(reload, [reload]);
|
||
|
||
return { items, error, reload, setItems };
|
||
}
|
||
|
||
/* ── Upload button ───────────────────────────────────────────── */
|
||
|
||
export function UploadButton({
|
||
onUploaded,
|
||
multiple = false,
|
||
label = "Upload",
|
||
}: {
|
||
onUploaded: (item: MediaItem) => void;
|
||
multiple?: boolean;
|
||
label?: string;
|
||
}) {
|
||
const inputRef = useRef<HTMLInputElement>(null);
|
||
const keepId = useId();
|
||
const [keepOriginal, setKeepOriginal] = useState(false);
|
||
const [busy, setBusy] = useState(false);
|
||
const [error, setError] = useState<string | null>(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));
|
||
} 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 (
|
||
<div>
|
||
<div className="flex flex-wrap items-center gap-3">
|
||
<button
|
||
type="button"
|
||
className={button}
|
||
disabled={busy}
|
||
onClick={() => inputRef.current?.click()}
|
||
>
|
||
{busy ? "Uploading…" : label}
|
||
</button>
|
||
<input
|
||
ref={inputRef}
|
||
type="file"
|
||
accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
|
||
multiple={multiple}
|
||
className="hidden"
|
||
onChange={(e) => send(e.target.files)}
|
||
/>
|
||
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-[#4a6b72]">
|
||
<input
|
||
id={keepId}
|
||
type="checkbox"
|
||
checked={keepOriginal}
|
||
onChange={(e) => setKeepOriginal(e.target.checked)}
|
||
className="h-3.5 w-3.5 rounded border-[#4a6b72]/40 text-[#138ba0]"
|
||
/>
|
||
Keep original
|
||
</label>
|
||
</div>
|
||
{error && <p className="mt-1 text-xs text-[#b3261e]">{error}</p>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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). 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 <p className="text-sm text-[#4a6b72]">Nothing here yet.</p>;
|
||
}
|
||
|
||
return (
|
||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||
{items.map((item) => {
|
||
const isSelected = selected === item.url;
|
||
const thumb = (
|
||
<>
|
||
<div className="aspect-[4/3] overflow-hidden rounded-lg" style={CHECKER}>
|
||
<img
|
||
src={item.url}
|
||
alt=""
|
||
loading="lazy"
|
||
className="h-full w-full object-contain"
|
||
/>
|
||
</div>
|
||
<p className="mt-1.5 truncate text-xs font-medium text-[#26454c]" title={item.original_name}>
|
||
{item.original_name}
|
||
</p>
|
||
<p className="text-xs text-[#4a6b72]/80">{mediaSize(item)}</p>
|
||
</>
|
||
);
|
||
|
||
return (
|
||
<li
|
||
key={item.id}
|
||
className={`rounded-xl border bg-white p-2 ${
|
||
isSelected ? "border-[#138ba0] ring-2 ring-[#138ba0]/30" : "border-[#4a6b72]/20"
|
||
}`}
|
||
>
|
||
{onPick ? (
|
||
<button
|
||
type="button"
|
||
onClick={() => onPick(item)}
|
||
className="block w-full text-left"
|
||
aria-pressed={isSelected}
|
||
>
|
||
{thumb}
|
||
</button>
|
||
) : (
|
||
thumb
|
||
)}
|
||
{renderActions && <div className="mt-2">{renderActions(item)}</div>}
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
);
|
||
}
|
||
|
||
/* ── Picker dialog ───────────────────────────────────────────── */
|
||
|
||
export function MediaPicker({
|
||
selected,
|
||
onPick,
|
||
onClose,
|
||
}: {
|
||
selected?: string | null;
|
||
onPick: (item: MediaItem) => void;
|
||
onClose: () => void;
|
||
}) {
|
||
const { user } = useAuth();
|
||
const [query, setQuery] = useState("");
|
||
const { items, error, setItems } = useMediaLibrary(query);
|
||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||
|
||
// showModal gives focus trapping, Escape and the backdrop for free.
|
||
useEffect(() => {
|
||
dialogRef.current?.showModal();
|
||
}, []);
|
||
|
||
return (
|
||
<dialog
|
||
ref={dialogRef}
|
||
onClose={onClose}
|
||
onClick={(e) => {
|
||
// A click on the backdrop lands on the dialog itself.
|
||
if (e.target === dialogRef.current) dialogRef.current?.close();
|
||
}}
|
||
className="w-[min(56rem,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-[#138ba0]/15 px-5 py-4">
|
||
<h2 className="text-lg font-semibold text-[#138ba0]">Choose an image</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-[#4a6b72]/25 px-3 py-1.5 text-sm outline-none focus:border-[#138ba0]"
|
||
/>
|
||
<button
|
||
type="button"
|
||
onClick={() => dialogRef.current?.close()}
|
||
aria-label="Close"
|
||
className="h-8 w-8 rounded-full text-[#4a6b72] hover:bg-[#eef9fb]"
|
||
>
|
||
✕
|
||
</button>
|
||
</div>
|
||
|
||
{roleCanWrite(user) && (
|
||
<div className="border-b border-[#138ba0]/10 px-5 py-3">
|
||
<UploadButton
|
||
label="Upload new"
|
||
onUploaded={(item) => {
|
||
setItems((current) => [item, ...(current ?? [])]);
|
||
onPick(item);
|
||
dialogRef.current?.close();
|
||
}}
|
||
/>
|
||
<p className="mt-1 text-xs text-[#4a6b72]">{UPLOAD_HELP}</p>
|
||
</div>
|
||
)}
|
||
|
||
<div className="overflow-y-auto px-5 py-4">
|
||
{error ? (
|
||
<p className="text-sm text-[#b3261e]">{error}</p>
|
||
) : items === null ? (
|
||
<p className="text-sm text-[#4a6b72]">Loading…</p>
|
||
) : (
|
||
<MediaGrid
|
||
items={items}
|
||
selected={selected}
|
||
onPick={(item) => {
|
||
onPick(item);
|
||
dialogRef.current?.close();
|
||
}}
|
||
/>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</dialog>
|
||
);
|
||
}
|
||
|
||
/* ── The form field ──────────────────────────────────────────── */
|
||
|
||
export function ImageInput({
|
||
id,
|
||
value,
|
||
resolve,
|
||
locked,
|
||
className,
|
||
onChange,
|
||
}: {
|
||
id: string;
|
||
value: string | null | undefined;
|
||
resolve?: (file?: string | null) => string | null;
|
||
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 (
|
||
<div className="flex gap-3">
|
||
<div
|
||
className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-[#4a6b72]/20"
|
||
style={CHECKER}
|
||
>
|
||
{src && !broken ? (
|
||
<img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} />
|
||
) : (
|
||
<span className="px-1 text-center text-[10px] text-[#4a6b72]/70">
|
||
{src ? "Not found" : "No image"}
|
||
</span>
|
||
)}
|
||
</div>
|
||
|
||
<div className="min-w-0 flex-1 space-y-2">
|
||
<input
|
||
id={id}
|
||
type="text"
|
||
value={value ?? ""}
|
||
readOnly={locked}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
className={className}
|
||
/>
|
||
{editable && (
|
||
<div className="flex flex-wrap items-start gap-2">
|
||
<UploadButton onUploaded={(item) => onChange(item.url)} />
|
||
<button type="button" className={button} onClick={() => setPicking(true)}>
|
||
Choose from library
|
||
</button>
|
||
{value && (
|
||
<button
|
||
type="button"
|
||
onClick={() => onChange("")}
|
||
className="px-2 py-1 text-sm text-[#4a6b72] hover:text-[#b3261e]"
|
||
>
|
||
Clear
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{picking && (
|
||
<MediaPicker
|
||
selected={value}
|
||
onPick={(item) => onChange(item.url)}
|
||
onClose={() => setPicking(false)}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ── 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,
|
||
onChange,
|
||
onPatch,
|
||
}: {
|
||
id: string;
|
||
value: string | null | undefined;
|
||
row: Record<string, any>;
|
||
locked: boolean;
|
||
className: string;
|
||
showButton: boolean;
|
||
onChange: (value: string) => void;
|
||
onPatch?: (patch: Record<string, any>) => void;
|
||
}) {
|
||
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<string, any> = {};
|
||
if (!row.title && preview.title) patch.title = preview.title;
|
||
if (!row.blurb && preview.description) patch.blurb = preview.description;
|
||
if (!row.image && preview.image) patch.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 (
|
||
<div className="space-y-2">
|
||
<input
|
||
id={id}
|
||
type="text"
|
||
value={value ?? ""}
|
||
readOnly={locked}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
placeholder="https://"
|
||
className={className}
|
||
/>
|
||
{showButton && !locked && roleCanWrite(user) && (
|
||
<div className="flex flex-wrap items-center gap-3">
|
||
<button type="button" className={button} disabled={busy || !value} onClick={fetchPreview}>
|
||
{busy ? "Fetching…" : "Fetch preview"}
|
||
</button>
|
||
{note && (
|
||
<span className={`text-xs ${note.tone === "ok" ? "text-[#138ba0]" : "text-[#b3261e]"}`}>
|
||
{note.text}
|
||
</span>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|