Accounts 1.8.0, Website 1.1.0: admins redesigned as Cross Events' dashboard and settings

- Website: an icon sidebar in groups (Your site, Content, Go live, Team), a
  dashboard with cards and a tile per part of the admin, steps to the first
  publish across the top of every admin page, and a live preview beside the
  page editor and Template and style (computer or phone width, folds away,
  reloads on save). A framed request (Sec-Fetch-Dest: iframe) with an admin
  session reads the drafts, so no preview cookie is set. /preview/start
  takes ?to=. The page editor has Content and Page details tabs.
- Accounts: /admin is an overview (cards, "Needs you", a tile per section);
  People moved to /admin/people; the sidebar shows the part you're in,
  grouped, with a count on Deletion requests; People redesigned, with a
  confirm before Deactivate; Email and WhatsApp split into two cards.
- Both: darker grey labels for contrast; lucide-react in the Website.
- e2e: the live preview shows drafts while the site stays live; axe on the
  page editor.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 19:57:22 +02:00
co-authored by Claude Opus 5.5
parent e6c91c3705
commit dcc22a5c16
42 changed files with 1278 additions and 353 deletions
+11
View File
@@ -2,6 +2,17 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## accounts@1.8.0 + website@1.1.0 - 2026-11-26
The admins of both, redesigned as Cross Events' admin dashboard and settings. Details in each app's
CHANGELOG.md. No migrations, no backend changes.
- **Accounts 1.8.0:** `/admin` is an overview (cards, "Needs you", a tile per section); People
moved to `/admin/people`; the sidebar shows the part you're in, grouped; People redesigned.
- **Website 1.1.0:** an icon sidebar in groups, a dashboard, steps to the first publish across the
top, and a live preview beside the page editor and Template and style (drafts in a frame, no
preview cookie).
## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26 ## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations. Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
+19
View File
@@ -1,5 +1,24 @@
# Changelog — Accounts # Changelog — Accounts
## [1.8.0] - 2026-11-26
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
dashboard and settings.
### Changed
- **`/admin` is an overview:** four cards (people with an account, deletion requests waiting,
sites that sign in here, last backup), a "Needs you" list with buttons to act, and a tile with a
line about every section. **People moved to `/admin/people`.**
- **The sidebar shows the part you're in** (your account or admin, with a link to the other), and
admin's sections are grouped: People, Church, Signing in, System. Deletion requests shows how many
are waiting. The phone menu shows both parts. Every page title has its section's icon.
- **People:** a search box, a row per person with initials, admin and status badges, two-step
sign-in and last sign-in; the person's card stays in view while scrolling. Deactivating someone
asks to confirm first.
- **Email and WhatsApp** are two cards, each with its own Save.
- Group labels are a darker grey (WCAG AA contrast).
## [1.7.1] - 2026-11-26 ## [1.7.1] - 2026-11-26
No migrations, no new settings. No migrations, no new settings.
+7
View File
@@ -3,6 +3,13 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged). WHATS-NEW.md; a section shows once its version is tagged).
## 1.8.0
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
needs you (like deletion requests waiting), and a tile for every setting. The menu down the side
is grouped and shows only the part you're in. People has moved to Admin → **People**, with a
search box and a clearer list; deactivating someone now asks you to confirm.
## 1.7.1 ## 1.7.1
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed - **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.7.1", "version": "1.8.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true, "private": true,
"type": "module", "type": "module",
+4
View File
@@ -102,6 +102,10 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`)); await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click(); await page.getByRole("button", { name: "Turn on" }).click();
await page.getByRole("button", { name: "I've saved them" }).click(); await page.getByRole("button", { name: "I've saved them" }).click();
// 1.8.0: /admin is the overview, with a tile for every section; People is one.
await expect(page.getByRole("heading", { name: "Admin", level: 1 })).toBeVisible();
await expect(page.getByText("People with an account")).toBeVisible();
await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "People", exact: true }).click();
await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible(); await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible();
await expect(page.getByText("thandi@hope.test")).toBeVisible(); await expect(page.getByText("thandi@hope.test")).toBeVisible();
// 1.3.0: every admin section has its own address, down the side; Backups is one. // 1.3.0: every admin section has its own address, down the side; Backups is one.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.7.1", "version": "1.8.0",
"private": true, "private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": { "scripts": {
@@ -6,7 +6,7 @@ import QRCode from "qrcode";
import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react"; import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider"; import { useBranding } from "@/components/BrandingProvider";
import { AppShell, PageTitle, ShellLoading } from "@/components/AppShell"; import { ACCOUNT_NAV, AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { Card, Heading } from "@/components/Panel"; import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api"; import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks"; import { useExternalEffect } from "@/lib/hooks";
@@ -62,7 +62,7 @@ export function Account({ section = "overview" }: { section?: AccountSection })
const first = me.name.split(" ")[0] || me.name; const first = me.name.split(" ")[0] || me.name;
return ( return (
<AppShell me={me} active={s.path}> <AppShell me={me} active={s.path}>
<PageTitle sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle> <PageTitle icon={section === "overview" ? undefined : ACCOUNT_NAV.find((n) => n.href === s.path)?.icon} sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>} {msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview me={me} />} {section === "overview" && <Overview me={me} />}
{section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>} {section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>}
+180 -34
View File
@@ -2,9 +2,12 @@
import Link from "next/link"; import Link from "next/link";
import React, { useCallback, useState } from "react"; import React, { useCallback, useState } from "react";
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react"; import {
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
} from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell"; import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText"; import { NoticeText } from "@/components/NoticeText";
import { Card, Heading } from "@/components/Panel"; import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api"; import { call, selfSignIn } from "@/lib/api";
@@ -26,6 +29,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
const [me, setMe] = useState<ShellUser | null>(null); const [me, setMe] = useState<ShellUser | null>(null);
const [allowed, setAllowed] = useState<boolean | null>(null); const [allowed, setAllowed] = useState<boolean | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null); const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const [waiting, setWaiting] = useState(0);
useExternalEffect(() => { useExternalEffect(() => {
let alive = true; let alive = true;
@@ -35,11 +39,15 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa")); if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa"));
if (who.ok) setMe(who.data); if (who.ok) setMe(who.data);
setAllowed(r.ok); setAllowed(r.ok);
// The count beside Deletion requests.
if (r.ok) void call<{ items: Deletion[] }>("GET", "/admin/deletions").then((d) => { if (alive && d.ok) setWaiting(d.data.items.filter((x) => x.status === "waiting_approval").length); });
}); });
return () => { alive = false; }; return () => { alive = false; };
}, [s.path]); }, [s.path]);
const flash: Flash = (tone, text) => setMsg({ tone, text }); const flash: Flash = (tone, text) => setMsg({ tone, text });
const icon = ADMIN_NAV.find((n) => n.href === s.path)?.icon;
const badges = { "/admin/deletions": waiting };
if (allowed === null || !me) return <ShellLoading />; if (allowed === null || !me) return <ShellLoading />;
if (!allowed) { if (!allowed) {
return ( return (
@@ -50,16 +58,20 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
} }
return ( return (
<AppShell me={me} active={s.path}> <AppShell me={me} active={s.path} badges={badges}>
<PageTitle sub={s.sub}>{s.title}</PageTitle> <PageTitle icon={section === "overview" ? undefined : icon} sub={section === "overview" ? `Welcome back, ${me.name.split(" ")[0] || me.name}. ${s.sub}` : s.sub}>{s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>} {msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview />}
{section === "people" && <People flash={flash} />} {section === "people" && <People flash={flash} />}
<div className="max-w-3xl"> <div className="max-w-3xl space-y-6">
{section === "deletions" && <Deletions flash={flash} />} {section === "deletions" && <Deletions flash={flash} onChange={setWaiting} />}
{section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>} {section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>}
{section === "linked" && <Linked flash={flash} />} {section === "linked" && <Linked flash={flash} />}
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />} {section === "signin" && <Settings flash={flash} title="Signing in" icon={<LogIn className="h-4 w-4" />} sub="For everyone with an account at the church." keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />} {section === "messages" && <>
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
</>}
{section === "notice" && <NoticeTab flash={flash} />} {section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />} {section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />} {section === "jobs" && <Jobs flash={flash} />}
@@ -70,11 +82,118 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
); );
} }
// ─── Overview (1.8.0, as Cross Events' admin dashboard) ─────────────────────
type Linked = { hubConnected: boolean; items: { installId: string; name: string; listed: boolean; signsInHere: boolean }[] };
type OverviewData = { people: number | null; deletions: number | null; linked: Linked | null; licence: { connected: boolean; state: string } | null; backups: BackupList | null };
const TILE: Record<string, string> = Object.fromEntries(Object.values(ADMIN_SECTIONS).map((x) => [x.path, x.tile]));
function Stat({ icon, label, value, detail, href, warn }: { icon: React.ReactNode; label: string; value: React.ReactNode; detail?: React.ReactNode; href: string; warn?: boolean }) {
return (
<Link href={href} className="group rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<div className="flex items-center gap-3">
<span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${warn ? "bg-amber-50 text-amber-700" : "bg-brand/10 text-brand"}`} aria-hidden>{icon}</span>
<span className="min-w-0">
<span className="block text-xs text-gray-500">{label}</span>
<span className="block truncate text-xl font-semibold text-gray-900">{value}</span>
</span>
</div>
{detail && <p className="mt-2 text-xs text-gray-500">{detail}</p>}
</Link>
);
}
function Overview() {
const [d, setD] = useState<OverviewData | null>(null);
useExternalEffect(() => {
let alive = true;
Promise.all([
call<{ total: number }>("GET", "/admin/people?q="), call<{ items: Deletion[] }>("GET", "/admin/deletions"), call<Linked>("GET", "/admin/linked-products"),
call<{ connected: boolean; state: string }>("GET", "/admin/licence"), call<BackupList>("GET", "/admin/backups"),
]).then(([people, dels, linked, licence, backups]) => {
if (!alive) return;
setD({
people: people.ok ? people.data.total : null,
deletions: dels.ok ? dels.data.items.filter((x) => x.status === "waiting_approval").length : null,
linked: linked.ok ? linked.data : null,
licence: licence.ok ? licence.data : null,
backups: backups.ok ? backups.data : null,
});
});
return () => { alive = false; };
}, []);
if (!d) return <p className="text-sm text-gray-500" role="status">Loading…</p>;
const connected = d.linked?.items.filter((l) => l.signsInHere).length ?? 0;
const notConnected = d.linked?.items.filter((l) => !l.signsInHere && l.listed) ?? [];
const lastBackup = d.backups?.items[0]?.createdAt ?? null;
const todo: { text: string; href: string; action: string }[] = [
...(d.deletions ? [{ text: `${d.deletions} ${d.deletions === 1 ? "person has" : "people have"} asked to delete their account.`, href: "/admin/deletions", action: "Review" }] : []),
...(d.licence && !d.licence.connected ? [{ text: "Accounts isn't connected to Cross Code yet, so the church's sites can't find it.", href: "/admin/licence", action: "Connect" }] : []),
...(notConnected.length ? [{ text: `${notConnected.map((l) => l.name).join(", ")} ${notConnected.length === 1 ? "doesn't" : "don't"} sign people in here yet.`, href: "/admin/linked", action: "Connect" }] : []),
...(d.backups?.lastError ? [{ text: "The last backup didn't work.", href: "/admin/backups", action: "See why" }] : []),
];
return (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
<Stat icon={<Users className="h-5 w-5" />} label="People with an account" value={d.people ?? "—"} href="/admin/people" detail="Find someone" />
<Stat icon={<UserX className="h-5 w-5" />} label="Deletion requests waiting" value={d.deletions ?? "—"} warn={!!d.deletions} href="/admin/deletions" detail={d.deletions ? "They need your answer" : "None waiting"} />
<Stat icon={<Link2 className="h-5 w-5" />} label="Sites that sign in here" value={d.linked ? `${connected} of ${d.linked.items.length}` : "—"} warn={notConnected.length > 0} href="/admin/linked" detail={d.linked && !d.linked.hubConnected ? "Not connected to the Hub" : "Linked products"} />
<Stat icon={<DatabaseBackup className="h-5 w-5" />} label="Last backup" value={lastBackup ? when(lastBackup) : "None yet"} warn={!!d.backups?.lastError} href="/admin/backups" detail={d.backups ? (d.backups.nightly ? "Every night at 02:00" : "Nightly backups are off") : undefined} />
</div>
<Card>
<Heading icon={todo.length ? <AlertTriangle className="h-4 w-4" /> : <CheckCircle2 className="h-4 w-4" />}>{todo.length ? "Needs you" : "Nothing needs you right now"}</Heading>
{todo.length > 0 ? (
<ul className="divide-y">
{todo.map((t) => (
<li key={t.href} className="flex flex-wrap items-center justify-between gap-3 py-3">
<span className="text-sm text-gray-700">{t.text}</span>
<Link href={t.href} className="inline-flex items-center gap-1 rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-dark">{t.action}<ArrowRight className="h-3.5 w-3.5" aria-hidden /></Link>
</li>
))}
</ul>
) : <p className="text-sm text-gray-600">Nothing is waiting for an admin. Anything that is (a deletion request, a site to connect, a backup that failed) shows here.</p>}
</Card>
<Card>
<Heading sub="Every setting, one click away.">All settings</Heading>
<div className="space-y-5">
{ADMIN_GROUPS.filter((g) => g.title).map((g) => (
<div key={g.title}>
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{g.title}</h3>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{g.items.map((n) => {
const Icon = n.icon;
return (
<Link key={n.href} href={n.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand" aria-hidden><Icon className="h-5 w-5" /></span>
<span className="min-w-0">
<span className="block text-sm font-semibold text-gray-900">{n.label}</span>
<span className="mt-0.5 block text-xs text-gray-500">{TILE[n.href]}</span>
</span>
</Link>
);
})}
</div>
</div>
))}
</div>
</Card>
</div>
);
}
// ─── People ────────────────────────────────────────────────────────────────── // ─── People ──────────────────────────────────────────────────────────────────
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null }; type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] }; type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((x) => x[0]!.toUpperCase()).join("") || "?";
const chip = "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium";
function People({ flash }: { flash: Flash }) { function People({ flash }: { flash: Flash }) {
const [q, setQ] = useState(""); const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null); const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
@@ -94,28 +213,47 @@ function People({ flash }: { flash: Flash }) {
}; };
return ( return (
<div className="grid gap-6 md:grid-cols-2"> <div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<Card> <Card>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2"> <form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-3 flex gap-2">
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" /> <span className="relative flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" aria-hidden />
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="w-full rounded-lg border py-2 pl-9 pr-3" />
</span>
<Button type="submit" variant="secondary">Search</Button> <Button type="submit" variant="secondary">Search</Button>
</form> </form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p> <p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} {list?.total === 1 ? "person" : "people"}</p>
<ul className="divide-y"> <ul className="-mx-2 divide-y">
{list?.items.map((p) => ( {list?.items.map((p) => (
<li key={p.id}> <li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50"> <button type="button" onClick={() => show(p.id)} aria-current={open?.id === p.id ? "true" : undefined}
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span> className={`flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left hover:bg-gray-50 ${open?.id === p.id ? "bg-brand/5" : ""}`}>
<span className="block text-sm text-gray-500">{p.email}</span> <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand-dark" aria-hidden>{initials(p.name)}</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-1.5 font-medium text-gray-900">
{p.name}
{p.role === "admin" && <span className={`${chip} bg-brand/10 text-brand-dark`}>admin</span>}
{p.status !== "active" && <span className={`${chip} bg-amber-50 text-amber-800`}>{p.status}</span>}
</span>
<span className="block truncate text-sm text-gray-500">{p.email}</span>
</span>
<span className="hidden shrink-0 text-right text-xs text-gray-500 sm:block">{p.twoFactor ? <span className="inline-flex items-center gap-1 text-green-700"><ShieldCheck className="h-3.5 w-3.5" aria-hidden />Two-step</span> : null}<span className="block">{p.lastSignInAt ? `Signed in ${when(p.lastSignInAt)}` : "Never signed in"}</span></span>
<ChevronRight className="h-4 w-4 shrink-0 text-gray-300" aria-hidden />
</button> </button>
</li> </li>
))} ))}
</ul> </ul>
</Card> </Card>
{open && ( {open ? (
<Card> <Card className="lg:sticky lg:top-20">
<Heading sub={open.email}>{open.name}</Heading> <div className="mb-4 flex items-center gap-3">
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm"> <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-brand/10 text-sm font-semibold text-brand-dark" aria-hidden>{initials(open.name)}</span>
<div className="min-w-0">
<h2 className="text-lg font-semibold text-gray-900">{open.name}</h2>
<p className="truncate text-xs text-gray-500">{open.email}</p>
</div>
</div>
<dl className="mb-4 grid grid-cols-2 gap-y-1.5 rounded-lg bg-gray-50 p-3 text-sm">
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd> <dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd> <dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd> <dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
@@ -126,12 +264,18 @@ function People({ flash }: { flash: Flash }) {
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>} {open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>} {open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button> <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button> <Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => { if (open.status === "active" && !window.confirm(`Deactivate ${open.name}? They're signed out of every site straight away.`)) return; void act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated."); }}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
</div> </div>
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p> <p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p> <p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul> <ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((x, i) => <li key={i}>{x.type} · {when(x.at)} {x.ip && <span className="text-gray-500">· {x.ip}</span>}</li>)}</ul>
{!open.signIns.length && <p className="text-sm text-gray-500">None yet.</p>}
</Card> </Card>
) : (
<div className="hidden rounded-xl border border-dashed p-8 text-center text-sm text-gray-500 lg:block">
<Users className="mx-auto mb-2 h-6 w-6 text-gray-300" aria-hidden />
Choose someone to see their account and what you can do for them.
</div>
)} )}
</div> </div>
); );
@@ -141,16 +285,16 @@ function People({ flash }: { flash: Flash }) {
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } }; type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
function Deletions({ flash }: { flash: Flash }) { function Deletions({ flash, onChange }: { flash: Flash; onChange: (waiting: number) => void }) {
const [items, setItems] = useState<Deletion[]>([]); const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => { const load = useCallback(async () => {
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions"); const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
if (r.ok) setItems(r.data.items); if (r.ok) { setItems(r.data.items); onChange(r.data.items.filter((x) => x.status === "waiting_approval").length); }
}, []); }, [onChange]);
useExternalEffect(() => { void load(); }, [load]); useExternalEffect(() => { void load(); }, [load]);
return ( return (
<Card> <Card>
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading> <Heading icon={<UserX className="h-4 w-4" />} sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>} {!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
<ul className="divide-y"> <ul className="divide-y">
{items.map((d) => ( {items.map((d) => (
@@ -189,7 +333,8 @@ function Church({ flash }: { flash: Flash }) {
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null); const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return ( return (
<Card> <Card>
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading> <Heading icon={<Building2 className="h-4 w-4" />} sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="The church's logo" className="mb-4 h-12 w-auto rounded border bg-gray-50 p-1" />}
<form onSubmit={async (e) => { <form onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
const f = new FormData(e.currentTarget); const f = new FormData(e.currentTarget);
@@ -230,7 +375,7 @@ function Linked({ flash }: { flash: Flash }) {
if (!data) return <p className="text-gray-600">Loading…</p>; if (!data) return <p className="text-gray-600">Loading…</p>;
return ( return (
<Card> <Card>
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading> <Heading icon={<Link2 className="h-4 w-4" />} sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
{!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>} {!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>}
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>} {!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<ul className="divide-y"> <ul className="divide-y">
@@ -260,7 +405,7 @@ const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "numb
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"], wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
}; };
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) { function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: string[]; title: string; icon: React.ReactNode; sub?: string }) {
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null); const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
useExternalEffect(() => { useExternalEffect(() => {
let alive = true; let alive = true;
@@ -271,6 +416,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true }; const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
return ( return (
<Card> <Card>
<Heading icon={icon} sub={sub}>{title}</Heading>
<form onSubmit={async (e) => { <form onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
const f = new FormData(e.currentTarget); const f = new FormData(e.currentTarget);
@@ -281,7 +427,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
else body[k] = String(f.get(k) ?? ""); else body[k] = String(f.get(k) ?? "");
} }
const r = await call("PUT", "/admin/settings", body); const r = await call("PUT", "/admin/settings", body);
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message); if (r.ok) flash("success", `${title}: saved.`); else flash("error", r.error.message);
}}> }}>
{keys.map((k) => { {keys.map((k) => {
const [label, kind] = SETTING_LABELS[k]!; const [label, kind] = SETTING_LABELS[k]!;
@@ -318,7 +464,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<Card> <Card>
<Heading sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading> <Heading icon={<FileText className="h-4 w-4" />} sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
{builtIn && !isBuiltIn && ( {builtIn && !isBuiltIn && (
<p className="mb-4 text-sm text-gray-600"> <p className="mb-4 text-sm text-gray-600">
The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "} The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}
@@ -339,7 +485,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
</form> </form>
</Card> </Card>
<Card> <Card>
<Heading sub="As people will see it.">Preview</Heading> <Heading icon={<Eye className="h-4 w-4" />} sub="As people will see it.">Preview</Heading>
<h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3> <h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3>
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div> <div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
</Card> </Card>
@@ -357,7 +503,7 @@ function Licence({ flash }: { flash: Flash }) {
if (!s) return <p className="text-gray-600">Loading…</p>; if (!s) return <p className="text-gray-600">Loading…</p>;
return ( return (
<Card> <Card>
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading> <Heading icon={<KeyRound className="h-4 w-4" />} sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm"> <dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd> <dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd> <dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
@@ -388,7 +534,7 @@ function Audit() {
}, []); }, []);
return ( return (
<Card> <Card>
<Heading>Audit log</Heading> <Heading icon={<ScrollText className="h-4 w-4" />}>Audit log</Heading>
<ul className="divide-y text-sm"> <ul className="divide-y text-sm">
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)} {items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>} {!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
@@ -7,9 +7,9 @@ export async function generateMetadata({ params }: { params: Promise<{ section:
return { title: ADMIN_SECTIONS[section as AdminSection]?.title ?? "Admin" }; return { title: ADMIN_SECTIONS[section as AdminSection]?.title ?? "Admin" };
} }
/** One section of admin (1.3.0): /admin/deletions, /church, /linked, … (/admin itself is People). */ /** One section of admin (1.3.0): /admin/people, /deletions, /church, … (1.8.0: /admin itself is the overview). */
export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) { export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) {
const { section } = await params; const { section } = await params;
if (section === "people" || !(section in ADMIN_SECTIONS)) notFound(); if (section === "overview" || !(section in ADMIN_SECTIONS)) notFound();
return <Admin section={section as AdminSection} />; return <Admin section={section as AdminSection} />;
} }
@@ -3,5 +3,5 @@ import { Admin } from "./Admin";
export const metadata = { title: "Admin" }; export const metadata = { title: "Admin" };
export default function AdminPage() { export default function AdminPage() {
return <Admin />; return <Admin section="overview" />;
} }
@@ -12,7 +12,7 @@ import { useBranding } from "@/components/BrandingProvider";
/** Who's signed in, as the shell shows them (null: a public page such as the privacy notice). */ /** Who's signed in, as the shell shows them (null: a public page such as the privacy notice). */
export type ShellUser = { name: string; email: string; role: "member" | "admin" }; export type ShellUser = { name: string; email: string; role: "member" | "admin" };
type NavItem = { href: string; label: string; icon: LucideIcon }; export type NavItem = { href: string; label: string; icon: LucideIcon };
export const ACCOUNT_NAV: NavItem[] = [ export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account", label: "Overview", icon: LayoutDashboard }, { href: "/account", label: "Overview", icon: LayoutDashboard },
@@ -22,19 +22,21 @@ export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account/activity", label: "Activity", icon: Activity }, { href: "/account/activity", label: "Activity", icon: Activity },
]; ];
export const ADMIN_NAV: NavItem[] = [ /** 1.8.0: the admin's sections in groups, as Cross Events' settings, with the overview first. */
{ href: "/admin", label: "People", icon: Users }, export const ADMIN_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ href: "/admin/deletions", label: "Deletion requests", icon: UserX }, { title: null, items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
{ href: "/admin/church", label: "Church profile", icon: Building2 }, { title: "People", items: [{ href: "/admin/people", label: "People", icon: Users }, { href: "/admin/deletions", label: "Deletion requests", icon: UserX }] },
{ href: "/admin/linked", label: "Linked products", icon: Link2 }, { title: "Church", items: [{ href: "/admin/church", label: "Church profile", icon: Building2 }, { href: "/admin/linked", label: "Linked products", icon: Link2 }] },
{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn }, {
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail }, title: "Signing in",
{ href: "/admin/notice", label: "Privacy notice", icon: FileText }, items: [{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn }, { href: "/admin/messages", label: "Email and WhatsApp", icon: Mail }, { href: "/admin/notice", label: "Privacy notice", icon: FileText }],
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup }, },
{ href: "/admin/jobs", label: "Background jobs", icon: Timer }, {
{ href: "/admin/licence", label: "Licence", icon: KeyRound }, title: "System",
{ href: "/admin/audit", label: "Audit log", icon: ScrollText }, items: [{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup }, { href: "/admin/jobs", label: "Background jobs", icon: Timer }, { href: "/admin/licence", label: "Licence", icon: KeyRound }, { href: "/admin/audit", label: "Audit log", icon: ScrollText }],
},
]; ];
export const ADMIN_NAV: NavItem[] = ADMIN_GROUPS.flatMap((g) => g.items);
/** Signs out of Accounts and every site of the church (RP-initiated logout), ending on /signed-out. */ /** Signs out of Accounts and every site of the church (RP-initiated logout), ending on /signed-out. */
export function signOutHref() { export function signOutHref() {
@@ -53,28 +55,59 @@ function RoleBadge({ role }: { role: ShellUser["role"] }) {
: <span className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600">Member</span>; : <span className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600">Member</span>;
} }
function NavList({ title, items, active, onNavigate }: { title: string; items: NavItem[]; active: string; onNavigate?: () => void }) { /** Counts beside a section (deletion requests waiting, say), by its address. */
export type Badges = Record<string, number>;
function NavLinks({ items, active, badges, onNavigate }: { items: NavItem[]; active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<ul className="space-y-0.5">
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
const n = badges?.[l.href] ?? 0;
return (
<li key={l.href}>
<Link href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
<span className="flex-1">{l.label}</span>
{n > 0 && <span className="rounded-full bg-amber-100 px-1.5 text-xs font-semibold text-amber-900">{n}<span className="sr-only"> waiting</span></span>}
</Link>
</li>
);
})}
</ul>
);
}
function AccountNav({ active, onNavigate }: { active: string; onNavigate?: () => void }) {
return ( return (
<div className="mb-6"> <div className="mb-6">
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-400">{title}</p> <p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Your account</p>
<nav className="space-y-1" aria-label={title}> <nav aria-label="Your account"><NavLinks items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /></nav>
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
return (
<Link key={l.href} href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
{l.label}
</Link>
);
})}
</nav>
</div> </div>
); );
} }
function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: string; onNavigate?: () => void }) { function AdminNav({ active, badges, onNavigate }: { active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<nav aria-label="Admin" className="mb-6 space-y-5">
{ADMIN_GROUPS.map((g, i) => (
<div key={g.title ?? i}>
<p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title ?? "Admin"}</p>
<NavLinks items={g.items} active={active} badges={badges} onNavigate={onNavigate} />
</div>
))}
</nav>
);
}
/**
* The sidebar: who's signed in, then the sections of the part you're in (1.8.0: your account or
* admin, not both at once; the bar across the top switches). In the phone menu, both.
*/
function SidebarContent({ me, active, badges, both, onNavigate }: { me: ShellUser; active: string; badges?: Badges; both?: boolean; onNavigate?: () => void }) {
const inAdmin = me.role === "admin" && active.startsWith("/admin");
return ( return (
<> <>
<div className="mb-6 flex items-center gap-3 px-1"> <div className="mb-6 flex items-center gap-3 px-1">
@@ -84,8 +117,14 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
<RoleBadge role={me.role} /> <RoleBadge role={me.role} />
</div> </div>
</div> </div>
<NavList title="Your account" items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /> {(both || !inAdmin) && <AccountNav active={active} onNavigate={onNavigate} />}
{me.role === "admin" && <NavList title="Admin" items={ADMIN_NAV} active={active} onNavigate={onNavigate} />} {me.role === "admin" && (both || inAdmin) && <AdminNav active={active} badges={badges} onNavigate={onNavigate} />}
{!both && me.role === "admin" && (
<Link href={inAdmin ? "/account" : "/admin"} className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-2 text-sm text-gray-600 hover:border-brand/40 hover:text-brand-dark">
{inAdmin ? <User className="h-4 w-4" aria-hidden /> : <ShieldCheck className="h-4 w-4" aria-hidden />}
{inAdmin ? "Go to your account" : "Go to admin"}
</Link>
)}
</> </>
); );
} }
@@ -95,7 +134,7 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
* and name across the top, a sidebar of sections, the page on a light grey, and a dark footer. * and name across the top, a sidebar of sections, the page on a light grey, and a dark footer.
* Without `me` (a public page) there's no sidebar. `active` is the current section's address. * Without `me` (a public page) there's no sidebar. `active` is the current section's address.
*/ */
export function AppShell({ me, active = "", children }: { me: ShellUser | null; active?: string; children: React.ReactNode }) { export function AppShell({ me, active = "", badges, children }: { me: ShellUser | null; active?: string; badges?: Badges; children: React.ReactNode }) {
const b = useBranding(); const b = useBranding();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const top = "text-sm border-b-2 pb-0.5 transition-colors"; const top = "text-sm border-b-2 pb-0.5 transition-colors";
@@ -131,7 +170,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} /> <button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
<div className="absolute inset-y-0 left-0 flex w-72 max-w-[85vw] flex-col overflow-y-auto bg-white p-4 shadow-xl"> <div className="absolute inset-y-0 left-0 flex w-72 max-w-[85vw] flex-col overflow-y-auto bg-white p-4 shadow-xl">
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="mb-2 self-end rounded-md p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button> <button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="mb-2 self-end rounded-md p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
<SidebarContent me={me} active={active} onNavigate={() => setOpen(false)} /> <SidebarContent me={me} active={active} badges={badges} both onNavigate={() => setOpen(false)} />
<a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className="mt-auto flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50"> <a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className="mt-auto flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50">
<LogOut className="h-4 w-4" aria-hidden /> Sign out <LogOut className="h-4 w-4" aria-hidden /> Sign out
</a> </a>
@@ -142,7 +181,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<div className="mx-auto flex w-full max-w-7xl flex-1"> <div className="mx-auto flex w-full max-w-7xl flex-1">
{me && ( {me && (
<aside className="hidden w-64 shrink-0 border-r bg-white p-4 md:block"> <aside className="hidden w-64 shrink-0 border-r bg-white p-4 md:block">
<div className="sticky top-20"><SidebarContent me={me} active={active} /></div> <div className="sticky top-20"><SidebarContent me={me} active={active} badges={badges} /></div>
</aside> </aside>
)} )}
<main id="main" className="min-w-0 flex-1 p-4 sm:p-6">{children}</main> <main id="main" className="min-w-0 flex-1 p-4 sm:p-6">{children}</main>
@@ -159,12 +198,15 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
); );
} }
/** A page's title and a line under it, at the top of the main column. */ /** A page's title and a line under it, at the top of the main column; with the section's icon. */
export function PageTitle({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) { export function PageTitle({ children, sub, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: LucideIcon }) {
return ( return (
<div className="mb-6"> <div className="mb-6 flex items-start gap-3">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1> {Icon && <span className="mt-0.5 hidden h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand sm:flex" aria-hidden><Icon className="h-5 w-5" /></span>}
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>} <div className="min-w-0">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
</div>
</div> </div>
); );
} }
+17 -12
View File
@@ -1,15 +1,20 @@
/** The admin's sections (1.3.0): one address each, in the sidebar (components/AppShell.tsx). */ /**
* The admin's sections: one address each, in groups down the side (components/AppShell.tsx), and a
* tile each on the overview. 1.8.0: /admin is the overview (as Cross Events' admin dashboard);
* People moved to /admin/people.
*/
export const ADMIN_SECTIONS = { export const ADMIN_SECTIONS = {
people: { path: "/admin", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site." }, overview: { path: "/admin", title: "Admin", sub: "How Accounts stands, what needs you, and every setting.", tile: "" },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account." }, people: { path: "/admin/people", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site.", tile: "Find someone, reset their two-step sign-in, make an admin" },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites." }, deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account.", tile: "Approve or cancel people's requests to delete their account" },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here." }, church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites.", tile: "Name, logo, colours and contact details for every site" },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in." }, linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here.", tile: "The sites and apps that sign people in here" },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." }, signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in.", tile: "Who can make an account, two-step sign-in, staying signed in" },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." }, messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices.", tile: "How sign-in codes and password links are sent" },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." }, notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes.", tile: "What people read before they first sign in" },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." }, backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server.", tile: "Back up now, download a copy, how many to keep" },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." }, jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away.", tile: "What runs on a schedule, and when" },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." }, licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code.", tile: "The connection to Cross Code" },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here.", tile: "Who changed what, and when" },
} as const; } as const;
export type AdminSection = keyof typeof ADMIN_SECTIONS; export type AdminSection = keyof typeof ADMIN_SECTIONS;
+30
View File
@@ -1,5 +1,35 @@
# Changelog — Church Website # Changelog — Church Website
## [1.1.0] — 2026-11-26
No migration, no new settings, no backend changes. The admin redesigned as Cross Events' admin
dashboard and settings. Adds `lucide-react` (the version Accounts uses).
### Added
- **Steps to the first publish** across the top of every admin page until the site is live (from
the setup checklist): each step is a link, done ones are ticked, "Next" goes to the first one to
do, and it folds to one line (remembered in the browser). It updates after every save.
- **A live preview beside the page editor** (home and custom pages) and Template and style: the
page at computer or phone width, scaled to fit, reloaded on each save at the same scroll position.
It folds to a tab on the right (remembered); on phones it's a Preview button that opens it full
screen. It shows drafts without the preview cookie: a request from a frame
(`Sec-Fetch-Dest: iframe`) with an admin session reads the drafts, so the live site in another
tab stays live. Links inside it load in full so they stay on drafts. `/preview/start` takes
`?to=` (a site path only) to open the full preview on that page.
### Changed
- **The admin's frame:** a sidebar with icons in groups (Your site, Content, Go live, Team), a
drawer on phones, and a bar across the top with the changes not published, Preview and who's
signed in. Publish shows the number of changes waiting.
- **The dashboard** as Cross Events': a welcome, four cards (site, changes waiting, storage, last
edit), a tile for every part of the admin, and recent edits.
- **The page editor** has tabs, Content and Page details (title, address, menu, search and
sharing); blocks are cards with a summary, icon buttons to move, hide and remove (asks first), and
"Add a block" is a grid of tiles. **Template and style** has tabs: Template, Home page layout,
Style. Every admin page has its icon.
## [1.0.2] — 2026-11-26 ## [1.0.2] — 2026-11-26
No migration, no new settings. Works with Accounts 1.7.0; with Accounts 1.7.1 the first sign-in No migration, no new settings. Works with Accounts 1.7.0; with Accounts 1.7.1 the first sign-in
+9
View File
@@ -3,6 +3,15 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged). WHATS-NEW.md; a section shows once its version is tagged).
## 1.1.0
- **An easier admin.** A menu with icons down the side, and a dashboard with a tile for every part
of your site.
- **Steps to get your site live:** until your site is published, the top of every admin page shows
what's left to do. Click a step to go there, or **Next** for the next one.
- **See your page as you edit it:** a live preview beside the editor, at computer or phone size.
It updates every time you save, and you can fold it away to the right.
## 1.0.2 ## 1.0.2
- **Preview works:** pressing Preview in the admin shows your site with your changes, instead of - **Preview works:** pressing Preview in the admin shows your site with your changes, instead of
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.0.2", "version": "1.1.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads", "description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true, "private": true,
"type": "module", "type": "module",
+26 -1
View File
@@ -21,10 +21,12 @@ async function signIn(context: BrowserContext, role = "editor") {
async function aboutTitle(page: Page, title: string) { async function aboutTitle(page: Page, title: string) {
await page.goto("/admin/pages"); await page.goto("/admin/pages");
await page.getByRole("link", { name: "About us", exact: true }).first().click(); await page.getByRole("link", { name: /^About us\b/ }).first().click();
// The list page has a Title field too (Add a page): wait for the page's own editor. // The list page has a Title field too (Add a page): wait for the page's own editor.
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/); await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible(); await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
// The editor opens on the page's content; the title is under Page details.
await page.getByRole("tab", { name: "Page details" }).click();
await page.getByLabel("Title", { exact: true }).fill(title); await page.getByLabel("Title", { exact: true }).fill(title);
await page.getByRole("button", { name: "Save details" }).click(); await page.getByRole("button", { name: "Save details" }).click();
await expect(page.getByText("Saved as a draft.")).toBeVisible(); await expect(page.getByText("Saved as a draft.")).toBeVisible();
@@ -58,6 +60,23 @@ test("edit, preview the whole site, publish: then visitors see it", async ({ pag
await visitor.close(); await visitor.close();
}); });
test("the live preview beside the editor shows the draft; the site itself doesn't", async ({ page, context }) => {
await signIn(context);
await aboutTitle(page, "Draft title");
const frame = page.frameLocator('iframe[title="Live preview of this page"]');
await expect(frame.getByRole("heading", { level: 1, name: "Draft title" })).toBeVisible();
// No preview cookie: the same browser, outside the frame, still sees the live site.
await page.goto("/about");
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
await expect(page.getByRole("region", { name: "Preview" })).toHaveCount(0);
// Folded away, it stays folded.
await page.goBack();
await page.getByRole("button", { name: "Hide the preview" }).click();
await expect(page.getByRole("button", { name: "Show the live preview" })).toBeVisible();
await page.reload();
await expect(page.getByRole("button", { name: "Show the live preview" })).toBeVisible();
});
test("discard one change", async ({ page, context }) => { test("discard one change", async ({ page, context }) => {
await signIn(context); await signIn(context);
await aboutTitle(page, "Changed my mind"); await aboutTitle(page, "Changed my mind");
@@ -159,4 +178,10 @@ test("the admin's screens are accessible", async ({ page, context }) => {
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze(); const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
expect(axe.violations.map((v) => `${path}: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]); expect(axe.violations.map((v) => `${path}: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
} }
// And a page's editor, with its live preview beside it.
await page.goto("/admin/pages");
await page.getByRole("link", { name: /^Home\b/ }).first().click();
await expect(page.frameLocator('iframe[title="Live preview of this page"]').getByRole("heading", { level: 1 })).toBeVisible();
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
expect(axe.violations.map((v) => `editor: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
}); });
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.0.2", "version": "1.1.0",
"private": true, "private": true,
"description": "Church Website: the church's public site in its template, and the admin", "description": "Church Website: the church's public site in its template, and the admin",
"scripts": { "scripts": {
@@ -14,6 +14,7 @@
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/seo": "*", "@crosscode/seo": "*",
"@crosscode/ui": "*", "@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6", "next": "^16.4.6",
"react": "^19.3.1", "react": "^19.3.1",
"react-dom": "^19.3.1" "react-dom": "^19.3.1"
@@ -0,0 +1,152 @@
"use client";
/**
* The live preview beside an editor: the page as it will look, with your saved drafts, on the right.
* It folds away to a tab on the right edge (remembered in this browser), shows a desktop or a phone
* width (the desktop scaled down to fit), and reloads where you were scrolled to each time
* something is saved. On a small screen it's a button that opens it full screen.
*
* The frame's pages are the working copy because they're framed and you're signed in (site/load.ts).
*/
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { Eye, ExternalLink, Monitor, PanelRightClose, PanelRightOpen, RotateCw, Smartphone, X } from "lucide-react";
import { cx } from "./ui";
type Device = "desktop" | "phone";
const WIDTH: Record<Device, number> = { desktop: 1280, phone: 390 };
const OPEN_KEY = "ccw-admin-preview-open";
const DEVICE_KEY = "ccw-admin-preview-device";
const read = (k: string) => { try { return window.localStorage.getItem(k); } catch { return null; } };
const write = (k: string, v: string) => { try { window.localStorage.setItem(k, v); } catch { /* not kept */ } };
function Frame({ path, version, device }: { path: string; version: string; device: Device }) {
const box = useRef<HTMLDivElement>(null);
const frame = useRef<HTMLIFrameElement>(null);
const scroll = useRef(0);
const shown = useRef(version);
const [size, setSize] = useState({ w: 0, h: 0 });
const [loading, setLoading] = useState(true);
useLayoutEffect(() => {
const el = box.current;
if (!el) return;
const ro = new ResizeObserver(([e]) => setSize({ w: e!.contentRect.width, h: e!.contentRect.height }));
ro.observe(el);
return () => ro.disconnect();
}, []);
// A save: reload the page in the frame (wherever it was clicked to), back at the same place.
useEffect(() => {
if (shown.current === version) return;
shown.current = version;
const w = frame.current?.contentWindow;
if (!w) return;
try {
scroll.current = w.scrollY;
// eslint-disable-next-line react-hooks/set-state-in-effect
setLoading(true);
w.location.reload();
} catch {
// Not the site's own page any more (a link out): leave it.
}
}, [version]);
const onLoad = useCallback(() => {
setLoading(false);
const w = frame.current?.contentWindow;
if (w && scroll.current) {
try { w.scrollTo(0, scroll.current); } catch { /* elsewhere */ }
scroll.current = 0;
}
}, []);
// The page at its real width, scaled down to fit (a phone has a margin round it).
const logical = WIDTH[device];
const pad = device === "phone" ? 12 : 0;
const scale = size.w ? Math.min(1, (size.w - pad * 2) / logical) : 1;
return (
<div ref={box} className="relative min-h-0 flex-1 overflow-hidden bg-gray-100">
{size.w > 0 && (
<iframe ref={frame} src={path} title="Live preview of this page" onLoad={onLoad}
className={cx("absolute origin-top-left border-0 bg-white", device === "phone" && "rounded-2xl shadow-lg ring-1 ring-gray-300")}
style={{ top: pad, left: (size.w - logical * scale) / 2, width: logical, height: (size.h - pad * 2) / scale, transform: `scale(${scale})` }} />
)}
{loading && <div className="pointer-events-none absolute right-3 top-3 rounded-full bg-white/90 px-2.5 py-1 text-xs text-gray-600 shadow" role="status">Loading…</div>}
</div>
);
}
function Toolbar({ path, device, setDevice, onReload, onClose, closeIcon }: { path: string; device: Device; setDevice: (d: Device) => void; onReload: () => void; onClose: () => void; closeIcon: "panel" | "x" }) {
const btn = "rounded-md p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-900";
return (
<div className="flex items-center gap-2 border-b border-gray-200 bg-white px-3 py-2">
<Eye className="h-4 w-4 text-brand-text" aria-hidden />
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-gray-900">Live preview</p>
<p className="truncate text-xs text-gray-500">Updates each time you save · {path === "/" ? "Home page" : path}</p>
</div>
<div className="flex rounded-lg border border-gray-200 p-0.5" role="group" aria-label="Width">
{(["desktop", "phone"] as const).map((d) => {
const Icon = d === "desktop" ? Monitor : Smartphone;
return (
<button key={d} type="button" onClick={() => setDevice(d)} aria-pressed={device === d} aria-label={d === "desktop" ? "Computer width" : "Phone width"} title={d === "desktop" ? "Computer" : "Phone"}
className={cx("rounded-md p-1", device === d ? "bg-brand/10 text-brand-text" : "text-gray-500 hover:text-gray-900")}><Icon className="h-4 w-4" aria-hidden /></button>
);
})}
</div>
<button type="button" onClick={onReload} className={btn} aria-label="Reload the preview" title="Reload"><RotateCw className="h-4 w-4" aria-hidden /></button>
<a href={`/preview/start?to=${encodeURIComponent(path)}`} target="_blank" rel="noopener" className={btn} aria-label="Open the full preview in a new tab" title="Open the full preview"><ExternalLink className="h-4 w-4" aria-hidden /></a>
<button type="button" onClick={onClose} className={btn} aria-label="Hide the preview" title="Hide the preview">
{closeIcon === "panel" ? <PanelRightClose className="h-4 w-4" aria-hidden /> : <X className="h-4 w-4" aria-hidden />}
</button>
</div>
);
}
/** An editor with the live preview of `path` beside it. `version` changes with each save (the saved data, say): the preview reloads. */
export function WithPreview({ path, version, children }: { path: string; version: string; children: React.ReactNode }) {
const [open, setOpenState] = useState(true);
const [device, setDeviceState] = useState<Device>("desktop");
const [sheet, setSheet] = useState(false);
const [manual, setManual] = useState(0);
useEffect(() => {
// The browser remembers the last choice.
// eslint-disable-next-line react-hooks/set-state-in-effect
if (read(OPEN_KEY) === "0") setOpenState(false);
if (read(DEVICE_KEY) === "phone") setDeviceState("phone");
}, []);
const setOpen = (v: boolean) => { setOpenState(v); write(OPEN_KEY, v ? "1" : "0"); };
const setDevice = (d: Device) => { setDeviceState(d); write(DEVICE_KEY, d); };
const v = `${version}·${manual}`;
return (
<div className="lg:flex lg:items-start lg:gap-6">
<div className="min-w-0 flex-1">{children}</div>
{/* Wide screens: beside the editor, or folded to a tab on the right edge. */}
{open ? (
<aside aria-label="Live preview" className="sticky top-[77px] hidden h-[calc(100vh-101px)] w-[45%] max-w-[52rem] shrink-0 flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm lg:flex">
<Toolbar path={path} device={device} setDevice={setDevice} onReload={() => setManual((n) => n + 1)} onClose={() => setOpen(false)} closeIcon="panel" />
<Frame path={path} version={v} device={device} />
</aside>
) : (
<button type="button" onClick={() => setOpen(true)} aria-label="Show the live preview"
className="fixed right-0 top-1/2 z-20 hidden -translate-y-1/2 items-center gap-2 rounded-l-xl border border-r-0 border-gray-200 bg-white px-2 py-4 text-sm font-semibold text-gray-700 shadow-lg hover:text-brand-text lg:flex [writing-mode:vertical-rl]">
<PanelRightOpen className="h-4 w-4 rotate-90" aria-hidden /> Show preview
</button>
)}
{/* Small screens: a button that opens it full screen. */}
<button type="button" onClick={() => setSheet(true)} className="fixed bottom-4 right-4 z-20 inline-flex items-center gap-2 rounded-full bg-brand px-4 py-3 text-sm font-semibold text-brand-on shadow-lg lg:hidden">
<Eye className="h-4 w-4" aria-hidden /> Preview
</button>
{sheet && (
<div className="fixed inset-0 z-50 flex flex-col bg-white lg:hidden" role="dialog" aria-modal="true" aria-label="Live preview">
<Toolbar path={path} device={device} setDevice={setDevice} onReload={() => setManual((n) => n + 1)} onClose={() => setSheet(false)} closeIcon="x" />
<Frame path={path} version={v} device={device} />
</div>
)}
</div>
);
}
@@ -0,0 +1,87 @@
"use client";
/**
* The steps to a first publish, across the top of every admin page until the site is live: each
* step is a link, done ones are ticked, and "Next" goes to the first one still to do. It can be
* folded to one line (remembered in this browser).
*/
import Link from "next/link";
import { useEffect, useState } from "react";
import { ArrowRight, Check, ChevronDown, ChevronUp, Rocket } from "lucide-react";
import { cx, type Overview } from "./ui";
const KEY = "ccw-admin-steps-folded";
export function SetupSteps({ overview, path }: { overview: Overview; path: string }) {
const [folded, setFolded] = useState(false);
useEffect(() => {
try {
// Only the browser knows what was chosen last time.
// eslint-disable-next-line react-hooks/set-state-in-effect
setFolded(window.localStorage.getItem(KEY) === "1");
} catch {
// Storage blocked: the steps show unfolded.
}
}, []);
const fold = (v: boolean) => {
setFolded(v);
try { window.localStorage.setItem(KEY, v ? "1" : "0"); } catch { /* not kept */ }
};
const steps = overview.checklist;
const done = steps.filter((s) => s.done).length;
const next = steps.find((s) => !s.done) ?? null;
const percent = steps.length ? Math.round((done / steps.length) * 100) : 0;
return (
<section aria-label="Getting your site ready" className="mb-6 rounded-xl border border-brand/20 bg-white shadow-sm">
<div className="flex flex-wrap items-center gap-x-4 gap-y-3 p-4">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand text-brand-on" aria-hidden><Rocket className="h-[18px] w-[18px]" /></span>
<div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-gray-900">Get your site ready to publish</h2>
<div className="mt-1 flex items-center gap-2">
<div className="h-1.5 w-32 overflow-hidden rounded-full bg-gray-200" role="progressbar" aria-valuenow={done} aria-valuemin={0} aria-valuemax={steps.length} aria-label="Steps done">
<div className="h-full rounded-full bg-brand transition-all" style={{ width: `${percent}%` }} />
</div>
<span className="text-xs text-gray-500">{done} of {steps.length} done</span>
</div>
</div>
{next?.href && (
<Link href={next.href} className="order-last inline-flex w-full items-center justify-center gap-1.5 rounded-lg bg-brand px-3 py-2 text-sm font-semibold text-brand-on hover:bg-brand-dark sm:order-none sm:w-auto">
<span className="hidden sm:inline">Next:</span> {next.label}<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
)}
<button type="button" onClick={() => fold(!folded)} aria-expanded={!folded} aria-label={folded ? "Show the steps" : "Hide the steps"} title={folded ? "Show the steps" : "Hide the steps"}
className="rounded-lg p-2 text-gray-500 hover:bg-gray-100 hover:text-gray-800">
{folded ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronUp className="h-4 w-4" aria-hidden />}
</button>
</div>
{!folded && (
<ol className="flex gap-2 overflow-x-auto border-t border-gray-100 px-4 py-3">
{steps.map((s, i) => {
const isNext = s === next;
const here = !!s.href && (path === s.href || path.startsWith(`${s.href}/`));
const body = (
<>
<span className={cx("flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-semibold",
s.done ? "bg-green-600 text-white" : isNext ? "bg-brand text-brand-on ring-4 ring-brand/15" : "bg-gray-100 text-gray-500")} aria-hidden>
{s.done ? <Check className="h-4 w-4" /> : i + 1}
</span>
<span className={cx("text-sm leading-tight", s.done ? "text-gray-500" : isNext ? "font-semibold text-gray-900" : "text-gray-700", here && "underline decoration-2 underline-offset-4")}>{s.label}</span>
<span className="sr-only">{s.done ? "(done)" : isNext ? "(next)" : "(to do)"}</span>
</>
);
return (
<li key={s.key} className="flex min-w-[10rem] flex-1 items-center gap-2">
{s.href ? (
<Link href={s.href} aria-current={here ? "step" : undefined} className="flex flex-1 items-center gap-2 rounded-lg p-1.5 hover:bg-gray-50">{body}</Link>
) : <span className="flex flex-1 items-center gap-2 p-1.5">{body}</span>}
{i < steps.length - 1 && <span className={cx("hidden h-px w-6 shrink-0 lg:block", s.done ? "bg-green-600" : "bg-gray-200")} aria-hidden />}
</li>
);
})}
</ol>
)}
</section>
);
}
+102 -46
View File
@@ -1,61 +1,117 @@
"use client"; "use client";
/** The admin's frame: navigation, the pending change count, Preview and Sign out (§4, §10). */ /**
* The admin's frame (§4, §10), as Cross Events' dashboard: a bar across the top (the pending change
* count, Preview, who's signed in, Sign out), the sections down the side with icons in groups, and,
* until the site is first published, the steps to get there above every page.
*/
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useMemo, useState } from "react";
import { Eye, Globe, LogOut, Menu, X } from "lucide-react";
import { ROLE_NAMES } from "./api"; import { ROLE_NAMES } from "./api";
import { cx, useAdmin } from "./ui"; import { NAV_GROUPS } from "./nav";
import { SetupSteps } from "./SetupSteps";
import { cx, OverviewContext, useAdmin, type Overview } from "./ui";
const NAV = [ const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/template", label: "Template and style" }, /** Pages that use the whole width: the editors with the preview beside them. */
{ href: "/admin/church", label: "Church details" }, const wide = (path: string) => path === "/admin/template" || /^\/admin\/pages\/[^/]+$/.test(path);
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" }, function SideNav({ role, path, pending, onNavigate }: { role: string; path: string; pending: number; onNavigate?: () => void }) {
{ href: "/admin/leaders", label: "Leadership" }, const managers = ["owner", "admin"].includes(role);
{ href: "/admin/messages", label: "Messages" }, return (
{ href: "/admin/events", label: "Events" }, <nav aria-label="Admin" className="space-y-5">
{ href: "/admin/linked", label: "Linked products" }, {NAV_GROUPS.map((g, gi) => {
{ href: "/admin/media", label: "Media library" }, const items = g.items.filter((n) => !n.managers || managers);
{ href: "/admin/publish", label: "Publish and history" }, if (!items.length) return null;
{ href: "/admin/settings", label: "Settings" }, return (
{ href: "/admin/people", label: "People", managers: true }, <div key={g.title ?? gi}>
{ href: "/admin/audit", label: "Audit log", managers: true }, {g.title && <p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title}</p>}
]; <ul className="space-y-0.5">
{items.map((n) => {
const Icon = n.icon;
const current = n.href === "/admin" ? path === "/admin" : path === n.href || path.startsWith(`${n.href}/`);
return (
<li key={n.href}>
<Link href={n.href} onClick={onNavigate} aria-current={current ? "page" : undefined}
className={cx("flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors", current ? "bg-brand/10 font-medium text-brand-text" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900")}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
<span className="flex-1">{n.label}</span>
{n.href === "/admin/publish" && pending > 0 && <span className="rounded-full bg-amber-100 px-1.5 text-xs font-semibold text-amber-900">{pending}<span className="sr-only"> not published</span></span>}
</Link>
</li>
);
})}
</ul>
</div>
);
})}
</nav>
);
}
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) { export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
const path = usePathname(); const path = usePathname();
const { data } = useAdmin<{ pending: number }>(`/overview?for=${encodeURIComponent(path)}`); const [open, setOpen] = useState(false);
const { data, reload } = useAdmin<Overview>(`/overview?for=${encodeURIComponent(path)}`);
const ctx = useMemo(() => ({ overview: data, refresh: reload }), [data, reload]);
const pending = data?.pending ?? 0;
return ( return (
<div className="min-h-screen bg-gray-50 font-sans text-gray-900"> <OverviewContext.Provider value={ctx}>
<header className="border-b border-gray-200 bg-white"> <div className="min-h-screen bg-gray-50 font-sans text-gray-900">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-3"> <a href="#admin-main" className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-4 focus:z-50 focus:rounded focus:bg-white focus:px-3 focus:py-2">Skip to content</a>
<Link href="/admin" className="font-semibold">Website admin</Link> <header className="sticky top-0 z-30 border-b border-gray-200 bg-white/95 backdrop-blur">
<div className="flex flex-wrap items-center gap-3 text-sm"> <div className="flex items-center justify-between gap-3 px-4 py-2.5">
{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>} <div className="flex min-w-0 items-center gap-2">
{/* 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 */} <button type="button" onClick={() => setOpen(true)} aria-label="Open the menu" aria-expanded={open} className="rounded-lg p-2 hover:bg-gray-100 md:hidden"><Menu className="h-5 w-5" /></button>
<a href="/preview/start" className="rounded-md border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50">Preview</a> <Link href="/admin" className="flex min-w-0 items-center gap-2 font-semibold">
<span className="text-gray-600">{user.name} · {ROLE_NAMES[user.role] ?? user.role}</span> <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand text-brand-on" aria-hidden><Globe className="h-4 w-4" /></span>
<form method="post" action="/api/auth/signout"><button type="submit" className="text-gray-600 underline-offset-4 hover:underline">Sign out</button></form> <span className="truncate">Website admin</span>
</Link>
</div>
<div className="flex items-center gap-2 text-sm sm:gap-3">
{pending > 0 && <Link href="/admin/publish" className="hidden rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-900 hover:bg-amber-200 sm:inline-block">{pending} {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="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50"><Eye className="h-4 w-4" aria-hidden />Preview</a>
<span className="hidden items-center gap-2 lg:flex">
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand-text" aria-hidden>{initials(user.name)}</span>
<span className="leading-tight"><span className="block font-medium">{user.name}</span><span className="block text-xs text-gray-500">{ROLE_NAMES[user.role] ?? user.role}</span></span>
</span>
<form method="post" action="/api/auth/signout">
<button type="submit" className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-gray-600 hover:bg-gray-100 hover:text-gray-900"><LogOut className="h-4 w-4" aria-hidden /><span className="hidden sm:inline">Sign out</span><span className="sr-only sm:hidden">Sign out</span></button>
</form>
</div>
</div> </div>
</header>
{open && (
<div className="fixed inset-0 z-40 md:hidden" role="dialog" aria-modal="true" aria-label="Menu">
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
<div className="absolute inset-y-0 left-0 w-72 max-w-[85vw] overflow-y-auto bg-white p-4 shadow-xl">
<div className="mb-4 flex items-center justify-between">
<span className="text-sm"><span className="block font-semibold">{user.name}</span><span className="text-xs text-gray-500">{ROLE_NAMES[user.role] ?? user.role}</span></span>
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="rounded-lg p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
</div>
<SideNav role={user.role} path={path} pending={pending} onNavigate={() => setOpen(false)} />
</div>
</div>
)}
<div className="flex">
<aside className="hidden w-60 shrink-0 border-r border-gray-200 bg-white md:block">
<div className="sticky top-[53px] max-h-[calc(100vh-53px)] overflow-y-auto p-4"><SideNav role={user.role} path={path} pending={pending} /></div>
</aside>
<main id="admin-main" className="min-w-0 flex-1 p-4 sm:p-6">
<div className={cx("mx-auto w-full", wide(path) ? "max-w-[100rem]" : "max-w-5xl")}>
{data && !data.lastPublished && <SetupSteps overview={data} path={path} />}
{children}
</div>
</main>
</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.filter((n) => !("managers" in n) || ["owner", "admin"].includes(user.role)).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>
</div> </OverviewContext.Provider>
); );
} }
+50
View File
@@ -0,0 +1,50 @@
/** The admin's sections, in groups (the sidebar) with a line each (the dashboard's tiles). */
import {
Building2, CalendarDays, FileText, HandHeart, Image as ImageIcon, LayoutDashboard, Link2, Mic, Palette, ScrollText,
Send, Settings, UserCog, Users, type LucideIcon,
} from "lucide-react";
export type NavItem = { href: string; label: string; description: string; icon: LucideIcon; managers?: boolean };
export const NAV_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ title: null, items: [{ href: "/admin", label: "Dashboard", description: "Where your site stands, and what to do next", icon: LayoutDashboard }] },
{
title: "Your site",
items: [
{ href: "/admin/template", label: "Template and style", description: "The look: template, home page layout, colours of sections", icon: Palette },
{ href: "/admin/pages", label: "Pages", description: "Your home page, the fixed pages and your own", icon: FileText },
{ href: "/admin/church", label: "Church details", description: "Name, logo, service times and address, for all your sites", icon: Building2 },
],
},
{
title: "Content",
items: [
{ href: "/admin/ministries", label: "Ministries", description: "What happens in your church, each on the Ministries page", icon: HandHeart },
{ href: "/admin/leaders", label: "Leadership", description: "Your pastors and team, with photos", icon: Users },
{ href: "/admin/messages", label: "Messages", description: "Sermons, from YouTube or Spotify", icon: Mic },
{ href: "/admin/events", label: "Events", description: "What's coming up, or your Cross Events calendar", icon: CalendarDays },
{ href: "/admin/media", label: "Media library", description: "Your photos, what each shows, and storage", icon: ImageIcon },
],
},
{
title: "Go live",
items: [
{ href: "/admin/publish", label: "Publish and history", description: "What's changed, publish it, share a preview, go back", icon: Send },
{ href: "/admin/linked", label: "Linked products", description: "Cross Events and your church's other sites", icon: Link2 },
{ href: "/admin/settings", label: "Settings", description: "Search engines, the menu order, the Coming soon line", icon: Settings },
],
},
{
title: "Team",
items: [
{ href: "/admin/people", label: "People", description: "Who can edit the site, and what they can do", icon: UserCog, managers: true },
{ href: "/admin/audit", label: "Audit log", description: "Who changed what, and when", icon: ScrollText, managers: true },
],
},
];
export const NAV: NavItem[] = NAV_GROUPS.flatMap((g) => g.items);
/** The section an address is in: the longest match, so /admin/pages/… is Pages. */
export const sectionFor = (path: string): NavItem | undefined =>
NAV.filter((n) => (n.href === "/admin" ? path === "/admin" : path === n.href || path.startsWith(`${n.href}/`))).sort((a, b) => b.href.length - a.href.length)[0];
+101 -16
View File
@@ -1,33 +1,105 @@
"use client"; "use client";
/** The admin's own building blocks: plain, calm, the church's colour for the main action. */ /** The admin's own building blocks: plain, calm, the church's colour for the main action (as Cross Events' dashboard). */
import { useCallback, useEffect, useState } from "react"; import Link from "next/link";
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { ArrowRight, type LucideIcon } from "lucide-react";
import { api, AdminError } from "./api"; import { api, AdminError } from "./api";
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); 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 }) { export function Title({ children, sub, actions, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; actions?: React.ReactNode; icon?: LucideIcon }) {
return ( return (
<div className="mb-6 flex flex-wrap items-end justify-between gap-4"> <div className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div> <div className="flex min-w-0 items-start gap-3">
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1> {Icon && <span className="mt-0.5 hidden h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand-text sm:flex" aria-hidden><Icon className="h-5 w-5" /></span>}
{sub && <p className="mt-1 text-gray-600">{sub}</p>} <div className="min-w-0">
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
</div>
</div> </div>
{actions && <div className="flex flex-wrap gap-2">{actions}</div>} {actions && <div className="flex flex-wrap gap-2">{actions}</div>}
</div> </div>
); );
} }
export function Panel({ children, className, title }: { children: React.ReactNode; className?: string; title?: string }) { /** A white card; with a title, an icon in a tile of the church's colour and a line under it. */
export function Panel({ children, className, title, icon: Icon, sub, actions }: { children: React.ReactNode; className?: string; title?: string; icon?: LucideIcon; sub?: React.ReactNode; actions?: React.ReactNode }) {
return ( return (
<section className={cx("rounded-lg border border-gray-200 bg-white p-5 shadow-sm", className)}> <section className={cx("rounded-xl 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>} {title && (
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-3">
{Icon && <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span>}
<div className="min-w-0">
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
{sub && <p className="mt-0.5 text-sm text-gray-500">{sub}</p>}
</div>
</div>
{actions && <div className="flex flex-wrap gap-2">{actions}</div>}
</div>
)}
{children} {children}
</section> </section>
); );
} }
type BtnProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: "primary" | "secondary" | "danger" | "link"; busy?: boolean }; /** Icon tabs (as Cross Events' Site Settings): one part of a page at a time. */
export function Tabs<T extends string>({ tabs, value, onChange, label }: { tabs: { id: T; label: string; icon: LucideIcon; badge?: React.ReactNode }[]; value: T; onChange: (id: T) => void; label: string }) {
return (
<div role="tablist" aria-label={label} className="mb-4 flex flex-wrap items-center gap-2">
{tabs.map((t) => {
const Icon = t.icon;
const on = t.id === value;
return (
<button key={t.id} type="button" role="tab" aria-selected={on} onClick={() => onChange(t.id)}
className={cx("inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors", on ? "border-brand bg-brand text-brand-on" : "border-gray-200 bg-white text-gray-700 hover:bg-gray-50")}>
<Icon className="h-4 w-4" aria-hidden />
{t.label}
{t.badge}
</button>
);
})}
</div>
);
}
const linkClass = "mt-3 inline-flex items-center gap-1 text-xs font-medium text-brand-text hover:underline";
const TONES = { brand: "bg-brand/10 text-brand-text", amber: "bg-amber-50 text-amber-700", green: "bg-green-50 text-green-700", gray: "bg-gray-100 text-gray-600" };
/** A number on the dashboard: an icon tile, a label, the value, and where to go for more. */
export function StatCard({ icon: Icon, label, value, detail, href, linkLabel, tone = "brand" }: { icon: LucideIcon; label: string; value: React.ReactNode; detail?: React.ReactNode; href?: string; linkLabel?: string; tone?: keyof typeof TONES }) {
return (
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="flex items-center gap-3">
<span className={cx("flex h-10 w-10 shrink-0 items-center justify-center rounded-lg", TONES[tone])} aria-hidden><Icon className="h-5 w-5" /></span>
<div className="min-w-0">
<div className="text-xs leading-snug text-gray-500">{label}</div>
<div className="truncate text-xl font-semibold text-gray-900">{value}</div>
</div>
</div>
{detail && <div className="mt-2 text-xs text-gray-500">{detail}</div>}
{href && (href.startsWith("/admin")
? <Link href={href} className={linkClass}>{linkLabel ?? "Open"}<ArrowRight className="h-3 w-3" aria-hidden /></Link>
: <a href={href} className={linkClass}>{linkLabel ?? "Open"}<ArrowRight className="h-3 w-3" aria-hidden /></a>)}
</div>
);
}
/** A quick-action tile: icon, title and a line about it; the whole tile is the link. */
export function ActionTile({ icon: Icon, title, description, href }: { icon: LucideIcon; title: string; description: string; href: string }) {
return (
<Link href={href} className="flex items-start gap-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-5 w-5" /></span>
<span className="min-w-0">
<span className="block text-sm font-semibold text-gray-900">{title}</span>
<span className="mt-0.5 block text-xs text-gray-500">{description}</span>
</span>
</Link>
);
}
type BtnProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: "primary" | "secondary" | "danger" | "link" | "icon"; busy?: boolean };
export function Btn({ kind = "secondary", busy, className, children, disabled, ...rest }: BtnProps) { export function Btn({ kind = "secondary", busy, className, children, disabled, ...rest }: BtnProps) {
return ( return (
@@ -36,15 +108,17 @@ export function Btn({ kind = "secondary", busy, className, children, disabled, .
{...rest} {...rest}
disabled={disabled || busy} disabled={disabled || busy}
className={cx( 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", "inline-flex items-center justify-center gap-2 rounded-lg text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50",
kind !== "icon" && kind !== "link" && "px-4 py-2",
kind === "primary" && "bg-brand text-brand-on hover:bg-brand-dark", 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 === "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 === "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", kind === "link" && "px-0 py-0 text-brand-text underline-offset-4 hover:underline",
kind === "icon" && "h-8 w-8 border border-gray-200 bg-white text-gray-600 hover:bg-gray-50 hover:text-gray-900",
className, className,
)} )}
> >
{busy ? "Working…" : children} {busy && kind !== "icon" ? "Working…" : children}
</button> </button>
); );
} }
@@ -60,11 +134,11 @@ export function Field({ label, hint, error, children }: { label: string; hint?:
); );
} }
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 const inputClass = "w-full rounded-lg 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 }) { 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" }; 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>; return <div role={tone === "error" ? "alert" : "status"} className={cx("rounded-lg border px-4 py-3 text-sm", tones[tone])}>{children}</div>;
} }
/** Loads `path` from the admin API; `reload` fetches it again. */ /** Loads `path` from the admin API; `reload` fetches it again. */
@@ -88,8 +162,18 @@ export function useAdmin<T>(path: string | null) {
return { data, error, reload: load, setData }; return { data, error, reload: load, setData };
} }
/** Runs an action, keeping its busy state, message and field errors. */ /** The dashboard's numbers, shared by the frame (the change count, the setup steps) and the pages. */
export type Overview = {
pending: number;
lastPublished: { number: number; at: string } | null;
checklist: { key: string; label: string; done: boolean; href: string | null }[];
};
export const OverviewContext = createContext<{ overview: Overview | null; refresh: () => void }>({ overview: null, refresh: () => {} });
export const useOverview = () => useContext(OverviewContext);
/** Runs an action, keeping its busy state, message and field errors. Afterwards the frame's change count and steps catch up. */
export function useAction() { export function useAction() {
const { refresh } = useOverview();
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null); const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
const [fields, setFields] = useState<Record<string, string>>({}); const [fields, setFields] = useState<Record<string, string>>({});
@@ -107,8 +191,9 @@ export function useAction() {
return null; return null;
} finally { } finally {
setBusy(false); setBusy(false);
refresh();
} }
}, []); }, [refresh]);
return { busy, message, fields, run, setMessage }; return { busy, message, fields, run, setMessage };
} }
@@ -4,6 +4,7 @@
import { useState } from "react"; import { useState } from "react";
import { api } from "@/admin/api"; import { api } from "@/admin/api";
import { Btn, Loading, Panel, Title, useAdmin, when } from "@/admin/ui"; import { Btn, Loading, Panel, Title, useAdmin, when } from "@/admin/ui";
import { ScrollText } from "lucide-react";
type Entry = { at: string; who: string; action: string; detail: string | null }; type Entry = { at: string; who: string; action: string; detail: string | null };
@@ -15,7 +16,7 @@ export default function Audit() {
const all = [...first.data, ...more]; const all = [...first.data, ...more];
return ( return (
<> <>
<Title sub="Who changed what, newest first.">Audit log</Title> <Title icon={ScrollText} sub="Who changed what, newest first.">Audit log</Title>
<Panel> <Panel>
{all.length === 0 && <p className="text-gray-600">Nothing yet.</p>} {all.length === 0 && <p className="text-gray-600">Nothing yet.</p>}
<table className="w-full text-left text-sm"> <table className="w-full text-left text-sm">
@@ -10,6 +10,7 @@ import type { Church } from "@crosscode/contracts";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media"; import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { Building2, Clock, MapPin, Palette, Share2 } from "lucide-react";
const DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; const DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
const PAIRINGS: [string, string][] = [["", "Your template's choice"], ["classic", "Classic"], ["scholarly", "Scholarly"], ["editorial", "Editorial"], ["impact", "Impact"], ["contemporary", "Contemporary"], ["friendly", "Friendly"], ["warm", "Warm"], ["modern", "Modern"]]; const PAIRINGS: [string, string][] = [["", "Your template's choice"], ["classic", "Classic"], ["scholarly", "Scholarly"], ["editorial", "Editorial"], ["impact", "Impact"], ["contemporary", "Contemporary"], ["friendly", "Friendly"], ["warm", "Warm"], ["modern", "Modern"]];
@@ -44,13 +45,13 @@ export default function ChurchDetails() {
const err = (k: string) => fields[k]; const err = (k: string) => fields[k];
return ( return (
<> <>
<Title sub="These show on all your church's sites (this website, Cross Events, the sign-in pages). Changes here go live straight away: they aren't drafts." <Title icon={Building2} sub="These show on all your church's sites (this website, Cross Events, the sign-in pages). Changes here go live straight away: they aren't drafts."
actions={editor && edit && <><Btn onClick={() => setEdit(null)}>Undo</Btn><Btn kind="primary" busy={busy} onClick={save}>Save for all your sites</Btn></>}> actions={editor && edit && <><Btn onClick={() => setEdit(null)}>Undo</Btn><Btn kind="primary" busy={busy} onClick={save}>Save for all your sites</Btn></>}>
Church details Church details
</Title> </Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6"> <fieldset disabled={!editor} className="space-y-6">
<Panel title="Name and look"> <Panel icon={Palette} title="Name and look">
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field> <Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field>
<Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field> <Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field>
@@ -79,7 +80,7 @@ export default function ChurchDetails() {
</div> </div>
</Panel> </Panel>
<Panel title="Service times"> <Panel icon={Clock} title="Service times">
<ul className="space-y-3"> <ul className="space-y-3">
{times.map((t, i) => ( {times.map((t, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[8rem_7rem_1fr_1fr_auto]"> <li key={i} className="grid gap-2 sm:grid-cols-[8rem_7rem_1fr_1fr_auto]">
@@ -95,7 +96,7 @@ export default function ChurchDetails() {
<Btn className="mt-3" onClick={() => set({ serviceTimes: [...times, { day: "sunday", time: "09:00", label: null, campus: null, note: null }] })}>Add a service time</Btn> <Btn className="mt-3" onClick={() => set({ serviceTimes: [...times, { day: "sunday", time: "09:00", label: null, campus: null, note: null }] })}>Add a service time</Btn>
</Panel> </Panel>
<Panel title="Contact and address"> <Panel icon={MapPin} title="Contact and address">
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Email" error={err("contact.email")}><input type="email" className={inputClass} value={c.contact.email ?? ""} onChange={(e) => set({ contact: { ...c.contact, email: e.target.value || null } })} /></Field> <Field label="Email" error={err("contact.email")}><input type="email" className={inputClass} value={c.contact.email ?? ""} onChange={(e) => set({ contact: { ...c.contact, email: e.target.value || null } })} /></Field>
<Field label="Phone" hint="With the country code: +27125550123" error={err("contact.phone")}><input className={inputClass} value={c.contact.phone ?? ""} onChange={(e) => set({ contact: { ...c.contact, phone: e.target.value.replace(/\s+/g, "") || null } })} /></Field> <Field label="Phone" hint="With the country code: +27125550123" error={err("contact.phone")}><input className={inputClass} value={c.contact.phone ?? ""} onChange={(e) => set({ contact: { ...c.contact, phone: e.target.value.replace(/\s+/g, "") || null } })} /></Field>
@@ -108,7 +109,7 @@ export default function ChurchDetails() {
</div> </div>
</Panel> </Panel>
<Panel title="Social links"> <Panel icon={Share2} title="Social links">
<ul className="space-y-2"> <ul className="space-y-2">
{c.social.map((s, i) => ( {c.social.map((s, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[12rem_1fr_auto]"> <li key={i} className="grid gap-2 sm:grid-cols-[12rem_1fr_auto]">
@@ -10,6 +10,7 @@ import { useState } from "react";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media"; import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { CalendarDays } from "lucide-react";
type Ev = { type Ev = {
id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null; id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null;
@@ -94,7 +95,7 @@ export default function Events() {
); );
return ( return (
<> <>
<Title sub={leaderOf ? `You can add and change ${nameOf(leaderOf) ?? "your ministry"}'s events; an editor publishes them.` : "Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked."}>Events</Title> <Title icon={CalendarDays} sub={leaderOf ? `You can add and change ${nameOf(leaderOf) ?? "your ministry"}'s events; an editor publishes them.` : "Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked."}>Events</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6"> <div className="space-y-6">
{mayWrite(null) && ( {mayWrite(null) && (
@@ -3,13 +3,14 @@
import { canEdit } from "@/admin/api"; import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor"; import { ListEditor } from "@/admin/ListEditor";
import { Title, useAdmin } from "@/admin/ui"; import { Title, useAdmin } from "@/admin/ui";
import { Users } from "lucide-react";
/** The team (§6): shown on the Leadership page and the home page's Team section. */ /** The team (§6): shown on the Leadership page and the home page's Team section. */
export default function Leaders() { export default function Leaders() {
const { data } = useAdmin<{ user: { role: string } }>("/me"); const { data } = useAdmin<{ user: { role: string } }>("/me");
return ( return (
<> <>
<Title sub="The people who lead your church. The first is shown largest in the Featured layout.">Leadership</Title> <Title icon={Users} 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={[ <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: "name", label: "Name", kind: "text", max: 120 },
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." }, { key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
@@ -8,6 +8,7 @@
*/ */
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { Btn, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { Link2 } from "lucide-react";
type Product = { installId: string; product: string; url: string; connected: boolean; listed: boolean; showEvents: boolean | null; events: number; lastSyncAt: string | null; lastSyncError: string | null }; type Product = { installId: string; product: string; url: string; connected: boolean; listed: boolean; showEvents: boolean | null; events: number; lastSyncAt: string | null; lastSyncError: string | null };
@@ -22,7 +23,7 @@ export default function Linked() {
const manager = ["owner", "admin"].includes(me.data.user.role); const manager = ["owner", "admin"].includes(me.data.user.role);
return ( return (
<> <>
<Title sub="Your church's other sites. Events can flow between them in either direction.">Linked products</Title> <Title icon={Link2} sub="Your church's other sites. Events can flow between them in either direction.">Linked products</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6"> <div className="space-y-6">
<Panel title="Publish my events"> <Panel title="Publish my events">
@@ -4,6 +4,7 @@ import { useState } from "react";
import { api } from "@/admin/api"; import { api } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media"; import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { Image as ImageIcon } from "lucide-react";
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */ /** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
export default function Media() { export default function Media() {
@@ -17,7 +18,7 @@ export default function Media() {
const s = data.storage; const s = data.storage;
return ( return (
<> <>
<Title sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title> <Title icon={ImageIcon} 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]"> <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<Panel> <Panel>
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
@@ -8,6 +8,7 @@
import { useState } from "react"; import { useState } from "react";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { Mic } from "lucide-react";
type Message = { id: string; title: string; date: string; mediaUrl: string; source: string; speaker: string | null; passage: string | null; notes: string | null; series: string | null; hidden: boolean; published: boolean; thumbnail: string | null }; type Message = { id: string; title: string; date: string; mediaUrl: string; source: string; speaker: string | null; passage: string | null; notes: string | null; series: string | null; hidden: boolean; published: boolean; thumbnail: string | null };
type Data = { youtube: { source: { kind: string; id: string } | null; lastSync: string | null; lastError: string | null }; items: Message[] }; type Data = { youtube: { source: { kind: string; id: string } | null; lastSync: string | null; lastError: string | null }; items: Message[] };
@@ -48,7 +49,7 @@ export default function Messages() {
const yt = data.youtube; const yt = data.youtube;
return ( return (
<> <>
<Title sub="Sermons. Audio and video stay on YouTube or Spotify: nothing is uploaded.">Messages</Title> <Title icon={Mic} sub="Sermons. Audio and video stay on YouTube or Spotify: nothing is uploaded.">Messages</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6"> <div className="space-y-6">
<Panel title="From YouTube, automatically"> <Panel title="From YouTube, automatically">
@@ -3,13 +3,14 @@
import { canEdit } from "@/admin/api"; import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor"; import { ListEditor } from "@/admin/ListEditor";
import { Title, useAdmin } from "@/admin/ui"; import { Title, useAdmin } from "@/admin/ui";
import { HandHeart } from "lucide-react";
/** Ministries (§6): shown on the Ministries page and the home page's Ministries section. */ /** Ministries (§6): shown on the Ministries page and the home page's Ministries section. */
export default function Ministries() { export default function Ministries() {
const { data } = useAdmin<{ user: { role: string } }>("/me"); const { data } = useAdmin<{ user: { role: string } }>("/me");
return ( return (
<> <>
<Title sub="Your ministries' pages. A ministry leader can edit their own; an editor publishes it.">Ministries</Title> <Title icon={HandHeart} 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={[ <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: "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: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
+70 -33
View File
@@ -1,51 +1,88 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { StorageMeter, type Storage } from "@/admin/media"; import { Clock, Globe, HardDrive, History, LayoutGrid, Send } from "lucide-react";
import { Loading, Notice, Panel, Title, useAdmin, when } from "@/admin/ui"; import { StorageMeter, gb, type Storage } from "@/admin/media";
import { NAV_GROUPS } from "@/admin/nav";
import { ActionTile, Loading, Notice, Panel, StatCard, useAdmin, when, type Overview } from "@/admin/ui";
type Overview = { type Full = Overview & {
pending: number;
lastPublished: { number: number; at: string } | null;
storage: Storage; storage: Storage;
colourNotes: string[]; colourNotes: string[];
checklist: { key: string; label: string; done: boolean; href: string | null }[];
recent: { at: string; who: string; action: string; detail: string | null }[]; recent: { at: string; who: string; action: string; detail: string | null }[];
}; };
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */ /**
* The dashboard (§10), as Cross Events': where the site stands in four numbers, a tile for every
* part of the admin, and the latest edits. The steps to a first publish are above every page (Shell).
*/
export default function Dashboard() { export default function Dashboard() {
const { data, error } = useAdmin<Overview>("/overview"); const { data, error } = useAdmin<Full>("/overview");
const me = useAdmin<{ user: { name: string; role: string } }>("/me");
if (!data) return <Loading error={error} />; if (!data) return <Loading error={error} />;
const first = me.data?.user.name.split(/\s+/)[0];
const managers = !!me.data && ["owner", "admin"].includes(me.data.user.role);
const live = !!data.lastPublished;
const stepsLeft = data.checklist.filter((c) => !c.done).length;
return ( return (
<> <>
<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="mb-6">
<div className="grid gap-6 lg:grid-cols-2"> <h1 className="text-2xl font-semibold text-gray-900">Welcome back{first ? `, ${first}` : ""}</h1>
<Panel title="Getting your site ready"> <p className="mt-1 text-sm text-gray-600">{live ? `Your site is live. Last published ${when(data.lastPublished!.at)}.` : "Your site shows Coming soon until you publish it. The steps above get you there."}</p>
<ol className="space-y-3"> </div>
{data.checklist.map((c) => (
<li key={c.key} className="flex items-start gap-3"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<span aria-hidden="true" className={c.done ? "text-green-700" : "text-gray-400"}>{c.done ? "✓" : "○"}</span> <StatCard icon={Globe} label="Your site" value={live ? "Live" : "Coming soon"} tone={live ? "green" : "amber"}
<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> detail={live ? `Version ${data.lastPublished!.number}` : `${stepsLeft} ${stepsLeft === 1 ? "step" : "steps"} to go`} href="/preview/start" linkLabel="Preview it" />
<span className="sr-only">{c.done ? "(done)" : "(to do)"}</span> <StatCard icon={Send} label="Changes not published" value={data.pending} tone={data.pending ? "amber" : "gray"}
</li> detail={data.pending ? "Visitors don't see these yet" : "Visitors see everything you've done"} href="/admin/publish" linkLabel={data.pending ? "Review and publish" : "Publish and history"} />
))} <StatCard icon={HardDrive} label="Storage used" value={`${data.storage.percent}%`} tone={data.storage.percent >= 80 ? "amber" : "brand"}
</ol> detail={`${gb(data.storage.usedBytes)} of ${gb(data.storage.limitBytes)}`} href="/admin/media" linkLabel="Media library" />
<StatCard icon={History} label="Last edit" value={data.recent[0] ? when(data.recent[0].at) : "None yet"} tone="brand"
detail={data.recent[0] ? `By ${data.recent[0].who}` : undefined} href={managers ? "/admin/audit" : undefined} linkLabel="Audit log" />
</div>
{data.pending > 0 && live && (
<div className="mt-6 flex flex-wrap items-center gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4">
<Clock className="h-5 w-5 text-amber-700" aria-hidden />
<p className="flex-1 text-sm text-amber-900">{data.pending} {data.pending === 1 ? "change is" : "changes are"} waiting. Preview them, then publish so visitors see them.</p>
<Link href="/admin/publish" className="rounded-lg bg-brand px-3 py-2 text-sm font-semibold text-brand-on hover:bg-brand-dark">Review and publish</Link>
</div>
)}
<Panel className="my-6" title="Quick actions" icon={LayoutGrid} sub="Everything in the admin, one click away.">
<div className="space-y-5">
{NAV_GROUPS.filter((g) => g.title).map((g) => {
const items = g.items.filter((n) => !n.managers || managers);
if (!items.length) return null;
return (
<div key={g.title}>
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{g.title}</h3>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{items.map((n) => <ActionTile key={n.href} icon={n.icon} title={n.label} description={n.description} href={n.href} />)}
</div>
</div>
);
})}
</div>
</Panel>
<div className="grid gap-6 lg:grid-cols-3">
<Panel className="lg:col-span-2" title="Recent edits" icon={History}>
{data.recent.length === 0 ? <p className="text-sm text-gray-600">None yet.</p> : (
<ul className="divide-y divide-gray-100 text-sm">
{data.recent.map((e, i) => (
<li key={i} className="flex flex-wrap items-baseline justify-between gap-2 py-2">
<span><span className="font-medium">{e.who}</span> {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail && <>: {e.detail}</>}</span>
<span className="text-xs text-gray-500">{when(e.at)}</span>
</li>
))}
</ul>
)}
</Panel> </Panel>
<div className="space-y-6"> <div className="space-y-6">
<Panel title="Waiting to be published"> <Panel title="Storage" icon={HardDrive}><StorageMeter s={data.storage} /></Panel>
{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="Recent edits">
{data.recent.length === 0 ? <p className="text-gray-600">None yet.</p> : (
<ul className="space-y-2 text-sm">
{data.recent.map((e, i) => <li key={i}><span className="font-medium">{e.who}</span> {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail && <>: {e.detail}</>} <span className="text-gray-500">({when(e.at)})</span></li>)}
</ul>
)}
</Panel>
<Panel title="Storage"><StorageMeter s={data.storage} /></Panel>
{data.colourNotes.length > 0 && ( {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> <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>
)} )}
@@ -1,19 +1,27 @@
"use client"; "use client";
/** /**
* One page (§6): its title, address, menu and search engine details, then its content. The home * One page (§6), with its live preview on the right. Content: the home page has one of each
* page has one of each homepage section (their layouts are set under Template and style); every * homepage section (their layouts, order and whether they show are under Template and style); every
* other page is built from blocks, which can be added, moved and removed. * other page is built from blocks, which can be added, moved, hidden and removed. Page details: its
* title, address, menu and search engine details.
*/ */
import Link from "next/link";
import { useParams, useRouter } from "next/navigation"; import { useParams, useRouter } from "next/navigation";
import { useState } from "react"; import { useMemo, useState } from "react";
import {
ArrowDown, ArrowUp, CalendarDays, ChevronDown, ChevronRight, Clock, EyeOff, Eye, FileText, Heart, Image as ImageIcon, LayoutList, Megaphone, Mic,
Plus, Quote, Search, Settings2, Sparkles, Trash2, Type, Users, HandHeart, type LucideIcon,
} from "lucide-react";
import { api } from "@/admin/api"; import { api } from "@/admin/api";
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields"; import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { WithPreview } from "@/admin/LivePreview";
import { ImagePicker } from "@/admin/media"; import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string }; type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] }; type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
type Design = { home: { section: string; hidden: boolean }[] };
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"]; const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
const LISTS: Record<string, string> = { const LISTS: Record<string, string> = {
@@ -23,25 +31,101 @@ const LISTS: Record<string, string> = {
messages: "This page lists your messages; 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.", contact: "This page shows your church's contact details and service times from your church profile.",
}; };
const ICONS: Record<string, LucideIcon> = {
hero: Sparkles, serviceTimes: Clock, welcome: Heart, ministries: HandHeart, team: Users, events: CalendarDays, latestMessage: Mic, invitation: Megaphone,
text: Type, "image-text": ImageIcon, quote: Quote, cta: Megaphone,
};
const BLOCK_ABOUT: Record<string, string> = {
text: "A heading and paragraphs", "image-text": "A photo beside some text, with a button", quote: "Words someone said, and who said them", cta: "A short line and a button to act on",
};
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 }) { /** A line about what a section says now, so it's recognisable folded. */
const summary = (data: Record<string, unknown>) => {
for (const k of ["headline", "heading", "quote", "text", "body"]) {
const v = data[k];
if (typeof v === "string" && v.trim()) return v.trim().split("\n")[0]!.slice(0, 90);
}
return null;
};
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }: {
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>;
onSave: (data: Record<string, unknown>) => Promise<unknown>; hidden?: React.ReactNode; extra?: React.ReactNode;
}) {
const [value, setValue] = useState(initial); const [value, setValue] = useState(initial);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const { busy, message, fields: errors, run } = useAction(); const { busy, message, fields: errors, run } = useAction();
const Icon = ICONS[type] ?? FileText;
const line = summary(initial);
return ( return (
<Panel> <section className={cx("rounded-xl border bg-white shadow-sm", open ? "border-brand/40" : "border-gray-200")}>
<div className="flex items-center justify-between gap-3"> <div className="flex items-center gap-2 p-3">
<h3 className="font-semibold">{title}</h3> <button type="button" onClick={() => setOpen(!open)} aria-expanded={open} className="flex min-w-0 flex-1 items-center gap-3 rounded-lg p-1 text-left hover:bg-gray-50">
<div className="flex gap-2">{extra}<Btn onClick={() => setOpen(!open)} aria-expanded={open}>{open ? "Close" : "Edit"}</Btn></div> <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-2 font-semibold text-gray-900">{title}{hidden}</span>
<span className="block truncate text-xs text-gray-500">{line ?? "Nothing written yet"}</span>
</span>
{open ? <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" aria-hidden /> : <ChevronRight className="h-4 w-4 shrink-0 text-gray-400" aria-hidden />}
<span className="sr-only">{open ? "Close" : "Edit"}</span>
</button>
{extra && <div className="flex shrink-0 gap-1">{extra}</div>}
</div> </div>
{open && ( {open && (
<div className="mt-4 space-y-4"> <div className="space-y-4 border-t border-gray-100 p-4">
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} /> <DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn> <div className="flex flex-wrap items-center gap-3">
{message && <Notice tone={message.tone}>{message.text}</Notice>} <Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
<Btn onClick={() => setOpen(false)}>Close</Btn>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
</div> </div>
)} )}
</Panel> </section>
);
}
function Details({ page, setData }: { page: PageData; setData: (p: PageData) => void }) {
const { id } = useParams<{ id: string }>();
const details = useAction();
const [form, setForm] = useState<Partial<PageData> | null>(null);
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, ifUpdatedAt: page.updatedAt } });
setData(p);
setForm(null);
}, "Saved as a draft.");
return (
<div className="space-y-6">
<Panel title="Title, address and menu" icon={Settings2}>
<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>}
</div>
</Panel>
<Panel title="Search and sharing" icon={Search} sub="What search engines and shared links show for this page.">
<div className="grid gap-4 sm:grid-cols-2">
<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-lg border border-gray-200 bg-gray-50 p-3" aria-label="How it may look in search results">
<p className="text-xs text-gray-500">In search results</p>
<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>
</Panel>
<div className="flex flex-wrap items-center gap-3">
<Btn kind="primary" busy={details.busy} onClick={saveDetails}>Save details</Btn>
{form && <Btn onClick={() => setForm(null)}>Undo</Btn>}
{details.message && <Notice tone={details.message.tone}>{details.message.text}</Notice>}
</div>
</div>
); );
} }
@@ -49,83 +133,86 @@ export default function EditPage() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const router = useRouter(); const router = useRouter();
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`); const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
const details = useAction(); const isHome = page?.kind === "home";
const design = useAdmin<{ design: Design }>(isHome ? "/design" : null);
const blocks = useAction(); const blocks = useAction();
const [form, setForm] = useState<Partial<PageData> | null>(null); const remove = useAction();
const [tab, setTab] = useState<"content" | "details">("content");
// The saved page: when it changes (any save), the preview reloads.
const version = useMemo(() => (page ? JSON.stringify([page.updatedAt, page.slug, page.sections.map((s) => [s.id, s.updatedAt, s.hidden])]) : ""), [page]);
if (!page) return <Loading error={error} />; if (!page) return <Loading error={error} />;
const f = { ...page, ...form }; const path = isHome ? "/" : `/${page.slug}`;
const saveDetails = () => details.run(async () => { const blockCall = (p: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${p}`, { method, body })));
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, ifUpdatedAt: page.updatedAt } });
setData(p); // The home page's sections in the order the site shows them, and whether each shows.
setForm(null); const home = design.data?.design.home ?? HOME_ORDER.map((section) => ({ section, hidden: false }));
}, "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 ( return (
<> <WithPreview path={path} version={version}>
<Title sub={page.kind === "home" ? "Your home page" : `Your site/${page.slug}`} <Link href="/admin/pages" className="mb-1 inline-block text-sm text-gray-500 hover:text-gray-800">← All pages</Link>
actions={page.kind !== "home" && <Btn kind="danger" onClick={() => details.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); })}>Remove page</Btn>}> <Title icon={FileText} sub={isHome ? "Your home page" : `Your site/${page.slug}`}
actions={!isHome && <Btn kind="danger" busy={remove.busy} onClick={() => { if (window.confirm(`Remove “${page.title}”? It goes when you next publish.`)) void remove.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); }); }}><Trash2 className="h-4 w-4" aria-hidden />Remove page</Btn>}>
{page.title} {page.title}
</Title> </Title>
<div className="space-y-6"> {remove.message?.tone === "error" && <div className="mb-4"><Notice tone="error">{remove.message.text}</Notice></div>}
<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" ? ( <Tabs label="This page" value={tab} onChange={setTab} tabs={[
<> { id: "content", label: isHome ? "Sections" : "Content", icon: LayoutList },
<p className="text-sm text-gray-600">Each section&apos;s layout, order and whether it shows are under Template and style.</p> { id: "details", label: "Page details", icon: Settings2 },
{HOME_ORDER.map((type) => { ]} />
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type]!; {/* Both stay mounted, so switching tabs keeps what's not saved yet. */}
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, ifUpdatedAt: s?.updatedAt } }))} />; <div hidden={tab !== "details"}><Details page={page} setData={setData} /></div>
})} <div hidden={tab !== "content"}>
</> {isHome ? (
) : ( <div className="space-y-3">
<> <Notice>Open a section to change what it says. Its layout, its place on the page and whether it shows are under <Link href="/admin/template" className="font-semibold underline">Template and style</Link>.</Notice>
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>} {home.map(({ section: type, hidden }) => {
{page.sections.map((s, i) => { const s = page.sections.find((x) => x.type === type);
const spec = BLOCK_FIELDS[s.type]; const spec = SECTION_FIELDS[type];
if (!spec) return null; if (!spec) return null;
return ( return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}}
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data} hidden={hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Not shown</span>}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
extra={<> })}
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn> </div>
<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> <div className="space-y-3">
<Btn kind="danger" onClick={() => blockCall(`/blocks/${s.id}`, "DELETE")}>Remove</Btn> {LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
</>} /> {page.sections.length === 0 && <p className="rounded-xl border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">Nothing on this page yet: add a block below.</p>}
); {page.sections.map((s, i) => {
})} const spec = BLOCK_FIELDS[s.type];
<Panel title="Add a block"> if (!spec) return null;
<div className="flex flex-wrap gap-2"> return (
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => <Btn key={type} busy={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}>{spec.name}</Btn>)} <SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data}
</div> hidden={s.hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Hidden</span>}
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
</Panel> extra={<>
</> <Btn kind="icon" onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up" title="Move up"><ArrowUp className="h-4 w-4" aria-hidden /></Btn>
)} <Btn kind="icon" onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down" title="Move down"><ArrowDown className="h-4 w-4" aria-hidden /></Btn>
<Btn kind="icon" onClick={() => blockCall(`/blocks/${s.id}`, "PUT", { hidden: !s.hidden })} aria-label={s.hidden ? "Show" : "Hide"} title={s.hidden ? "Show it" : "Hide it"}>{s.hidden ? <Eye className="h-4 w-4" aria-hidden /> : <EyeOff className="h-4 w-4" aria-hidden />}</Btn>
<Btn kind="icon" className="hover:!text-red-700" onClick={() => { if (window.confirm(`Remove this ${spec.name.toLowerCase()} block?`)) void blockCall(`/blocks/${s.id}`, "DELETE"); }} aria-label="Remove" title="Remove"><Trash2 className="h-4 w-4" aria-hidden /></Btn>
</>} />
);
})}
<Panel title="Add a block" icon={Plus} className="!mt-6">
<div className="grid gap-2 sm:grid-cols-2">
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => {
const Icon = ICONS[type] ?? FileText;
return (
<button key={type} type="button" disabled={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}
className="flex items-start gap-3 rounded-lg border border-gray-200 p-3 text-left hover:border-brand/40 hover:bg-brand/5 disabled:opacity-50">
<Icon className="mt-0.5 h-5 w-5 shrink-0 text-brand-text" aria-hidden />
<span><span className="block text-sm font-semibold text-gray-900">{spec.name}</span><span className="block text-xs text-gray-500">{BLOCK_ABOUT[type] ?? ""}</span></span>
</button>
);
})}
</div>
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>}
</Panel>
</div>
)}
</div> </div>
</> </WithPreview>
); );
} }
@@ -3,12 +3,19 @@
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import {
BookOpen, Building2, CalendarDays, ChevronRight, FileText, Gift, HandHeart, Home, Mail, MapPin, Mic, Plus, ShieldCheck, Users, type LucideIcon,
} from "lucide-react";
import { api } from "@/admin/api"; import { api } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; 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 }; 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" }; const KINDS: Record<string, [string, LucideIcon]> = {
home: ["Home", Home], visit: ["Plan your visit", MapPin], about: ["About", Building2], leadership: ["Leadership", Users], ministries: ["Ministries", HandHeart],
events: ["Events", CalendarDays], messages: ["Messages", Mic], give: ["Give", Gift], contact: ["Contact", Mail], terms: ["Terms", BookOpen],
safeguarding: ["Safeguarding", ShieldCheck], custom: ["Your own page", FileText],
};
/** Pages (§6): the fixed ones and the church's own, built from blocks. */ /** Pages (§6): the fixed ones and the church's own, built from blocks. */
export default function Pages() { export default function Pages() {
@@ -24,22 +31,29 @@ export default function Pages() {
}); });
return ( return (
<> <>
<Title sub="Each page is a draft until you publish.">Pages</Title> <Title icon={FileText} sub="Open a page to change what it says, with a live preview beside it. Each change is a draft until you publish.">Pages</Title>
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]"> <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<Panel> <Panel className="!p-2">
<ul className="divide-y divide-gray-200"> <ul className="divide-y divide-gray-100">
{data.map((p) => ( {data.map((p) => {
<li key={p.id} className="flex items-center justify-between gap-3 py-3"> const [kind, Icon] = KINDS[p.kind] ?? [p.kind, FileText];
<div> return (
<Link href={`/admin/pages/${p.id}`} className="font-medium underline-offset-4 hover:underline">{p.title}</Link> <li key={p.id}>
<p className="text-xs text-gray-500">{KINDS[p.kind] ?? p.kind} · {p.path}{!p.inNav && p.kind !== "home" && " · not in the menu"}</p> <Link href={`/admin/pages/${p.id}`} className="group flex items-center gap-3 rounded-lg px-3 py-3 hover:bg-gray-50">
</div> <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span>
<Link href={`/admin/pages/${p.id}`} className="text-sm font-semibold text-brand-text">Edit</Link> <span className="min-w-0 flex-1">
</li> <span className="block font-medium text-gray-900">{p.title}</span>
))} <span className="block truncate text-xs text-gray-500">{kind} · {p.path}</span>
</span>
{p.kind !== "home" && !p.inNav && <span className="hidden rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600 sm:inline">Not in the menu</span>}
<ChevronRight className="h-4 w-4 shrink-0 text-gray-300 group-hover:text-gray-500" aria-hidden />
</Link>
</li>
);
})}
</ul> </ul>
</Panel> </Panel>
<Panel title="Add a page"> <Panel title="Add a page" icon={Plus} sub="Your own page, built from blocks." className="self-start">
<div className="space-y-3"> <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="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> <Field label="Address" hint={`Your site/${slug || "…"}`} error={fields.slug}><input className={inputClass} value={slug} maxLength={80} onChange={(e) => setSlug(e.target.value)} /></Field>
@@ -7,6 +7,7 @@
import { useState } from "react"; import { useState } from "react";
import { api, ROLE_NAMES } from "@/admin/api"; import { api, ROLE_NAMES } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { UserCog } from "lucide-react";
type Person = { id: string; name: string; email: string; role: string; ministryId: string | null; ministry: string | null; lastSignInAt: string | null }; type Person = { id: string; name: string; email: string; role: string; ministryId: string | null; ministry: string | null; lastSignInAt: string | null };
@@ -50,7 +51,7 @@ export default function People() {
const mayTouch = (p: Person) => p.id !== me.data!.user.id && (owner || p.role !== "owner"); const mayTouch = (p: Person) => p.id !== me.data!.user.id && (owner || p.role !== "owner");
return ( return (
<> <>
<Title sub="Who can use this website's admin. They sign in with their church account.">People</Title> <Title icon={UserCog} sub="Who can use this website's admin. They sign in with their church account.">People</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="grid gap-6 lg:grid-cols-[3fr_2fr]"> <div className="grid gap-6 lg:grid-cols-[3fr_2fr]">
<Panel> <Panel>
@@ -8,6 +8,7 @@
import { useState } from "react"; import { useState } from "react";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { History, ListChecks, Send, Share2 } from "lucide-react";
type Change = { key: string; kind: "added" | "changed" | "removed"; what: string; label: string; by: string | null; at: string | null }; 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 Version = { number: number; publishedAt: string; by: string | null; note: string | null };
@@ -31,7 +32,7 @@ export default function Publish() {
return ( return (
<> <>
<Title sub={first ? "Until you publish, visitors see Coming soon." : "Visitors see the last version published."} <Title icon={Send} sub={first ? "Until you publish, visitors see Coming soon." : "Visitors see the last version published."}
actions={<> 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 */} {/* 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> <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>
@@ -40,7 +41,7 @@ export default function Publish() {
</Title> </Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6"> <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"}> <Panel icon={ListChecks} title={pending.data.length ? `${pending.data.length} ${pending.data.length === 1 ? "change" : "changes"} not published` : "Nothing waiting to be published"}>
{pending.data.length > 0 && ( {pending.data.length > 0 && (
<ul className="mb-4 divide-y divide-gray-200"> <ul className="mb-4 divide-y divide-gray-200">
{pending.data.map((c) => ( {pending.data.map((c) => (
@@ -72,7 +73,7 @@ export default function Publish() {
</Panel> </Panel>
{editor && ( {editor && (
<Panel title="Share the preview"> <Panel icon={Share2} 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> <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> <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 && ( {newLink && (
@@ -91,7 +92,7 @@ export default function Publish() {
</Panel> </Panel>
)} )}
<Panel title="History"> <Panel icon={History} title="History">
{versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : ( {versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : (
<ul className="divide-y divide-gray-200"> <ul className="divide-y divide-gray-200">
{versions.data.map((v, i) => ( {versions.data.map((v, i) => (
@@ -8,6 +8,7 @@ import Link from "next/link";
import { useState } from "react"; import { useState } from "react";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { Hourglass, ListOrdered, Search, Settings } from "lucide-react";
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null }; type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
type PageRow = { id: string; kind: string; title: string; inNav: boolean }; type PageRow = { id: string; kind: string; title: string; inNav: boolean };
@@ -30,10 +31,10 @@ export default function SettingsPage() {
}, "Saved as a draft: publish to change the menu."); }, "Saved as a draft: publish to change the menu.");
return ( return (
<> <>
<Title sub="How your site is found, and its menu.">Settings</Title> <Title icon={Settings} sub="How your site is found, and its menu.">Settings</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6"> <fieldset disabled={!editor} className="space-y-6">
<Panel title="Search engines"> <Panel icon={Search} title="Search engines">
<p className="mb-3 text-sm text-gray-600">To see how people find your site, add it to Google Search Console and Bing Webmaster Tools. They give you a code to prove the site is yours: paste it here (the whole tag is fine), save, then press Verify there. This goes live straight away.</p> <p className="mb-3 text-sm text-gray-600">To see how people find your site, add it to Google Search Console and Bing Webmaster Tools. They give you a code to prove the site is yours: paste it here (the whole tag is fine), save, then press Verify there. This goes live straight away.</p>
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Google Search Console code" error={fields.googleVerification}><input className={inputClass} value={s.googleVerification ?? ""} onChange={(e) => setForm({ ...form, googleVerification: e.target.value })} /></Field> <Field label="Google Search Console code" error={fields.googleVerification}><input className={inputClass} value={s.googleVerification ?? ""} onChange={(e) => setForm({ ...form, googleVerification: e.target.value })} /></Field>
@@ -41,7 +42,7 @@ export default function SettingsPage() {
</div> </div>
<p className="mt-3 text-sm text-gray-600">A Google Business Profile helps people find your church on Google Maps: set one up at business.google.com with the same address as your church details.</p> <p className="mt-3 text-sm text-gray-600">A Google Business Profile helps people find your church on Google Maps: set one up at business.google.com with the same address as your church details.</p>
</Panel> </Panel>
<Panel title="Coming soon"> <Panel icon={Hourglass} title="Coming soon">
<Field label="The line under “Coming soon”" hint="Shown until you first publish your site." error={fields.comingSoonText}> <Field label="The line under “Coming soon”" hint="Shown until you first publish your site." error={fields.comingSoonText}>
<input className={inputClass} value={s.comingSoonText} maxLength={300} onChange={(e) => setForm({ ...form, comingSoonText: e.target.value })} /> <input className={inputClass} value={s.comingSoonText} maxLength={300} onChange={(e) => setForm({ ...form, comingSoonText: e.target.value })} />
</Field> </Field>
@@ -49,7 +50,7 @@ export default function SettingsPage() {
{editor && Object.keys(form).length > 0 && ( {editor && Object.keys(form).length > 0 && (
<Btn kind="primary" busy={busy} onClick={() => run(async () => { settings.setData(await api<Settings>("/settings", { method: "PUT", body: form })); setForm({}); }, "Saved.")}>Save settings</Btn> <Btn kind="primary" busy={busy} onClick={() => run(async () => { settings.setData(await api<Settings>("/settings", { method: "PUT", body: form })); setForm({}); }, "Saved.")}>Save settings</Btn>
)} )}
<Panel title="Menu order"> <Panel icon={ListOrdered} title="Menu order">
<p className="mb-3 text-sm text-gray-600">Pages in the menu, in this order. Which pages show is set on each page (<Link href="/admin/pages" className="underline">Pages</Link>).</p> <p className="mb-3 text-sm text-gray-600">Pages in the menu, in this order. Which pages show is set on each page (<Link href="/admin/pages" className="underline">Pages</Link>).</p>
<ul className="divide-y divide-gray-200"> <ul className="divide-y divide-gray-200">
{menu.map((p, i) => ( {menu.map((p, i) => (
@@ -5,8 +5,12 @@
* (recommended first), the homepage order, and the style settings. Fonts and corners are the * (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. * church's brand style, shared with its other sites, so they're set in its church profile.
*/ */
import Link from "next/link";
import { useState } from "react";
import { ArrowDown, ArrowUp, Check, Eye, LayoutTemplate, ListOrdered, Palette, SlidersHorizontal } from "lucide-react";
import { api } from "@/admin/api"; import { api } from "@/admin/api";
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; import { WithPreview } from "@/admin/LivePreview";
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> }; 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[]> }; type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
@@ -42,6 +46,7 @@ const STYLE = [
export default function TemplatePage() { export default function TemplatePage() {
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design"); const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
const { busy, message, run } = useAction(); const { busy, message, run } = useAction();
const [tab, setTab] = useState<"template" | "home" | "style">("template");
if (!data) return <Loading error={error} />; if (!data) return <Loading error={error} />;
const { design, options } = data; const { design, options } = data;
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => { const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
@@ -57,37 +62,48 @@ export default function TemplatePage() {
save({ home }); save({ home });
}; };
return ( return (
<> <WithPreview path="/" version={JSON.stringify(design)}>
<Title sub="Changes here are drafts: preview them, then publish.">Template and style</Title> <Title icon={Palette} sub="How your whole site looks. Changes here are drafts: the preview shows them, then publish.">Template and style</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6"> <Tabs label="Template and style" value={tab} onChange={setTab} tabs={[
<Panel title="Template"> { id: "template", label: "Template", icon: LayoutTemplate },
{ id: "home", label: "Home page layout", icon: ListOrdered },
{ id: "style", label: "Style", icon: SlidersHorizontal },
]} />
{tab === "template" && (
<Panel title="Template" icon={LayoutTemplate} sub="Your content stays the same whichever you choose; only the look changes.">
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2">
{TEMPLATES.map((t) => ( {TEMPLATES.map((t) => {
<div key={t.id} className={cx("rounded-lg border-2 p-4", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200")}> const inUse = t.id === design.template;
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span> return (
<span className="mt-1 block text-sm text-gray-600">{t.text}</span> <div key={t.id} className={cx("rounded-xl border-2 p-4", inUse ? "border-brand bg-brand-tint" : "border-gray-200")}>
{t.id !== design.template && ( <span className="flex items-center justify-between gap-2 font-semibold">{t.name}{inUse && <span className="inline-flex items-center gap-1 rounded-full bg-brand px-2 py-0.5 text-xs text-brand-on"><Check className="h-3 w-3" aria-hidden />In use</span>}</span>
<div className="mt-3 flex flex-wrap gap-2"> <span className="mt-1 block text-sm text-gray-600">{t.text}</span>
<a href={`/preview/start?template=${t.id}`} className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-semibold hover:bg-gray-50">Preview with your content</a> {!inUse && (
<Btn busy={busy} onClick={() => save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}>Use {t.name}</Btn> <div className="mt-3 flex flex-wrap gap-2">
</div> <a href={`/preview/start?template=${t.id}`} className="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white px-3 py-1.5 text-sm font-semibold hover:bg-gray-50"><Eye className="h-4 w-4" aria-hidden />Try it with your content</a>
)} <Btn busy={busy} onClick={() => save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}>Use {t.name}</Btn>
</div> </div>
))} )}
</div>
);
})}
</div> </div>
</Panel> </Panel>
)}
<Panel title="Home page: sections and layouts"> {tab === "home" && (
<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> <Panel title="Home page: sections and layouts" icon={ListOrdered} sub={<>Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best. What each section says is on the home page, under Pages.</>}>
<ul className="divide-y divide-gray-200"> <ul className="divide-y divide-gray-100">
{design.home.map((e, i) => { {design.home.map((e, i) => {
const recommended = options.variants[design.template]?.[e.section] ?? []; const recommended = options.variants[design.template]?.[e.section] ?? [];
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))]; const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
return ( return (
<li key={e.section} className="flex flex-wrap items-center gap-3 py-3"> <li key={e.section} className={cx("flex flex-wrap items-center gap-3 py-3", e.hidden && "opacity-60")}>
<span className="w-40 font-medium">{SECTIONS[e.section]}</span> <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-100 text-xs font-semibold text-gray-600" aria-hidden>{i + 1}</span>
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-56`} value={design.variants[e.section]} disabled={busy} <span className="w-36 font-medium">{SECTIONS[e.section]}</span>
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-52`} value={design.variants[e.section]} disabled={busy}
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}> 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>)} {ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
</select> </select>
@@ -96,33 +112,35 @@ export default function TemplatePage() {
Show Show
</label> </label>
<span className="ml-auto flex gap-1"> <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 kind="icon" onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${SECTIONS[e.section]} up`} title="Move up"><ArrowUp className="h-4 w-4" aria-hidden /></Btn>
<Btn onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`}>↓</Btn> <Btn kind="icon" onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`} title="Move down"><ArrowDown className="h-4 w-4" aria-hidden /></Btn>
</span> </span>
</li> </li>
); );
})} })}
</ul> </ul>
</Panel> </Panel>
)}
<Panel title="Style"> {tab === "style" && (
<Panel title="Style" icon={SlidersHorizontal} sub="The finishing touches, on every page.">
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Header"> <Field label="Header">
<select className={inputClass} value={design.style.header} disabled={busy} onChange={(e) => save({ style: { header: e.target.value } })}> <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>)} {(options.headers[design.template] ?? []).map((h) => <option key={h} value={h}>{HEADER_NAMES[h] ?? h}</option>)}
</select> </select>
</Field> </Field>
{STYLE.map((s) => ( {STYLE.map((st) => (
<Field key={s.key} label={s.label}> <Field key={st.key} label={st.label}>
<select className={inputClass} value={design.style[s.key]} disabled={busy} onChange={(e) => save({ style: { [s.key]: e.target.value } })}> <select className={inputClass} value={design.style[st.key]} disabled={busy} onChange={(e) => save({ style: { [st.key]: e.target.value } })}>
{Object.entries(s.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)} {Object.entries(st.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select> </select>
</Field> </Field>
))} ))}
</div> </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> <p className="mt-4 text-sm text-gray-600">Colours, fonts and corners are your church&apos;s brand style, shared with your Events and sign-in pages: change them in <Link href="/admin/church" className="font-semibold underline">Church details</Link>.</p>
</Panel> </Panel>
</div> )}
</> </WithPreview>
); );
} }
@@ -7,7 +7,9 @@ import { localRedirect } from "@/lib/localRedirect";
* on every page (site/preview), so it shows nothing to anyone else. * on every page (site/preview), so it shows nothing to anyone else.
*/ */
export function GET(request: NextRequest) { export function GET(request: NextRequest) {
const res = localRedirect("/"); // ?to=/about: straight to the page being edited (the editor's "Open the full preview"). A page of the site only.
const to = request.nextUrl.searchParams.get("to") ?? "/";
const res = localRedirect(/^\/(?!\/|\\|admin|api|preview)[A-Za-z0-9\-/]*$/.test(to) ? to : "/");
const opts = { httpOnly: true, sameSite: "lax" as const, secure: process.env.NODE_ENV === "production", path: "/" }; const opts = { httpOnly: true, sameSite: "lax" as const, secure: process.env.NODE_ENV === "production", path: "/" };
res.cookies.set("ccw_preview", "admin", opts); res.cookies.set("ccw_preview", "admin", opts);
// "Choose your template": the church's own content in another template, nothing saved. // "Choose your template": the church's own content in another template, nothing saved.
+17 -1
View File
@@ -13,8 +13,24 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
// Only the browser knows whether this page is inside the width frame. // Only the browser knows whether this page is inside the width frame.
const framed = window.self !== window.top;
// eslint-disable-next-line react-hooks/set-state-in-effect // eslint-disable-next-line react-hooks/set-state-in-effect
setInFrame(window.self !== window.top); setInFrame(framed);
if (!framed) return;
// In a frame (the admin's live preview), a link is a full page load: the frame's page loads are
// what show the working copy (site/load.ts), and the client-side ones aren't.
const onClick = (e: MouseEvent) => {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const a = (e.target as Element | null)?.closest?.("a");
if (!a || (a.target && a.target !== "_self") || a.hasAttribute("download")) return;
const url = new URL(a.href, window.location.href);
if (url.origin !== window.location.origin || (url.pathname === window.location.pathname && url.hash)) return;
e.preventDefault();
e.stopPropagation();
window.location.assign(url.href);
};
document.addEventListener("click", onClick, true);
return () => document.removeEventListener("click", onClick, true);
}, []); }, []);
if (inFrame) return null; if (inFrame) return null;
const publish = async () => { const publish = async () => {
+5 -2
View File
@@ -1,4 +1,4 @@
import { cookies } from "next/headers"; import { cookies, headers } from "next/headers";
import { cache } from "react"; import { cache } from "react";
import type { Image, Published, SiteContent, Template } from "./types"; import type { Image, Published, SiteContent, Template } from "./types";
@@ -20,8 +20,11 @@ const FALLBACK: SiteContent = {
*/ */
export const loadContent = cache(async (): Promise<SiteContent> => { 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. // Previewing (§4): the working copy, if the backend agrees this is an admin or a live share link.
// The admin's live preview beside its editors is the site in a frame: a signed-in admin's framed
// page is the working copy too, without the cookie (which would turn the whole browser to preview).
const jar = await cookies(); const jar = await cookies();
const preview = jar.get("ccw_preview")?.value; const framed = (await headers()).get("sec-fetch-dest") === "iframe" && jar.has("ccw_session");
const preview = jar.get("ccw_preview")?.value ?? (framed ? "admin" : undefined);
if (preview) { if (preview) {
try { try {
const session = jar.get("ccw_session")?.value; const session = jar.get("ccw_session")?.value;
+10 -3
View File
@@ -11,8 +11,8 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released | | What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------| |------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 | | Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.0.2** | `website@1.0.2` | 2026-11-26 | | Church Website | `crosscode-platform` (`apps/website`) | **1.1.0** | `website@1.1.0` | 2026-11-26 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.1** | `accounts@1.7.1` | 2026-11-26 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 | | Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 | | Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
| Cross Code Hub | `events-hub` | **2.23.1** | `v2.23.1` | 2026-11-26 | | Cross Code Hub | `events-hub` | **2.23.1** | `v2.23.1` | 2026-11-26 |
@@ -30,7 +30,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) | | `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) | | `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) | | `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 1.0.2 (1.0.0–1.0.2 released 2026-11-26; installed for the demo church cross-demo2 (1.0.1) only, Hope Family Church next) | | Website | `apps/website` | 1.1.0 (1.0.0–1.1.0 released 2026-11-26; installed for the demo church cross-demo2 (1.0.1) only, Hope Family Church next) |
| App | `apps/app` | 0.0.0 (not started, phase 6) | | App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -38,6 +38,13 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for ## What each latest release was for
- **Accounts 1.8.0 + Church Website 1.1.0 (2026-11-26):** both admins redesigned as Cross Events' admin
dashboard and settings. Accounts: `/admin` is an overview, People moved to `/admin/people`, a
grouped sidebar showing the part you're in. Website: an icon sidebar, a dashboard, steps to the
first publish across the top, and a live preview beside the page editor (drafts for a framed
request with an admin session, no preview cookie). No migrations, no backend changes. Checked:
typechecks and lint, the Website's e2e (10, with axe on the admin and the editor) and Accounts' e2e
(11). **Not deployed yet.**
- **Accounts 1.7.1 + Church Website 1.0.2 + Cross Events 3.7.1 (2026-11-26):** found installing - **Accounts 1.7.1 + Church Website 1.0.2 + Cross Events 3.7.1 (2026-11-26):** found installing
the Website for cross-demo2. All three: a connect involving an install that isn't in the cached the Website for cross-demo2. All three: a connect involving an install that isn't in the cached
copy of the Hub's list yet asks the Hub for a fresh one (one heartbeat, at most once a minute) copy of the Hub's list yet asks the Hub for a fresh one (one heartbeat, at most once a minute)
+5 -4
View File
@@ -51,7 +51,7 @@
}, },
"apps/accounts/backend": { "apps/accounts/backend": {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.7.1", "version": "1.8.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
@@ -88,7 +88,7 @@
}, },
"apps/accounts/frontend": { "apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.7.1", "version": "1.8.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/ui": "*", "@crosscode/ui": "*",
@@ -360,7 +360,7 @@
}, },
"apps/website/backend": { "apps/website/backend": {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.0.2", "version": "1.1.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/auth-client": "*", "@crosscode/auth-client": "*",
@@ -387,11 +387,12 @@
}, },
"apps/website/frontend": { "apps/website/frontend": {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.0.2", "version": "1.1.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/seo": "*", "@crosscode/seo": "*",
"@crosscode/ui": "*", "@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6", "next": "^16.4.6",
"react": "^19.3.1", "react": "^19.3.1",
"react-dom": "^19.3.1" "react-dom": "^19.3.1"