Files
crosscode-platform/apps/website/frontend/src/admin/media.tsx
T
joshuaandClaude Opus 5.5 a9215ac4e4 Website 1.7.0: move and zoom photos in their frame; delete unused photos
- A section's photo (hero, welcome, invitation, image-text) shows in the
  shape of its frame for the current template and layout, with a Move and
  zoom dialog: drag or arrow keys to choose what stays in view, zoom to
  300%. Saved with the section as data.framing ({ x, y, zoom } by media
  id), a draft until published. The site draws it with object-position
  and scale() around that point; Bold split/collage frames now clip, and
  a zoomed photo stays inside Heritage's mat. Framing for photos a section
  no longer shows is dropped on save.
- Media library: each photo says where it's used; one used nowhere can be
  deleted with its files (DELETE /admin/media/:id, 409 IN_USE otherwise,
  audited as media_deleted).

Checked: Website backend tests (135) and typecheck, frontend typecheck,
lint and production build, and an e2e test of both flows in Chromium.
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:34:10 +02:00

116 lines
6.7 KiB
TypeScript

"use client";
/** The media library: pick an image, or upload one (with its alt text) and pick it. */
import { useRef, useState } from "react";
import { Move } from "lucide-react";
import { api } from "./api";
import { Framed, FramingDialog, useFraming } from "./framing";
import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui";
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] };
export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number };
export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
export function StorageMeter({ s }: { s: Storage }) {
return (
<div>
<div className="h-2 w-full overflow-hidden rounded bg-gray-200" role="progressbar" aria-valuenow={s.percent} aria-valuemin={0} aria-valuemax={100} aria-label="Storage used">
<div className={cx("h-full", s.percent >= 100 ? "bg-red-600" : s.percent >= 80 ? "bg-amber-500" : "bg-brand")} style={{ width: `${s.percent}%` }} />
</div>
<p className="mt-1 text-xs text-gray-600">{gb(s.usedBytes)} of {gb(s.limitBytes)} used</p>
</div>
);
}
/** Upload form: a photo and what it shows (alt text is required, §3 "Every image needs alt text"). */
export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) => void; disabled?: boolean }) {
const file = useRef<HTMLInputElement>(null);
const [alt, setAlt] = useState("");
const { busy, message, run } = useAction();
const go = () => run(async () => {
const f = file.current?.files?.[0];
if (!f) throw new Error("Choose a photo first.");
if (!alt.trim()) throw new Error("Say what the photo shows (for people who can't see it).");
const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f });
setAlt("");
if (file.current) file.current.value = "";
onUploaded(m);
}, "Uploaded.");
return (
<div className="space-y-3">
<Field label="Photo" hint="JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.">
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="block text-sm" disabled={disabled} />
</Field>
<Field label="What the photo shows" hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
<input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} />
</Field>
<Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
);
}
/**
* One image field: shows the chosen image, with Choose and Remove. In a section (`slot` and a
* FramingContext), it's shown in the shape of its frame on the site, with Move and zoom.
*/
export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) {
const [open, setOpen] = useState(false);
const [framingOpen, setFramingOpen] = useState(false);
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
const chosen = data?.items.find((m) => m.id === value);
const framing = useFraming();
const frame = framing && slot ? framing.frame(slot.key, slot.index) : null;
const focus = value ? framing?.get(value) : undefined;
return (
<div>
<span className="block text-sm font-medium text-gray-800">{label}</span>
<div className="mt-1 flex flex-wrap items-center gap-3">
{chosen && frame ? (
<button type="button" onClick={() => setFramingOpen(true)} title="Move and zoom" className="shrink-0 rounded border border-gray-200"
style={{ width: `${Math.round(Math.min(160, Math.max(48, 72 * frame.ratio)))}px` }}>
<Framed url={chosen.url} frame={frame} focus={focus} />
</button>
) : (
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
</div>
)}
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
{chosen && frame && <Btn onClick={() => setFramingOpen(true)}><Move className="h-4 w-4" aria-hidden />Move and zoom</Btn>}
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
</div>
{chosen && frame && focus && <p className="mt-1 text-xs text-gray-500">Moved{focus.zoom > 1 ? ` and zoomed to ${Math.round(focus.zoom * 100)}%` : ""}. Save to see it in the preview.</p>}
{framingOpen && chosen && frame && framing && (
<FramingDialog url={chosen.url} alt={chosen.alt} frame={frame} initial={focus}
onDone={(f) => { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} />
)}
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image">
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
<div className="mb-4 flex items-center justify-between">
<h2 className="text-lg font-semibold">Choose an image</h2>
<Btn onClick={() => setOpen(false)}>Close</Btn>
</div>
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
{data?.items.map((m) => (
<button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }}
className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}>
<img src={m.url} alt="" className="aspect-[4/3] w-full object-cover" />
<span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span>
</button>
))}
</div>
<div className="mt-6 border-t border-gray-200 pt-4">
<h3 className="mb-2 font-semibold">Upload a new one</h3>
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>}
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
</div>
</div>
</div>
)}
</div>
);
}