A photo field with a shape (crop: square for people, 16:9 for event photos, covers and hero photos, the photo's own for block images and schedule graphics) opens Frame the photo when a JPEG, PNG or WebP is uploaded: drag or arrow keys to place it, a zoom slider, and a shape menu. The framed part is drawn on a canvas and uploaded in place of the original; Upload as is skips it. Logos, SVGs and GIFs go as they are. No new dependency and nothing stored beside the picture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
780 lines
28 KiB
TypeScript
780 lines
28 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". Its From
|
||
requests tab lists photos sent with the Request
|
||
form (in Drive); picking one copies it into the
|
||
library first (RequestImages).
|
||
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/<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 { ClosedCaptioning, FileAudio, X } from "@phosphor-icons/react";
|
||
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||
|
||
import { useLocation } from "react-router-dom";
|
||
|
||
import { ApiError, get, post, upload } from "../../lib/api.ts";
|
||
import { useAuth } from "../../lib/auth.tsx";
|
||
import { clock, parseClock } from "../../lib/clock.ts";
|
||
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||
import { useSmallImage } from "../../lib/useSmallImage.ts";
|
||
import CropDialog, { type Crop } from "./CropDialog.tsx";
|
||
|
||
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, thumbnails or captions; 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"],
|
||
["captions", "Captions"],
|
||
] as const;
|
||
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
|
||
|
||
/* A tab strip over the folders; `value` is the one showing. `extra`
|
||
adds tabs after them (the picker's From requests). */
|
||
export function FolderTabs({
|
||
value,
|
||
onChange,
|
||
extra = [],
|
||
}: {
|
||
value: string;
|
||
onChange: (folder: string) => void;
|
||
extra?: [string, string][];
|
||
}) {
|
||
return (
|
||
<div role="tablist" aria-label="Folders" className="flex flex-wrap gap-1">
|
||
{[...IMAGE_FOLDERS, ...extra].map(([folder, label]) => (
|
||
<button
|
||
key={folder}
|
||
type="button"
|
||
role="tab"
|
||
aria-selected={value === folder}
|
||
onClick={() => onChange(folder)}
|
||
className={
|
||
"btn px-3 py-1 text-sm transition-colors " +
|
||
(value === folder ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
|
||
}
|
||
>
|
||
{label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const button =
|
||
"btn border border-brand px-3 py-1 text-sm 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,#f5f9f8 25%,transparent 25%),linear-gradient(-45deg,#f5f9f8 25%,transparent 25%)," +
|
||
"linear-gradient(45deg,transparent 75%,#f5f9f8 75%),linear-gradient(-45deg,transparent 75%,#f5f9f8 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<MediaItem> {
|
||
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);
|
||
}
|
||
|
||
/* How long a search waits after the last keystroke. */
|
||
export const SEARCH_PAUSE_MS = 250;
|
||
/* The most the library route sends (MAX_LIST, server/src/routes/media.js). */
|
||
const MEDIA_LIST_MAX = 500;
|
||
|
||
/* `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<MediaItem[] | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
// Only the newest request may write: a slow answer to an earlier
|
||
// search mustn't replace the list for a later one.
|
||
const latest = useRef(0);
|
||
|
||
const reload = useCallback(() => {
|
||
const ask = ++latest.current;
|
||
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) => ask === latest.current && setItems(data.media))
|
||
.catch((err) =>
|
||
ask === latest.current && setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
|
||
);
|
||
}, [query, type, folder]);
|
||
|
||
// A search waits for a pause in the typing; anything else asks at once.
|
||
useEffect(() => {
|
||
const timer = setTimeout(reload, query.trim() ? SEARCH_PAUSE_MS : 0);
|
||
return () => clearTimeout(timer);
|
||
}, [reload]);
|
||
|
||
return { items, error, reload, setItems };
|
||
}
|
||
|
||
/* ── Upload button ───────────────────────────────────────────── */
|
||
|
||
export function UploadButton({
|
||
onUploaded,
|
||
multiple = false,
|
||
label = "Upload",
|
||
folder,
|
||
crop,
|
||
}: {
|
||
onUploaded: (item: MediaItem) => void;
|
||
multiple?: boolean;
|
||
label?: string;
|
||
/** Where it goes; blank: the server's default, images. */
|
||
folder?: string;
|
||
/** The field's shape: a photo is framed (CropDialog) before it goes. */
|
||
crop?: Crop;
|
||
}) {
|
||
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);
|
||
const [framing, setFraming] = useState<File | null>(null);
|
||
// Captions are kept as they are, so there's no original to keep.
|
||
const captions = folder === "captions";
|
||
|
||
// A single photo for a field with a shape is framed first; SVGs and
|
||
// GIFs (which would lose their animation) go as they are.
|
||
function choose(files: FileList | null) {
|
||
const one = files?.length === 1 ? files[0] : null;
|
||
if (crop && one && /^image\/(jpeg|png|webp)$/.test(one.type)) setFraming(one);
|
||
else send(files ? Array.from(files) : []);
|
||
}
|
||
|
||
async function send(files: File[]) {
|
||
if (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 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 (
|
||
<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={captions ? ".vtt,text/vtt" : "image/jpeg,image/png,image/gif,image/webp,image/svg+xml"}
|
||
multiple={multiple}
|
||
className="hidden"
|
||
onChange={(e) => choose(e.target.files)}
|
||
/>
|
||
{!captions && (
|
||
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-muted">
|
||
<input
|
||
id={keepId}
|
||
type="checkbox"
|
||
checked={keepOriginal}
|
||
onChange={(e) => setKeepOriginal(e.target.checked)}
|
||
className="h-3.5 w-3.5 border-muted/40 text-link"
|
||
/>
|
||
Keep original
|
||
</label>
|
||
)}
|
||
</div>
|
||
{error && <p className="mt-1 text-xs text-danger">{error}</p>}
|
||
{framing && crop && (
|
||
<CropDialog
|
||
file={framing}
|
||
crop={crop}
|
||
onDone={(file) => {
|
||
setFraming(null);
|
||
if (file) send([file]);
|
||
else if (inputRef.current) inputRef.current.value = "";
|
||
}}
|
||
/>
|
||
)}
|
||
</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), 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 <p className="text-sm text-muted">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" style={CHECKER}>
|
||
{item.content_type.startsWith("video/") ? (
|
||
// Nothing loads until it's played: a page of videos
|
||
// would otherwise fetch every one's opening.
|
||
<video src={item.url} preload="none" muted className="h-full w-full bg-black object-contain" />
|
||
) : item.content_type.startsWith("audio/") ? (
|
||
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
|
||
<FileAudio weight="bold" className="h-10 w-10 text-link" />
|
||
</div>
|
||
) : item.content_type === "text/vtt" ? (
|
||
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
|
||
<ClosedCaptioning weight="bold" className="h-10 w-10 text-link" />
|
||
</div>
|
||
) : (
|
||
<Thumb url={item.url} />
|
||
)}
|
||
</div>
|
||
<p className="mt-1.5 truncate text-xs font-medium text-body" title={item.original_name}>
|
||
{item.original_name}
|
||
</p>
|
||
<p className="text-xs text-muted/80">{mediaSize(item)}</p>
|
||
</>
|
||
);
|
||
|
||
return (
|
||
<li
|
||
key={item.id}
|
||
className={`border bg-surface p-2 ${
|
||
isSelected ? "border-brand ring-2 ring-brand/30" : "border-muted/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>
|
||
{items.length >= MEDIA_LIST_MAX && (
|
||
<p className="notice mt-4 p-4 text-sm text-body">Newest {MEDIA_LIST_MAX} shown, search to narrow.</p>
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* A tile's picture: the 640px copy, the full file if there's none. */
|
||
function Thumb({ url }: { url: string }) {
|
||
const img = useSmallImage(url);
|
||
if (img.failed) return null;
|
||
return <img src={img.src} onError={img.onError} alt="" loading="lazy" className="h-full w-full object-contain" />;
|
||
}
|
||
|
||
/* ── Photos sent with requests ───────────────────────────────── */
|
||
|
||
const REQUESTS_TAB = "requests";
|
||
|
||
/* Photos from the Request form, which live in Drive: the one being
|
||
edited from first (Forms → Content requests → Create from this),
|
||
then newest. Picking one copies it into the library, into the
|
||
field's folder, and that copy is what the field gets. */
|
||
function RequestImages({ folder, onPick }: { folder?: string; onPick: (item: MediaItem) => void }) {
|
||
const current = (useLocation().state as any)?.fromRequest?.request ?? null;
|
||
const [files, setFiles] = useState<any[] | null>(null);
|
||
const [busy, setBusy] = useState<number | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
get("/admin/request-files", { ttl: 0 })
|
||
.then((data) => {
|
||
const photos = data.files.filter((f) => f.mime.startsWith("image/") && !f.missing);
|
||
setFiles([...photos.filter((f) => f.feedback_id === current), ...photos.filter((f) => f.feedback_id !== current)]);
|
||
})
|
||
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files."));
|
||
}, [current]);
|
||
|
||
async function pick(file) {
|
||
setBusy(file.id);
|
||
setError(null);
|
||
try {
|
||
const { media } = await post(`/admin/feedback/${file.feedback_id}/files/${file.id}/to-library`, { folder });
|
||
onPick(media);
|
||
} catch (err) {
|
||
setError(err instanceof ApiError ? err.message : "Couldn't copy it into the library.");
|
||
setBusy(null);
|
||
}
|
||
}
|
||
|
||
if (error && !files) return <p className="text-sm text-danger">{error}</p>;
|
||
if (!files) return <p className="text-sm text-muted">Loading…</p>;
|
||
if (files.length === 0) return <p className="text-sm text-muted">No photos have come in with requests.</p>;
|
||
return (
|
||
<>
|
||
{error && <p className="mb-3 text-sm text-danger">{error}</p>}
|
||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||
{files.map((file) => (
|
||
<li key={file.id} className="border border-muted/20 bg-surface p-2">
|
||
<button type="button" disabled={busy !== null} onClick={() => pick(file)} className="block w-full text-left disabled:opacity-60">
|
||
<div className="aspect-[4/3] overflow-hidden" style={CHECKER}>
|
||
{/* Straight from Drive through the server; private to the admin. */}
|
||
<img
|
||
src={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
|
||
alt=""
|
||
loading="lazy"
|
||
className="h-full w-full object-contain"
|
||
/>
|
||
</div>
|
||
<p className="mt-1.5 truncate text-xs font-medium text-body" title={file.name}>
|
||
{busy === file.id ? "Copying…" : file.name}
|
||
</p>
|
||
<p className="truncate text-xs text-muted/80">
|
||
{file.feedback_id === current ? "This request" : `Request #${file.feedback_id}`}
|
||
{file.subject ? `: ${file.subject}` : ""}
|
||
</p>
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ── 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<string>(folder);
|
||
const fromRequests = tab === REQUESTS_TAB;
|
||
const { items, error, setItems } = useMediaLibrary(query, tab === "captions" ? undefined : "image", fromRequests ? undefined : tab);
|
||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||
|
||
// showModal gives focus trapping, Escape and the backdrop for free.
|
||
useEffect(() => {
|
||
dialogRef.current?.showModal();
|
||
}, []);
|
||
|
||
return (
|
||
<dialog
|
||
ref={dialogRef}
|
||
aria-label="Choose an image"
|
||
onClose={onClose}
|
||
onClick={(e) => {
|
||
// 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))] p-0 backdrop:bg-[#001011]/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-bold text-link">Choose an image</h2>
|
||
<input
|
||
type="search"
|
||
value={query}
|
||
onChange={(e) => setQuery(e.target.value)}
|
||
placeholder="Search by file name"
|
||
aria-label="Search by file name"
|
||
className="ml-auto w-56 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 btn text-muted hover:bg-tint"
|
||
>
|
||
<X aria-hidden="true" weight="bold" className="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<div className="border-b border-brand/10 px-5 py-3">
|
||
<FolderTabs value={tab} onChange={setTab} extra={[[REQUESTS_TAB, "From requests"]]} />
|
||
</div>
|
||
|
||
{roleCanWrite(user) && (
|
||
<div className="border-b border-brand/10 px-5 py-3">
|
||
<UploadButton
|
||
label="Upload new"
|
||
folder={folder}
|
||
onUploaded={(item) => {
|
||
setItems((current) => [item, ...(current ?? [])]);
|
||
onPick(item);
|
||
dialogRef.current?.close();
|
||
}}
|
||
/>
|
||
<p className="mt-1 text-xs text-muted">{UPLOAD_HELP}</p>
|
||
</div>
|
||
)}
|
||
|
||
<div className="overflow-y-auto px-5 py-4">
|
||
{fromRequests ? (
|
||
<RequestImages
|
||
folder={folder}
|
||
onPick={(item) => {
|
||
setItems((current) => [item, ...(current ?? []).filter((m) => m.id !== item.id)]);
|
||
onPick(item);
|
||
dialogRef.current?.close();
|
||
}}
|
||
/>
|
||
) : error ? (
|
||
<p className="text-sm text-danger">{error}</p>
|
||
) : items === null ? (
|
||
<p className="text-sm text-muted">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,
|
||
folder,
|
||
videoUrl,
|
||
crop,
|
||
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;
|
||
/** A video link to take a frame from (the field's `frameFrom`). */
|
||
videoUrl?: string | null;
|
||
/** The field's `crop`: uploads are framed to it first. */
|
||
crop?: Crop;
|
||
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 border border-muted/20"
|
||
style={CHECKER}
|
||
>
|
||
{folder === "captions" && src ? (
|
||
<ClosedCaptioning weight="bold" className="h-8 w-8 text-link" aria-label="Captions file" />
|
||
) : 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-muted/70">
|
||
{src ? "Not found" : folder === "captions" ? "No file" : "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 folder={folder} crop={crop} 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-muted hover:text-danger"
|
||
>
|
||
Clear
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
{editable && videoUrl && <FrameFromVideo url={videoUrl} className={className} onSaved={onChange} />}
|
||
</div>
|
||
|
||
{picking && (
|
||
<MediaPicker
|
||
selected={value}
|
||
folder={folder}
|
||
onPick={(item) => onChange(item.url)}
|
||
onClose={() => setPicking(false)}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ── Frame from a video ──────────────────────────────────────── */
|
||
|
||
/* A link's own start time (YouTube's t=83 or t=83s), so a link
|
||
copied at the moment wanted starts the picker there. */
|
||
function startOf(url: string): number {
|
||
try {
|
||
const t = new URL(url).searchParams.get("t") ?? "";
|
||
return /^\d+s?$/.test(t) ? parseInt(t, 10) : 0;
|
||
} catch {
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) {
|
||
const [text, setText] = useState(() => clock(startOf(url)));
|
||
const [busy, setBusy] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const timeId = useId();
|
||
const seconds = parseClock(text);
|
||
|
||
async function take() {
|
||
setBusy(true);
|
||
setError(null);
|
||
try {
|
||
const { media } = await post("/admin/video-frame", { url, seconds });
|
||
onSaved(media.url);
|
||
} catch (err) {
|
||
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<label htmlFor={timeId} className="text-sm text-muted">
|
||
Frame at
|
||
</label>
|
||
<div className="w-24">
|
||
<input id={timeId} type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="eg. 1:23" className={className} />
|
||
</div>
|
||
<button type="button" className={button} disabled={busy || seconds == null} onClick={take}>
|
||
{busy ? "Taking…" : "Use this frame"}
|
||
</button>
|
||
{error && <span className="text-xs text-danger">{error}</span>}
|
||
</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,
|
||
fills = { title: "title", blurb: "blurb", image: "image" },
|
||
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;
|
||
/** 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<string, any> = {};
|
||
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 (
|
||
<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-link" : "text-danger"}`}>
|
||
{note.text}
|
||
</span>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|