feat(website): the admin, with drafts, preview, publish and restore

Admin API and screens: dashboard and setup checklist, template and
style, pages and blocks, ministries, leadership, media library with
the storage limit, publish and history. Pending changes with who and
when, discard one, one Publish, restore any version (each version
keeps the working copy's rows, never sent to visitors). Preview on
the site's own addresses with a bar (widths, back, publish); shared
preview links for 7 days or until revoked. Roles checked, same-origin
changes only. Publish refreshes the public pages at once
(WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the
admin's flows and axe on every screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:30:29 +02:00
co-authored by Claude Opus 5.5
parent 3caa1d1e1a
commit 84c5b0c08e
44 changed files with 2404 additions and 65 deletions
@@ -0,0 +1,74 @@
"use client";
/** A list of things the church keeps (ministries, its team): add, edit, remove. Drafts until Publish. */
import { useState } from "react";
import { api } from "./api";
import { ImagePicker } from "./media";
import { Btn, Field, inputClass, Loading, Notice, Panel, useAction, useAdmin } from "./ui";
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string };
type Row = Record<string, unknown> & { id: string };
function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: ListField[]; initial: Row | Record<string, unknown>; onSave: (v: Record<string, unknown>) => void; onCancel: () => void; busy: boolean; errors: Record<string, string> }) {
const [v, setV] = useState<Record<string, unknown>>(initial);
return (
<div className="space-y-3">
{fields.map((f) => f.kind === "image"
? <ImagePicker key={f.key} label={f.label} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id })} />
: (
<Field key={f.key} label={f.label} hint={f.hint} error={errors[f.key]}>
{f.kind === "text"
? <input className={inputClass} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />
: <textarea className={inputClass} rows={4} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />}
</Field>
))}
<div className="flex gap-2"><Btn kind="primary" busy={busy} onClick={() => onSave(v)}>Save</Btn><Btn onClick={onCancel}>Cancel</Btn></div>
</div>
);
}
export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }: { path: string; fields: ListField[]; nameKey: string; subKey: string; addLabel: string; canAdd: boolean }) {
const { data, error, reload } = useAdmin<Row[]>(path);
const [editing, setEditing] = useState<string | null>(null);
const { busy, message, fields: errors, run } = useAction();
if (!data) return <Loading error={error} />;
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
const body = Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null]));
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
setEditing(null);
await reload();
}, "Saved as a draft.");
return (
<div className="space-y-4">
{message && <Notice tone={message.tone}>{message.text}</Notice>}
<Panel>
{data.length === 0 && <p className="text-gray-600">None yet.</p>}
<ul className="divide-y divide-gray-200">
{data.map((row) => (
<li key={row.id} className="py-3">
{editing === row.id ? (
<Editor fields={fields} initial={row} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(row.id, v)} />
) : (
<div className="flex items-center justify-between gap-3">
<div><p className="font-medium">{String(row[nameKey])}</p>{row[subKey] ? <p className="text-sm text-gray-600">{String(row[subKey])}</p> : null}</div>
<div className="flex gap-2">
<Btn onClick={() => setEditing(row.id)}>Edit</Btn>
{canAdd && <Btn kind="danger" onClick={() => run(async () => { await api(`${path}/${row.id}`, { method: "DELETE" }); await reload(); }, "Removed (until you publish, you can discard this).")}>Remove</Btn>}
</div>
</div>
)}
</li>
))}
</ul>
</Panel>
{canAdd && (
<Panel title={addLabel}>
{editing === "new"
? <Editor fields={fields} initial={{}} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(null, v)} />
: <Btn kind="primary" onClick={() => setEditing("new")}>{addLabel}</Btn>}
</Panel>
)}
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
/** The admin's frame: navigation, the pending change count, Preview and Sign out (§4, §10). */
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ROLE_NAMES } from "./api";
import { cx, useAdmin } from "./ui";
const NAV = [
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/template", label: "Template and style" },
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" },
{ href: "/admin/leaders", label: "Leadership" },
{ href: "/admin/media", label: "Media library" },
{ href: "/admin/publish", label: "Publish and history" },
];
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
const path = usePathname();
const { data } = useAdmin<{ pending: number }>(`/overview?for=${encodeURIComponent(path)}`);
return (
<div className="min-h-screen bg-gray-50 font-sans text-gray-900">
<header className="border-b border-gray-200 bg-white">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-3">
<Link href="/admin" className="font-semibold">Website admin</Link>
<div className="flex flex-wrap items-center gap-3 text-sm">
{data && data.pending > 0 && <Link href="/admin/publish" className="rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-900">{data.pending} {data.pending === 1 ? "change" : "changes"} not published</Link>}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
<a href="/preview/start" className="rounded-md border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50">Preview</a>
<span className="text-gray-600">{user.name} · {ROLE_NAMES[user.role] ?? user.role}</span>
<form method="post" action="/api/auth/signout"><button type="submit" className="text-gray-600 underline-offset-4 hover:underline">Sign out</button></form>
</div>
</div>
</header>
<div className="mx-auto grid max-w-6xl gap-6 px-4 py-6 md:grid-cols-[13rem_1fr]">
<nav aria-label="Admin">
<ul className="flex gap-1 overflow-x-auto md:flex-col">
{NAV.map((n) => {
const current = n.href === "/admin" ? path === "/admin" : path.startsWith(n.href);
return (
<li key={n.href}>
<Link href={n.href} aria-current={current ? "page" : undefined}
className={cx("block whitespace-nowrap rounded-md px-3 py-2 text-sm", current ? "bg-brand text-brand-on" : "text-gray-700 hover:bg-gray-100")}>{n.label}</Link>
</li>
);
})}
</ul>
</nav>
<main>{children}</main>
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
/** The admin API from the browser (same origin: the session cookie goes along, and so does Origin). */
export class AdminError extends Error {
constructor(message: string, public code: string, public status: number, public fields: Record<string, string> = {}) {
super(message);
}
}
export async function api<T = unknown>(path: string, opts: { method?: string; body?: unknown; raw?: Blob } = {}): Promise<T> {
const res = await fetch(`/api/v1/admin${path}`, {
method: opts.method ?? (opts.body !== undefined || opts.raw ? "POST" : "GET"),
headers: opts.raw ? { "Content-Type": "application/octet-stream" } : opts.body !== undefined ? { "Content-Type": "application/json" } : undefined,
body: opts.raw ?? (opts.body !== undefined ? JSON.stringify(opts.body) : undefined),
cache: "no-store",
});
const data = await res.json().catch(() => null);
if (!res.ok) {
const e = (data as { error?: { message?: string; code?: string; fields?: Record<string, string> } } | null)?.error;
// Signed out: off to sign in (a route on the backend), and back to this page.
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
if (res.status === 401) window.location.href = `/api/auth/signin?returnTo=${encodeURIComponent(window.location.pathname)}`;
throw new AdminError(e?.message ?? `Something went wrong (${res.status}).`, e?.code ?? "ERROR", res.status, e?.fields ?? {});
}
return data as T;
}
export const ROLE_NAMES: Record<string, string> = { owner: "Owner", admin: "Admin", editor: "Editor", ministry_leader: "Ministry leader", viewer: "Viewer" };
export const canEdit = (role: string) => ["owner", "admin", "editor"].includes(role);
+114
View File
@@ -0,0 +1,114 @@
"use client";
/**
* The forms for each homepage section and block, from one description per type (the backend's
* zod schemas in src/site/sections.ts check what's saved; field errors come back by path).
*/
import { ImagePicker } from "./media";
import { Btn, Field, inputClass } from "./ui";
type Spec =
| { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number }
| { key: string; kind: "number"; label: string; min: number; max: number }
| { key: string; kind: "image"; label: string }
| { key: string; kind: "images"; label: string; max: number }
| { key: string; kind: "button"; label: string }
| { key: string; kind: "group"; label: string; fields: Spec[] };
const heading: Spec = { key: "heading", kind: "text", label: "Heading", max: 120 };
const button: Spec = { key: "button", kind: "button", label: "Button" };
export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
hero: { name: "Top of the page (hero)", fields: [
{ key: "headline", kind: "text", label: "Headline", max: 120 },
{ key: "subline", kind: "textarea", label: "Under the headline", max: 300 },
{ key: "images", kind: "images", label: "Photos (the first for Photo and Split; up to three for Collage)", max: 3 },
button,
] },
serviceTimes: { name: "Service times and location", fields: [heading, { key: "note", kind: "textarea", label: "A note for visitors", hint: "The times and address come from your church profile.", max: 300 }] },
welcome: { name: "Welcome", fields: [
heading,
{ key: "mission", kind: "text", label: "Mission (one line)", max: 200 },
{ key: "body", kind: "textarea", label: "Introduction", hint: "Leave an empty line between paragraphs.", max: 4000 },
{ key: "imageId", kind: "image", label: "Photo (Image and text layout)" },
{ key: "pastor", kind: "group", label: "Pastor's photo and quote (With pastor layout)", fields: [
{ key: "name", kind: "text", label: "Name", max: 120 }, { key: "role", kind: "text", label: "Role", max: 80 },
{ key: "quote", kind: "textarea", label: "Quote", max: 400 }, { key: "photoId", kind: "image", label: "Photo" },
] },
] },
ministries: { name: "Ministries", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
team: { name: "Team", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
events: { name: "Upcoming events", fields: [heading, { key: "count", kind: "number", label: "How many to show", min: 2, max: 12 }] },
latestMessage: { name: "Latest message", fields: [heading] },
invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo (Image background layout)" }] },
};
export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
text: { name: "Text", fields: [heading, { key: "body", kind: "textarea", label: "Text", hint: "Leave an empty line between paragraphs.", max: 20000 }] },
"image-text": { name: "Image and text", fields: [heading, { key: "body", kind: "textarea", label: "Text", max: 4000 }, { key: "imageId", kind: "image", label: "Photo" }, button] },
quote: { name: "Quote", fields: [{ key: "quote", kind: "textarea", label: "Quote", max: 600 }, { key: "by", kind: "text", label: "Who said it", max: 120 }] },
cta: { name: "Call to action", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button] },
};
type Data = Record<string, unknown>;
export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string }) {
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
return (
<div className="space-y-4">
{fields.map((f) => {
const err = errors[`${prefix}${f.key}`];
const v = value[f.key];
switch (f.kind) {
case "text":
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><input className={inputClass} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || null)} /></Field>;
case "textarea":
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>;
case "number":
return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
case "image":
return <div key={f.key}><ImagePicker label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
case "images": {
const list = Array.isArray(v) ? (v as string[]) : [];
return (
<div key={f.key} className="space-y-2">
<p className="text-sm font-medium text-gray-800">{f.label}</p>
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
</div>
);
}
case "button": {
const b = v as { label: string; href: string } | null;
return (
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
{b ? (
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Says" error={errors[`${prefix}${f.key}.label`]}><input className={inputClass} value={b.label} maxLength={60} onChange={(e) => set(f.key, { ...b, label: e.target.value })} /></Field>
<Field label="Goes to" hint="A page here (/visit) or https://…" error={errors[`${prefix}${f.key}.href`]}><input className={inputClass} value={b.href} onChange={(e) => set(f.key, { ...b, href: e.target.value })} /></Field>
<Btn kind="link" onClick={() => set(f.key, null)}>No button</Btn>
</div>
) : <Btn onClick={() => set(f.key, { label: "Plan your visit", href: "/visit" })}>Add a button</Btn>}
</fieldset>
);
}
case "group": {
const g = v as Data | null;
return (
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
{g ? (
<>
<DataForm fields={f.fields} value={g} onChange={(n) => set(f.key, n)} errors={errors} prefix={`${prefix}${f.key}.`} />
<Btn kind="link" className="mt-3" onClick={() => set(f.key, null)}>Remove</Btn>
</>
) : <Btn onClick={() => set(f.key, { name: "", role: null, quote: null, photoId: null })}>Add</Btn>}
</fieldset>
);
}
}
})}
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
"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 (
<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. */
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 (
<div>
<span className="block text-sm font-medium text-gray-800">{label}</span>
<div className="mt-1 flex items-center gap-3">
<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-400">No image</span>}
</div>
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
</div>
{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. To get more (5 GB at a time), contact Cross Code.</Notice>}
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
</div>
</div>
</div>
)}
</div>
);
}
+119
View File
@@ -0,0 +1,119 @@
"use client";
/** The admin's own building blocks: plain, calm, the church's colour for the main action. */
import { useCallback, useEffect, useState } from "react";
import { api, AdminError } from "./api";
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
export function Title({ children, sub, actions }: { children: React.ReactNode; sub?: React.ReactNode; actions?: React.ReactNode }) {
return (
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-gray-600">{sub}</p>}
</div>
{actions && <div className="flex flex-wrap gap-2">{actions}</div>}
</div>
);
}
export function Panel({ children, className, title }: { children: React.ReactNode; className?: string; title?: string }) {
return (
<section className={cx("rounded-lg border border-gray-200 bg-white p-5 shadow-sm", className)}>
{title && <h2 className="mb-4 text-lg font-semibold text-gray-900">{title}</h2>}
{children}
</section>
);
}
type BtnProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: "primary" | "secondary" | "danger" | "link"; busy?: boolean };
export function Btn({ kind = "secondary", busy, className, children, disabled, ...rest }: BtnProps) {
return (
<button
type="button"
{...rest}
disabled={disabled || busy}
className={cx(
"inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50",
kind === "primary" && "bg-brand text-brand-on hover:bg-brand-dark",
kind === "secondary" && "border border-gray-300 bg-white text-gray-800 hover:bg-gray-50",
kind === "danger" && "border border-red-300 bg-white text-red-700 hover:bg-red-50",
kind === "link" && "px-0 py-0 text-brand-text underline-offset-4 hover:underline",
className,
)}
>
{busy ? "Working…" : children}
</button>
);
}
export function Field({ label, hint, error, children }: { label: string; hint?: React.ReactNode; error?: string; children: React.ReactNode }) {
return (
<label className="block">
<span className="block text-sm font-medium text-gray-800">{label}</span>
<span className="mt-1 block">{children}</span>
{hint && !error && <span className="mt-1 block text-xs text-gray-500">{hint}</span>}
{error && <span className="mt-1 block text-xs font-medium text-red-700" role="alert">{error}</span>}
</label>
);
}
export const inputClass = "w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-brand focus:outline-none focus:ring-2 focus:ring-brand/30";
export function Notice({ tone = "info", children }: { tone?: "info" | "error" | "success" | "warning"; children: React.ReactNode }) {
const tones = { info: "border-blue-200 bg-blue-50 text-blue-900", error: "border-red-200 bg-red-50 text-red-900", success: "border-green-200 bg-green-50 text-green-900", warning: "border-amber-200 bg-amber-50 text-amber-900" };
return <div role={tone === "error" ? "alert" : "status"} className={cx("rounded-md border px-4 py-3 text-sm", tones[tone])}>{children}</div>;
}
/** Loads `path` from the admin API; `reload` fetches it again. */
export function useAdmin<T>(path: string | null) {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
if (!path) return;
try {
setData(await api<T>(path));
setError(null);
} catch (e) {
setError((e as Error).message);
}
}, [path]);
useEffect(() => {
// Fetching on mount is this hook's job.
// eslint-disable-next-line react-hooks/set-state-in-effect
load();
}, [load]);
return { data, error, reload: load, setData };
}
/** Runs an action, keeping its busy state, message and field errors. */
export function useAction() {
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
const [fields, setFields] = useState<Record<string, string>>({});
const run = useCallback(async <T,>(fn: () => Promise<T>, success?: string): Promise<T | null> => {
setBusy(true);
setMessage(null);
setFields({});
try {
const out = await fn();
if (success) setMessage({ tone: "success", text: success });
return out;
} catch (e) {
setMessage({ tone: "error", text: (e as Error).message });
if (e instanceof AdminError) setFields(e.fields);
return null;
} finally {
setBusy(false);
}
}, []);
return { busy, message, fields, run, setMessage };
}
export function Loading({ error }: { error?: string | null }) {
return error ? <Notice tone="error">{error}</Notice> : <p className="text-gray-500">Loading…</p>;
}
export const when = (iso: string | null) => (iso ? new Intl.DateTimeFormat("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }).format(new Date(iso)) : "");