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:
@@ -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'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" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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'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'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'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'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's brand style, shared with your Events and sign-in pages: change them in your church profile.</p>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user