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)) : "");
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { AdminShell } from "@/admin/Shell";
import { loadMe, signInHref } from "@/lib/admin";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
export const dynamic = "force-dynamic";
/** Every admin page: signed in through the church's Accounts (§10), else off to sign in and back. */
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const me = await loadMe();
if (!me) {
const path = (await headers()).get("x-ccw-path") || "/admin";
redirect(signInHref(path.startsWith("/admin") ? path : "/admin"));
}
return <AdminShell user={me.user}>{children}</AdminShell>;
}
@@ -0,0 +1,21 @@
"use client";
import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor";
import { Title, useAdmin } from "@/admin/ui";
/** The team (§6): shown on the Leadership page and the home page's Team section. */
export default function Leaders() {
const { data } = useAdmin<{ user: { role: string } }>("/me");
return (
<>
<Title sub="The people who lead your church. The first is shown largest in the Featured layout.">Leadership</Title>
<ListEditor path="/leaders" nameKey="name" subKey="role" addLabel="Add a person" canAdd={!!data && canEdit(data.user.role)} fields={[
{ key: "name", label: "Name", kind: "text", max: 120 },
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
{ key: "bio", label: "About them", kind: "textarea", max: 4000 },
{ key: "photoId", label: "Photo", kind: "image" },
]} />
</>
);
}
@@ -0,0 +1,50 @@
"use client";
import { useState } from "react";
import { api } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
export default function Media() {
const { data, error, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>("/media");
const [alts, setAlts] = useState<Record<string, string>>({});
const { busy, message, run } = useAction();
if (!data) return <Loading error={error} />;
const s = data.storage;
return (
<>
<Title sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<Panel>
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
{data.items.length === 0 && <p className="text-gray-600">No photos yet.</p>}
<ul className="grid gap-4 sm:grid-cols-2">
{data.items.map((m) => (
<li key={m.id} className="space-y-2">
<img src={m.url} alt={m.alt} className="aspect-[4/3] w-full rounded object-cover" />
<label className="block text-xs text-gray-600">What it shows
<input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} />
</label>
{alts[m.id] !== undefined && alts[m.id] !== m.alt && (
<Btn busy={busy} onClick={() => run(async () => { await api(`/media/${m.id}`, { method: "PUT", body: { alt: alts[m.id] } }); await reload(); }, "Saved.")}>Save</Btn>
)}
{!m.alt && <p className="text-xs font-medium text-amber-800">Add what it shows, for people who can&apos;t see it.</p>}
<p className="text-xs text-gray-500">{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}</p>
</li>
))}
</ul>
</Panel>
<div className="space-y-6">
<Panel title="Storage">
<StorageMeter s={s} />
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} More comes in 5 GB steps (R20 a month each): contact Cross Code.</Notice></div>}
</Panel>
<Panel title="Upload a photo">
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
</Panel>
</div>
</div>
</>
);
}
@@ -0,0 +1,21 @@
"use client";
import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor";
import { Title, useAdmin } from "@/admin/ui";
/** Ministries (§6): shown on the Ministries page and the home page's Ministries section. */
export default function Ministries() {
const { data } = useAdmin<{ user: { role: string } }>("/me");
return (
<>
<Title sub="Your ministries' pages. A ministry leader can edit their own; an editor publishes it.">Ministries</Title>
<ListEditor path="/ministries" nameKey="name" subKey="summary" addLabel="Add a ministry" canAdd={!!data && canEdit(data.user.role)} fields={[
{ key: "name", label: "Name", kind: "text", max: 120 },
{ key: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
{ key: "body", label: "More about it", kind: "textarea", max: 8000 },
{ key: "imageId", label: "Photo", kind: "image" },
]} />
</>
);
}
+43 -21
View File
@@ -1,26 +1,48 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/admin";
"use client";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
export const dynamic = "force-dynamic";
import Link from "next/link";
import { StorageMeter, type Storage } from "@/admin/media";
import { Loading, Notice, Panel, Title, useAdmin, when } from "@/admin/ui";
// The admin (docs/WEBSITE-1.0-PLAN.md §10), signed in through the church's Accounts. The screens
// (template and style, pages, messages, events, publish) come next.
export default async function Admin() {
const me = await loadMe();
if (!me) redirect(signInHref("/admin"));
type Overview = {
pending: number;
lastPublished: { number: number; at: string } | null;
storage: Storage;
colourNotes: string[];
checklist: { key: string; label: string; done: boolean; href: string | null }[];
};
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */
export default function Dashboard() {
const { data, error } = useAdmin<Overview>("/overview");
if (!data) return <Loading error={error} />;
return (
<main className="mx-auto max-w-xl px-4 py-16">
<h1 className="text-2xl font-semibold">Website admin</h1>
<p className="mt-2 text-gray-600">
Signed in as {me.user.name} ({me.user.email}), {ROLE_NAMES[me.user.role]}.
</p>
<form method="post" action="/api/auth/signout" className="mt-6">
<button type="submit" className="rounded border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
Sign out
</button>
</form>
</main>
<>
<Title sub={data.lastPublished ? `Last published ${when(data.lastPublished.at)} (version ${data.lastPublished.number}).` : "Your site shows Coming soon until you publish it."}>Dashboard</Title>
<div className="grid gap-6 lg:grid-cols-2">
<Panel title="Getting your site ready">
<ol className="space-y-3">
{data.checklist.map((c) => (
<li key={c.key} className="flex items-start gap-3">
<span aria-hidden="true" className={c.done ? "text-green-700" : "text-gray-400"}>{c.done ? "✓" : "○"}</span>
<span className={c.done ? "text-gray-500 line-through" : ""}>{c.href ? <Link href={c.href} className="underline-offset-4 hover:underline">{c.label}</Link> : c.label}</span>
<span className="sr-only">{c.done ? "(done)" : "(to do)"}</span>
</li>
))}
</ol>
</Panel>
<div className="space-y-6">
<Panel title="Waiting to be published">
{data.pending ? (
<p>{data.pending} {data.pending === 1 ? "change" : "changes"}. <Link href="/admin/publish" className="font-semibold text-brand-text underline-offset-4 hover:underline">Review and publish</Link></p>
) : <p className="text-gray-600">Nothing: the site shows everything you&apos;ve done.</p>}
</Panel>
<Panel title="Storage"><StorageMeter s={data.storage} /></Panel>
{data.colourNotes.length > 0 && (
<Notice tone="info"><p className="font-semibold">About your colours</p><ul className="mt-1 list-disc pl-5">{data.colourNotes.map((n) => <li key={n}>{n}</li>)}</ul></Notice>
)}
</div>
</div>
</>
);
}
@@ -0,0 +1,131 @@
"use client";
/**
* One page (§6): its title, address, menu and search engine details, then its content. The home
* page has one of each homepage section (their layouts are set under Template and style); every
* other page is built from blocks, which can be added, moved and removed.
*/
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { api } from "@/admin/api";
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown> };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; sections: Section[] };
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
const LISTS: Record<string, string> = {
ministries: "This page lists your ministries (under Ministries); blocks you add show after them.",
leadership: "This page lists your team (under Leadership); blocks you add show after them.",
events: "This page lists your events; blocks you add show after them.",
messages: "This page lists your messages; blocks you add show after them.",
contact: "This page shows your church's contact details and service times from your church profile.",
};
function SectionEditor({ title, fields, initial, onSave, extra }: { title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; onSave: (data: Record<string, unknown>) => Promise<unknown>; extra?: React.ReactNode }) {
const [value, setValue] = useState(initial);
const [open, setOpen] = useState(false);
const { busy, message, fields: errors, run } = useAction();
return (
<Panel>
<div className="flex items-center justify-between gap-3">
<h3 className="font-semibold">{title}</h3>
<div className="flex gap-2">{extra}<Btn onClick={() => setOpen(!open)} aria-expanded={open}>{open ? "Close" : "Edit"}</Btn></div>
</div>
{open && (
<div className="mt-4 space-y-4">
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
)}
</Panel>
);
}
export default function EditPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
const details = useAction();
const blocks = useAction();
const [form, setForm] = useState<Partial<PageData> | null>(null);
if (!page) return <Loading error={error} />;
const f = { ...page, ...form };
const saveDetails = () => details.run(async () => {
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId } });
setData(p);
setForm(null);
}, "Saved as a draft.");
const blockCall = (path: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${path}`, { method, body })));
return (
<>
<Title sub={page.kind === "home" ? "Your home page" : `Your site/${page.slug}`}
actions={page.kind !== "home" && <Btn kind="danger" onClick={() => details.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); })}>Remove page</Btn>}>
{page.title}
</Title>
<div className="space-y-6">
<Panel title="Page details">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Title" error={details.fields.title}><input className={inputClass} value={f.title ?? ""} maxLength={120} onChange={(e) => setForm({ ...form, title: e.target.value })} /></Field>
{page.kind !== "home" && <Field label="Address" hint={`Your site/${f.slug}`} error={details.fields.slug}><input className={inputClass} value={f.slug ?? ""} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></Field>}
{page.kind !== "home" && <Field label="Name in the menu" hint="Leave empty to use the title."><input className={inputClass} value={f.navLabel ?? ""} maxLength={40} onChange={(e) => setForm({ ...form, navLabel: e.target.value || null })} /></Field>}
{page.kind !== "home" && <label className="flex items-center gap-2 self-end pb-2 text-sm"><input type="checkbox" checked={!!f.inNav} onChange={(e) => setForm({ ...form, inNav: e.target.checked })} />Show in the menu</label>}
<Field label="Title in search results" hint={`${(f.seoTitle ?? f.title ?? "").length} of 60 characters`} error={details.fields.seoTitle}><input className={inputClass} value={f.seoTitle ?? ""} maxLength={70} onChange={(e) => setForm({ ...form, seoTitle: e.target.value || null })} placeholder={f.title} /></Field>
<Field label="Description in search results" hint={`${(f.description ?? "").length} of 155 characters${f.description ? "" : ": add one, so search engines show what this page is about"}`} error={details.fields.description}>
<textarea className={inputClass} rows={2} value={f.description ?? ""} maxLength={300} onChange={(e) => setForm({ ...form, description: e.target.value || null })} />
</Field>
<div className="sm:col-span-2"><ImagePicker label="Image when shared (optional)" value={f.imageId ?? null} onChange={(imageId) => setForm({ ...form, imageId })} /></div>
</div>
{/* A Google-style preview of the search result (ROADMAP-v3 §11). */}
<div className="mt-4 rounded border border-gray-200 p-3" aria-label="How it may look in search results">
<p className="truncate text-lg text-blue-800">{f.seoTitle || f.title}</p>
<p className="line-clamp-2 text-sm text-gray-600">{f.description || "No description yet."}</p>
</div>
<div className="mt-4 flex items-center gap-3">
<Btn kind="primary" busy={details.busy} onClick={saveDetails}>Save details</Btn>
{details.message && <Notice tone={details.message.tone}>{details.message.text}</Notice>}
</div>
</Panel>
{page.kind === "home" ? (
<>
<p className="text-sm text-gray-600">Each section&apos;s layout, order and whether it shows are under Template and style.</p>
{HOME_ORDER.map((type) => {
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type]!;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data } }))} />;
})}
</>
) : (
<>
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
{page.sections.map((s, i) => {
const spec = BLOCK_FIELDS[s.type];
if (!spec) return null;
return (
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data } }))}
extra={<>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down">↓</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}`, "PUT", { hidden: !s.hidden })}>{s.hidden ? "Show" : "Hide"}</Btn>
<Btn kind="danger" onClick={() => blockCall(`/blocks/${s.id}`, "DELETE")}>Remove</Btn>
</>} />
);
})}
<Panel title="Add a block">
<div className="flex flex-wrap gap-2">
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => <Btn key={type} busy={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}>{spec.name}</Btn>)}
</div>
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>}
</Panel>
</>
)}
</div>
</>
);
}
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type PageRow = { id: string; kind: string; slug: string; title: string; inNav: boolean; path: string };
const KINDS: Record<string, string> = { home: "Home", visit: "Plan your visit", about: "About", leadership: "Leadership", ministries: "Ministries", events: "Events", messages: "Messages", give: "Give", contact: "Contact", terms: "Terms", safeguarding: "Safeguarding", custom: "Your own page" };
/** Pages (§6): the fixed ones and the church's own, built from blocks. */
export default function Pages() {
const { data, error } = useAdmin<PageRow[]>("/pages");
const router = useRouter();
const [title, setTitle] = useState("");
const [slug, setSlug] = useState("");
const { busy, message, fields, run } = useAction();
if (!data) return <Loading error={error} />;
const create = () => run(async () => {
const p = await api<{ id: string }>("/pages", { body: { title, slug } });
router.push(`/admin/pages/${p.id}`);
});
return (
<>
<Title sub="Each page is a draft until you publish.">Pages</Title>
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<Panel>
<ul className="divide-y divide-gray-200">
{data.map((p) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-3">
<div>
<Link href={`/admin/pages/${p.id}`} className="font-medium underline-offset-4 hover:underline">{p.title}</Link>
<p className="text-xs text-gray-500">{KINDS[p.kind] ?? p.kind} · {p.path}{!p.inNav && p.kind !== "home" && " · not in the menu"}</p>
</div>
<Link href={`/admin/pages/${p.id}`} className="text-sm font-semibold text-brand-text">Edit</Link>
</li>
))}
</ul>
</Panel>
<Panel title="Add a page">
<div className="space-y-3">
<Field label="Title" error={fields.title}><input className={inputClass} value={title} maxLength={120} onChange={(e) => { setTitle(e.target.value); setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")); }} /></Field>
<Field label="Address" hint={`Your site/${slug || "…"}`} error={fields.slug}><input className={inputClass} value={slug} maxLength={80} onChange={(e) => setSlug(e.target.value)} /></Field>
<Btn kind="primary" busy={busy} onClick={create} disabled={!title || !slug}>Add page</Btn>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,112 @@
"use client";
/**
* Publish and history (WEBSITE-1.0-PLAN §4): every pending change (what, who, when), Discard for
* any one, one Publish for the whole site; links to share the preview; every published version,
* any of which can be restored into the working copy.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Change = { key: string; kind: "added" | "changed" | "removed"; what: string; label: string; by: string | null; at: string | null };
type Version = { number: number; publishedAt: string; by: string | null; note: string | null };
type Link = { id: string; createdAt: string; expiresAt: string; by: string | null; active: boolean };
const WHAT: Record<string, string> = { design: "Template and style", page: "Page", ministry: "Ministry", leader: "Team" };
const KIND: Record<string, string> = { added: "Added", changed: "Changed", removed: "Removed" };
export default function Publish() {
const me = useAdmin<{ user: { role: string } }>("/me");
const pending = useAdmin<Change[]>("/changes");
const versions = useAdmin<Version[]>("/versions");
const editor = !!me.data && canEdit(me.data.user.role);
const links = useAdmin<Link[]>(editor ? "/preview-links" : null);
const [note, setNote] = useState("");
const [newLink, setNewLink] = useState<string | null>(null);
const { busy, message, run } = useAction();
if (!pending.data || !versions.data) return <Loading error={pending.error ?? versions.error} />;
const first = versions.data.length === 0;
const reloadAll = async () => { await Promise.all([pending.reload(), versions.reload(), links.reload()]); };
return (
<>
<Title sub={first ? "Until you publish, visitors see Coming soon." : "Visitors see the last version published."}
actions={<>
{/* 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 bg-white px-4 py-2 text-sm font-semibold hover:bg-gray-50">Preview the whole site</a>
</>}>
Publish and history
</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title={pending.data.length ? `${pending.data.length} ${pending.data.length === 1 ? "change" : "changes"} not published` : "Nothing waiting to be published"}>
{pending.data.length > 0 && (
<ul className="mb-4 divide-y divide-gray-200">
{pending.data.map((c) => (
<li key={c.key} className="flex flex-wrap items-center justify-between gap-3 py-2">
<div>
<p><span className="font-medium">{KIND[c.kind]}:</span> {WHAT[c.what]} {c.what !== "design" && <>“{c.label}”</>}</p>
<p className="text-xs text-gray-500">{[c.by, when(c.at)].filter(Boolean).join(", ")}</p>
</div>
{editor && <Btn busy={busy} onClick={() => run(async () => { await api("/discard", { body: { key: c.key } }); await reloadAll(); }, "Discarded: back to the published version.")}>Discard</Btn>}
</li>
))}
</ul>
)}
{editor ? (
(pending.data.length > 0 || first) && (
<div className="space-y-3">
<Field label="A note for the history (optional)"><input className={inputClass} value={note} maxLength={500} onChange={(e) => setNote(e.target.value)} placeholder="E.g. Christmas service times" /></Field>
<Btn kind="primary" busy={busy} onClick={() => run(async () => {
const r = await api<{ number: number }>("/publish", { body: { note } });
// Visitors get it at once, not after the 30-second cache.
await fetch("/revalidate", { method: "POST" }).catch(() => {});
setNote("");
await reloadAll();
return r;
}, first ? "Published: your site is live." : "Published: visitors see it now.")}>{first ? "Publish your site" : "Publish all changes"}</Btn>
</div>
)
) : <p className="text-sm text-gray-600">An editor publishes your changes.</p>}
</Panel>
{editor && (
<Panel title="Share the preview">
<p className="mb-3 text-sm text-gray-600">A link for someone without an account (your pastor, say) to see the whole site as it would look published. It works for 7 days, or until you stop it, and can&apos;t change anything.</p>
<Btn busy={busy} onClick={() => run(async () => { const l = await api<{ url: string }>("/preview-links", { body: {} }); setNewLink(l.url); await links.reload(); })}>Make a preview link</Btn>
{newLink && (
<div className="mt-3"><Notice tone="success">Copy this link now (it isn&apos;t shown again): <code className="break-all font-mono">{newLink}</code></Notice></div>
)}
{links.data && links.data.length > 0 && (
<ul className="mt-4 divide-y divide-gray-200 text-sm">
{links.data.map((l) => (
<li key={l.id} className="flex items-center justify-between gap-3 py-2">
<span>Made {when(l.createdAt)}{l.by && ` by ${l.by}`} · {l.active ? `works until ${when(l.expiresAt)}` : "stopped"}</span>
{l.active && <Btn kind="danger" onClick={() => run(async () => { await api(`/preview-links/${l.id}`, { method: "DELETE" }); await links.reload(); }, "The link stopped working.")}>Stop it</Btn>}
</li>
))}
</ul>
)}
</Panel>
)}
<Panel title="History">
{versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : (
<ul className="divide-y divide-gray-200">
{versions.data.map((v, i) => (
<li key={v.number} className="flex flex-wrap items-center justify-between gap-3 py-2">
<div>
<p className="font-medium">Version {v.number}{i === 0 && " (live)"}{v.note && <span className="font-normal text-gray-600"> · {v.note}</span>}</p>
<p className="text-xs text-gray-500">{when(v.publishedAt)}{v.by && `, ${v.by}`}</p>
</div>
{editor && i > 0 && <Btn onClick={() => run(async () => { await api(`/versions/${v.number}/restore`, { body: {} }); await reloadAll(); }, `Version ${v.number} is back in your drafts: preview it, then publish.`)}>Restore</Btn>}
</li>
))}
</ul>
)}
</Panel>
</div>
</>
);
}
@@ -0,0 +1,124 @@
"use client";
/**
* Template and style (WEBSITE-1.0-PLAN §3): the template, each homepage section's layout
* (recommended first), the homepage order, and the style settings. Fonts and corners are the
* church's brand style, shared with its other sites, so they're set in its church profile.
*/
import { api } from "@/admin/api";
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> };
type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
const TEMPLATES = [
{ id: "heritage", name: "Heritage", text: "Traditional and dignified: centred, framed images, serif headings." },
{ id: "bold", name: "Bold", text: "Modern and energetic: full-screen photos, big headlines, bands." },
{ id: "community", name: "Community", text: "Warm and friendly: cards, rounded shapes, faces up front." },
{ id: "clean", name: "Clean", text: "Minimal and calm: lots of space, good without photos." },
];
const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes: "Service times", welcome: "Welcome", ministries: "Ministries", team: "Team", events: "Upcoming events", latestMessage: "Latest message", invitation: "Invitation" };
const VARIANT_NAMES: Record<string, string> = {
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
calendar: "Calendar strip", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
};
const ALL_VARIANTS: Record<string, string[]> = {
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
team: ["faces", "list", "featured"], events: ["cards", "list", "calendar"], latestMessage: ["video", "card", "compact"], invitation: ["banner", "centred", "image"],
};
const HEADER_NAMES: Record<string, string> = {
centred: "Centred", "centred-top-bar": "Centred, with a top bar", transparent: "Over the photo, solid when scrolling", solid: "Solid",
"logo-left-button": "Logo left, with a Plan your visit button", "logo-left-tinted": "Logo left, on a tinted bar", small: "Small", "small-menu": "Small, menu on every screen",
};
const STYLE = [
{ key: "sectionColour", label: "Section colour", options: { light: "Light", tinted: "Tinted (your colour, softly)", mixed: "Mixed, with dark bands" } },
{ key: "spacing", label: "Spacing", options: { airy: "Airy", compact: "Compact" } },
{ key: "buttons", label: "Buttons", options: { solid: "Solid", outline: "Outline", pill: "Pill" } },
{ key: "images", label: "Photos", options: { natural: "Natural", mono: "Black and white", duotone: "Duotone in your colour" } },
];
export default function TemplatePage() {
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
const { busy, message, run } = useAction();
if (!data) return <Loading error={error} />;
const { design, options } = data;
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
const r = await api<{ design: Design; moved: { what: string }[] }>("/design", { method: "PUT", body: patch });
setData({ ...data, design: r.design });
return r;
}, done);
const move = (i: number, d: -1 | 1) => {
const home = [...design.home];
const j = i + d;
if (j < 0 || j >= home.length) return;
[home[i], home[j]] = [home[j]!, home[i]!];
save({ home });
};
return (
<>
<Title sub="Changes here are drafts: preview them, then publish.">Template and style</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title="Template">
<div className="grid gap-3 sm:grid-cols-2">
{TEMPLATES.map((t) => (
<button key={t.id} type="button" disabled={busy} onClick={() => t.id !== design.template && save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}
aria-pressed={t.id === design.template}
className={cx("rounded-lg border-2 p-4 text-left", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200 hover:border-gray-400")}>
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span>
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
</button>
))}
</div>
</Panel>
<Panel title="Home page: sections and layouts">
<p className="mb-4 text-sm text-gray-600">Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best.</p>
<ul className="divide-y divide-gray-200">
{design.home.map((e, i) => {
const recommended = options.variants[design.template]?.[e.section] ?? [];
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
return (
<li key={e.section} className="flex flex-wrap items-center gap-3 py-3">
<span className="w-40 font-medium">{SECTIONS[e.section]}</span>
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-56`} value={design.variants[e.section]} disabled={busy}
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}>
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
</select>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={!e.hidden} disabled={busy} onChange={(ev) => save({ home: design.home.map((x) => (x.section === e.section ? { ...x, hidden: !ev.target.checked } : x)) })} />
Show
</label>
<span className="ml-auto flex gap-1">
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${SECTIONS[e.section]} up`}>↑</Btn>
<Btn onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`}>↓</Btn>
</span>
</li>
);
})}
</ul>
</Panel>
<Panel title="Style">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Header">
<select className={inputClass} value={design.style.header} disabled={busy} onChange={(e) => save({ style: { header: e.target.value } })}>
{(options.headers[design.template] ?? []).map((h) => <option key={h} value={h}>{HEADER_NAMES[h] ?? h}</option>)}
</select>
</Field>
{STYLE.map((s) => (
<Field key={s.key} label={s.label}>
<select className={inputClass} value={design.style[s.key]} disabled={busy} onChange={(e) => save({ style: { [s.key]: e.target.value } })}>
{Object.entries(s.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</Field>
))}
</div>
<p className="mt-4 text-sm text-gray-600">Fonts and corners are your church&apos;s brand style, shared with your Events and sign-in pages: change them in your church profile.</p>
</Panel>
</div>
</>
);
}
+15 -2
View File
@@ -1,25 +1,35 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { loadContent } from "@/site/load";
import { PreviewBar } from "@/site/PreviewBar";
export async function generateMetadata(): Promise<Metadata> {
const c = await loadContent();
const name = c.church?.name ?? "Church Website";
return { title: { default: name, template: `%s · ${name}` }, icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined };
return {
title: { default: name, template: `%s · ${name}` },
icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined,
// A preview is never indexed (§4).
...(c.mode === "published" && c.preview ? { robots: { index: false, follow: false } } : {}),
};
}
/**
* Every page: the church's fonts and corners (shared brand style), the template and the style
* settings as attributes (globals.css), and its colours, made safe by the backend, as variables.
* While previewing, the site's pages get the preview bar above them.
*/
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const c = await loadContent();
const path = (await headers()).get("x-ccw-path") ?? "/";
const p = c.palette;
const template = c.mode === "published" ? c.snapshot.design.template : c.template;
const s = c.mode === "published" ? c.snapshot.design.style : null;
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
const bar = c.mode === "published" && c.preview && !path.startsWith("/admin") && !path.startsWith("/preview") ? c.preview : null;
return (
<html
lang="en-ZA"
@@ -33,7 +43,10 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<head>
<style>{vars.replace(/[<>]/g, "")}</style>
</head>
<body>{children}</body>
<body>
{bar && <PreviewBar preview={bar} />}
{children}
</body>
</html>
);
}
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
/**
* A shared preview link (§4): keeps its token in a cookie for the rest of the visit, so every page
* shows the working copy. The backend checks the token (7 days, until revoked) on every page.
*/
export async function GET(request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
const res = NextResponse.redirect(new URL("/", request.url), 303);
if (/^[A-Za-z0-9_-]{20,100}$/.test(token)) {
res.cookies.set("ccw_preview", token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 7 * 86400 });
}
res.headers.set("X-Robots-Tag", "noindex, nofollow");
return res;
}
@@ -0,0 +1,10 @@
import { NextResponse, type NextRequest } from "next/server";
/** Leaves the preview: an admin goes back to editing, someone with a shared link to the live site. */
export function GET(request: NextRequest) {
const admin = request.cookies.get("ccw_preview")?.value === "admin";
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : "/admin") : "/";
const res = NextResponse.redirect(new URL(to, request.url), 303);
res.cookies.delete("ccw_preview");
return res;
}
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { PreviewBar } from "@/site/PreviewBar";
import { loadContent } from "@/site/load";
export const metadata: Metadata = { title: "Preview", robots: { index: false, follow: false } };
const WIDTHS: Record<string, number> = { phone: 390, tablet: 820 };
/**
* The preview at phone or tablet width (§4): the site in a frame of that width, so its layout is
* exactly what a phone shows. The bar stays outside the frame.
*/
export default async function Frame({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
const q = await searchParams;
const size = q.size === "tablet" ? "tablet" : "phone";
const c = await loadContent();
return (
<div className="min-h-screen bg-gray-200">
{c.mode === "published" && c.preview && <PreviewBar preview={c.preview} size={size} />}
<div className="flex justify-center py-6">
<iframe src="/" title={`The site at ${size} width`} style={{ width: WIDTHS[size], height: "calc(100vh - 7rem)" }} className="rounded-lg border border-gray-300 bg-white shadow-xl" />
</div>
</div>
);
}
@@ -0,0 +1,12 @@
import { NextResponse, type NextRequest } from "next/server";
/**
* Preview (WEBSITE-1.0-PLAN §4): a signed-in admin sees the working copy on the site's own
* addresses, fully clickable. The cookie only asks for it; the backend checks the admin's session
* on every page (site/preview), so it shows nothing to anyone else.
*/
export function GET(request: NextRequest) {
const res = NextResponse.redirect(new URL("/", request.url), 303);
res.cookies.set("ccw_preview", "admin", { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/" });
return res;
}
@@ -0,0 +1,17 @@
import { revalidateTag } from "next/cache";
import { NextResponse, type NextRequest } from "next/server";
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
/**
* Publish (WEBSITE-1.0-PLAN §1, §4) refreshes the public pages at once: the admin calls this right
* after publishing, and the next visitor gets the new version (no stale copy). Only a signed-in
* admin can ask.
*/
export async function POST(request: NextRequest) {
const session = request.cookies.get("ccw_session")?.value;
const me = session ? await fetch(`${api}/api/auth/me`, { headers: { Cookie: `ccw_session=${encodeURIComponent(session)}` }, cache: "no-store" }).catch(() => null) : null;
if (!me?.ok) return NextResponse.json({ error: { code: "SIGNED_OUT", message: "Please sign in." } }, { status: 401 });
revalidateTag("site-content", { expire: 0 });
return NextResponse.json({ ok: true });
}
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
/**
* The address a page was asked for, for the layouts: the admin's, so signing in comes back to
* that exact page (ROADMAP-v3 §3, "Sign-in always returns you to where you came from"), and the
* root layout's, which shows the preview bar on the site's pages only.
*/
export function proxy(request: NextRequest) {
const headers = new Headers(request.headers);
headers.set("x-ccw-path", `${request.nextUrl.pathname}${request.nextUrl.search}`);
return NextResponse.next({ request: { headers } });
}
// Never Next's own paths (/_next: its files and the development connection).
export const config = { matcher: ["/((?!api|_next|favicon.ico).*)"] };
@@ -0,0 +1,58 @@
"use client";
/**
* The preview bar (WEBSITE-1.0-PLAN §4): above the page (so the page is laid out exactly as it
* will be), with phone / tablet / desktop width, Back to editing, and Publish for an editor. Inside
* the width frame it hides itself: the frame page has its own.
*/
import { useEffect, useState } from "react";
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean }; size?: "phone" | "tablet" | "desktop" }) {
const [inFrame, setInFrame] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Only the browser knows whether this page is inside the width frame.
// eslint-disable-next-line react-hooks/set-state-in-effect
setInFrame(window.self !== window.top);
}, []);
if (inFrame) return null;
const publish = async () => {
setBusy(true);
setError(null);
const res = await fetch("/api/v1/admin/publish", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
if (res.ok) {
await fetch("/revalidate", { method: "POST" }).catch(() => {});
// A full page load: the route clears the preview cookie.
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
window.location.href = "/preview/exit?published=1";
}
else {
setError(((await res.json().catch(() => null)) as { error?: { message?: string } } | null)?.error?.message ?? "Publishing didn't work.");
setBusy(false);
}
};
const width = (s: string, label: string, href: string) => (
<a href={href} aria-current={size === s ? "true" : undefined} className={`rounded px-2 py-1 ${size === s ? "bg-white text-gray-900" : "hover:bg-white/10"}`}>{label}</a>
);
return (
<div className="bg-gray-900 font-sans text-sm text-white" role="region" aria-label="Preview">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-2">
<p><strong>Preview</strong> · {preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
<div className="flex items-center gap-1" aria-label="Width">
{width("phone", "Phone", "/preview/frame?size=phone")}
{width("tablet", "Tablet", "/preview/frame?size=tablet")}
{width("desktop", "Desktop", "/")}
</div>
<div className="flex items-center gap-3">
{error && <span role="alert" className="text-amber-300">{error}</span>}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that clears the preview cookie: a full page load, not a client navigation */}
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
{preview.canPublish && (
<button type="button" onClick={publish} disabled={busy} className="rounded bg-white px-3 py-1.5 font-semibold text-gray-900 disabled:opacity-60">{busy ? "Publishing…" : "Publish"}</button>
)}
</div>
</div>
</div>
);
}
+25 -5
View File
@@ -1,3 +1,4 @@
import { cookies } from "next/headers";
import { cache } from "react";
import type { Image, Published, SiteContent, Template } from "./types";
@@ -13,14 +14,33 @@ const FALLBACK: SiteContent = {
};
/**
* The site as visitors see it: one fetch per request (React `cache`), kept by Next for 30 seconds,
* so Publish shows within half a minute. While the backend can't answer: Coming soon, never an
* error page.
* The site as visitors see it: one fetch per request (React `cache`), kept by Next for
* WEBSITE_CONTENT_CACHE_SECONDS (30; tag `site-content`, which Publish clears at once through
* app/revalidate). While the backend can't answer: Coming soon, never an error page.
*/
export const loadContent = cache(async (): Promise<SiteContent> => {
// Previewing (§4): the working copy, if the backend agrees this is an admin or a live share link.
const jar = await cookies();
const preview = jar.get("ccw_preview")?.value;
if (preview) {
try {
const session = jar.get("ccw_session")?.value;
const res = await fetch(`${api}/api/v1/site/preview`, {
cache: "no-store",
headers: {
...(session ? { Cookie: `ccw_session=${encodeURIComponent(session)}` } : {}),
...(preview !== "admin" ? { "x-preview-token": preview } : {}),
},
});
if (res.ok) return (await res.json()) as SiteContent;
} catch {
// Falls back to the live site.
}
}
try {
// In development (and the e2e run) always fresh, so a Publish shows at once.
const res = await fetch(`${api}/api/v1/site/content`, process.env.NODE_ENV === "production" ? { next: { revalidate: 30 } } : { cache: "no-store" });
// Not kept in development, or when set to 0 (the e2e run changes content behind Next's back).
const seconds = process.env.NODE_ENV === "production" ? Number(process.env.WEBSITE_CONTENT_CACHE_SECONDS ?? 30) : 0;
const res = await fetch(`${api}/api/v1/site/content`, seconds > 0 ? { next: { revalidate: seconds, tags: ["site-content"] } } : { cache: "no-store" });
if (res.ok) return (await res.json()) as SiteContent;
} catch {
// Starting or down.
+2
View File
@@ -78,6 +78,8 @@ export type Published = Common & {
transparentHeader: Record<string, boolean>;
messages: SiteMessage[];
events: SiteEvent[];
/** Only when previewing the working copy (§4). */
preview?: { by: "admin" | "link"; canPublish: boolean };
};
export type SiteContent = ComingSoon | Published;