"use client"; /** The media library: pick an image, or upload one (with its alt text) and pick it. */ import { useRef, useState } from "react"; import { api } from "./api"; 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 }; 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 (
= 100 ? "bg-red-600" : s.percent >= 80 ? "bg-amber-500" : "bg-brand")} style={{ width: `${s.percent}%` }} />

{gb(s.usedBytes)} of {gb(s.limitBytes)} used

); } /** 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(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(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f }); setAlt(""); if (file.current) file.current.value = ""; onUploaded(m); }, "Uploaded."); return (
setAlt(e.target.value)} maxLength={500} disabled={disabled} /> Upload {message && {message.text}}
); } /** One image field: shows the chosen image, with Choose and Remove. */ export function ImagePicker({ value, onChange, label }: { value: string | null; onChange: (id: string | null) => void; label: string }) { const [open, setOpen] = useState(false); const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null); const chosen = data?.items.find((m) => m.id === value); return (
{label}
{chosen ? {chosen.alt} : No image}
setOpen(true)}>{value ? "Change" : "Choose"} {value && onChange(null)}>Remove}
{open && (

Choose an image

setOpen(false)}>Close
{data?.items.map((m) => ( ))}

Upload a new one

{data?.storage.full && Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.} { reload(); onChange(m.id); setOpen(false); }} />
)}
); }