Compare commits

...
Author SHA1 Message Date
joshua d3e04127f3 Merge branch 'feat/website-demo-seeds' 2026-11-27 09:30:15 +02:00
joshuaandClaude Opus 5.5 2fb7ac57da Website 1.3.0, agent 1.6.0, contracts 1.19.0: demo data for the Church Website
Eight demo churches, two per template (the second on the template's other
recommended variants and header), loaded from the Hub on demo sites with
`crosscode demo <church> website --profile <p>`. A profile replaces the
content only: the church's profile from Accounts, the site settings, the
site icon and the admins stay, and the copy names the church.

- contracts: WEBSITE_DEMO_PROFILES, DEMO_PRODUCTS, SEED_WEBSITE_DEMO_MIN_AGENT;
  seed-demo takes an optional product (events by default)
- agent: a Website seed-demo job runs `crosscode demo <church> website`
- crosscode script: backup, demo as the site's user, reload, health check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:20:09 +02:00
joshua 81c01d8a9f Merge branch 'docs/deployed-hub-2.24.1-website-1.2.0' 2026-11-27 08:44:56 +02:00
joshuaandClaude Opus 5.5 2335fd46e4 docs: Hub 2.24.1 deployed, Website 1.2.0 on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:44:55 +02:00
joshua f58711603a Merge branch 'docs/hub-2.24.1' 2026-11-27 08:36:19 +02:00
joshuaandClaude Opus 5.5 d1354a6a17 docs: Hub 2.24.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:36:18 +02:00
joshua 175a6b41eb Merge branch 'docs/hub-2.24.0' 2026-11-27 08:30:15 +02:00
joshuaandClaude Opus 5.5 80d8e903dd docs: Hub 2.24.0 deployed (Website 1.2.0 not on cross-demo2 yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:30:15 +02:00
joshua 35501deb0d Merge branch 'fix/website-starter-pages' 2026-11-27 08:18:53 +02:00
joshuaandClaude Opus 5.5 79e1450df6 Website 1.2.0: starter pages on a new install, and a site icon
A new install had no pages, so the home page and its live preview showed
only the header and footer (found on cross-demo2). The backend now adds the
fixed pages with starter text at startup. Settings -> Site icon sets the
favicon, with a default from the church's colour and initial. The Latest
message's Card layout has its name; the media picker's placeholder has
enough contrast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:18:47 +02:00
joshua 6905a19c8c Merge branch 'feat/admin-redesign' 2026-11-26 19:57:23 +02:00
joshuaandClaude Opus 5.5 dcc22a5c16 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>
2026-11-26 19:57:22 +02:00
joshua e6c91c3705 Merge branch 'docs/deployed-cross-demo2' 2026-11-26 16:18:45 +02:00
joshuaandClaude Opus 5.5 925b5fbd8b docs: Accounts 1.7.1, Website 1.0.2, Events 3.7.1 deployed on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:18:44 +02:00
joshua 58cadbf472 Merge branch 'fix/link-after-install' 2026-11-26 16:14:20 +02:00
joshuaandClaude Opus 5.5 f6a536ad64 Accounts 1.7.1, Website 1.0.2, Events 3.7.1: link right after an install; Preview behind the proxy
Found installing 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 list (one heartbeat, at
  most once a minute) instead of refusing. A new Website's admin couldn't
  sign in for up to 30 minutes.
- Accounts: a heartbeat on every start.
- Website: /admin links to Accounts on the spot (at most every 15 s), one
  connect to Accounts at a time, and the problem page says "not linked
  yet" (ACCOUNTS_NOT_LINKED). Preview redirected to the server's own
  http://localhost:<web port>: the preview routes now answer with a
  relative Location.
- Events: a new Website can connect for the event feed straight away.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:14:20 +02:00
joshua 05d808b74c Merge branch 'docs/hub-2.23.1' 2026-11-26 15:27:27 +02:00
joshuaandClaude Opus 5.5 20a23a3ba8 docs: Hub 2.23.1 deployed (Accounts version from the heartbeat)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:27:26 +02:00
joshua 9c9c96dd2c Merge branch 'docs/hub-2.23.0' 2026-11-26 15:11:58 +02:00
joshuaandClaude Opus 5.5 f73761f956 docs: Hub 2.23.0 deployed (requirements carry forward)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:11:57 +02:00
joshua 62441ad437 Merge branch 'docs/site-1.7.0' 2026-11-26 14:38:00 +02:00
joshuaandClaude Opus 5.5 7814a64cf7 docs: crosscode-site 1.7.0 released (the Website on sale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:37:59 +02:00
joshua 679f61febf Merge branch 'fix/website-1.0.1' 2026-11-26 14:36:35 +02:00
joshuaandClaude Opus 5.5 723bb15a5e website 1.0.1: thumbnails from the site, Calendar dates
- The messages' YouTube thumbnails are served from the site
  (/api/thumbnails/<id>.jpg): the backend fetches a message's thumbnail
  once and keeps it in uploads/.thumbnails (only the site's own videos,
  only a JPEG), so visitors ask nothing of YouTube before pressing play.
  The messages page preloads the first one (its LCP: Heritage 89 -> 95).
- Calendar events' dates read "Sun · November", not
  "Sun (month: November)".
- e2e: no request to YouTube or Spotify before play; the variant
  screenshots round section heights to whole pixels (a one-pixel flake);
  the e2e thumbnail is one of the demo's illustrations.
- crosscode script: a Website's export leaves out uploads/.thumbnails.
- docs: release checks on 1.0.1, VERSIONS, handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:36:34 +02:00
joshua dd0e5e17b3 Merge branch 'docs/website-release-checks' 2026-11-26 12:03:10 +02:00
joshuaandClaude Opus 5.5 7216035e49 docs: website release checks run again on the release build
Variants: axe passes everywhere, all 104 baselines taken (67 new to look
through). Lighthouse 11 of 12 (Heritage messages 89, the YouTube
thumbnail as LCP). Found: Calendar dates print "Sun (month: November)".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:03:10 +02:00
101 changed files with 3089 additions and 542 deletions
+54
View File
@@ -2,6 +2,60 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27
Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job
means what it did. Details in each app's CHANGELOG.md. No migrations.
- **contracts 1.19.0:** `agent.WEBSITE_DEMO_PROFILES` (eight, two per template:
`heritage-parish`, `heritage-city`, `bold-youth`, `bold-plant`, `community-family`,
`community-town`, `clean-modern`, `clean-campus`), `DEMO_PRODUCTS`, `DEMO_PROFILES_BY_PRODUCT`,
`SEED_WEBSITE_DEMO_MIN_AGENT` (1.6.0). `seed-demo` args take an optional `product` (`events`,
the default, or `website`); the profile must be one of that product's, and a Website demo takes
no `adminEmail`.
- **agent 1.6.0:** a Website `seed-demo` job runs `crosscode demo <church> website --profile <p>`.
- **website 1.3.0:** the eight demo churches (`backend/src/demo/seeds.ts`,
`npm run demo -- --profile <p>`, `--list`). They replace the content only: the church's profile
from Accounts, the site settings, the site icon and the admins stay, and the copy names the
church. `--template` alone is still the Acacia Hill development church.
- **crosscode script:** `crosscode demo <church> website --profile <p>`: backup, the demo as the
site's user (`--force`), reload, wait for `/api/health`. Refused on a Website release without
the profiles (before 1.3.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
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
- **Linking right after an install** (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 list (one heartbeat, at most once a
minute) instead of refusing. Before, a new product and its siblings only learned of each other at
their 15-minute heartbeats, so a new Website's admin couldn't sign in for up to 30 minutes.
- **Accounts 1.7.1:** also a heartbeat on every start.
- **Website 1.0.2:** opening `/admin` without a link to Accounts links on the spot; the problem page
says "not linked yet" (`ACCOUNTS_NOT_LINKED`) instead of "can't reach your sign-in". Preview no
longer redirects to the server's own `http://localhost:<web port>` (relative redirects).
- **Events 3.7.1:** a new Website can connect for the event feed straight away.
## website@1.0.1 + crosscode script - 2026-11-26
Details in `apps/website/CHANGELOG.md`.
- **Website 1.0.1:** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`), so visitors ask nothing of YouTube until they press play; the
Calendar events' dates read "Sun · November", not "Sun (month: November)". No migration.
- **crosscode script:** a Website's export leaves out `uploads/.thumbnails` (the kept thumbnails).
## contracts@1.18.0 - 2026-11-25
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
+35
View File
@@ -1,5 +1,40 @@
# 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
No migrations, no new settings.
### Fixed
- **A product installed after Accounts' last heartbeat links straight away.** Accounts accepted a
connect only from installs in its cached copy of the Hub's list, which it refreshed every 15
minutes. A new Church Website (or Events) was refused ("doesn't know that install yet") and tried
again only at its own next heartbeat, so its admin couldn't sign in for up to 30 minutes after the
install (found on cross-demo2). Now, for an install it doesn't know, Accounts sends the Hub a
heartbeat to get a fresh list and looks again (at most one such heartbeat a minute, so unknown
installs can't make it call the Hub more often). The same applies when an Accounts admin connects.
- **A heartbeat on every start**, not only the first: after a restart the list of the church's
products is fresh at once.
## [1.7.0] - 2026-11-24
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
+12
View File
@@ -3,6 +3,18 @@
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).
## 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
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
for your church can be signed in to within moments, instead of after up to half an hour.
## 1.7.0
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.7.0",
"version": "1.8.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
+3 -1
View File
@@ -23,8 +23,10 @@ async function main() {
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
const stopJobs = await startJobs(ctx, url);
// 1.7.1: a heartbeat on every start, not only the first (as the Website), so the list of the
// church's products is fresh after a restart.
connectFromEnv(ctx).then((r) => {
if (r.connected) heartbeat(ctx).catch(() => {});
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
+28 -4
View File
@@ -11,6 +11,7 @@ import {
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { heartbeat } from '../hub/client.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, listedProduct } from './store.js';
@@ -24,6 +25,29 @@ export class LinkError extends Error {
/** Products that sign people in through Accounts. */
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after Accounts' last heartbeat), Accounts asks the Hub for a fresh list with a heartbeat and looks
* again, so a new Website links straight away instead of up to 30 minutes later. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make Accounts call the Hub
* more often than that.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
r = { at: now, run: heartbeat(ctx).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
return listedProduct(ctx, installId);
}
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
@@ -55,8 +79,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -86,9 +110,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(ctx, m.from.installId);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (Accounts asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -2,6 +2,8 @@
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
// church profile, Connect, and admin and setup rules.
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, beforeEach, describe, test } from 'node:test';
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
@@ -156,6 +158,44 @@ describe('Connect from a product', () => {
const client = await h.provider.Client.find(APP_ID);
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
});
test('1.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const own = await startHarness({ now: () => clock });
const appKey = generateEd25519();
const NEW_ID = '5c1d7e2f-8a3b-4c4d-9e5f-6a7b8c9d0e1f';
const listed = { product: 'website', installId: NEW_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) };
// A Hub whose list has the new Website; Accounts' cached list doesn't yet.
const hubCalls: string[] = [];
const hub = http.createServer((req, res) => {
hubCalls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: [listed] }));
});
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', () => r()));
try {
own.ctx.config.hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
await own.ctx.settings.setMany({ hub_install_secret: 'secret', hub_linked_products: '[]' });
const msg = (installId: string) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'website', installId, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: clock.toISOString(), nonce: newLinkNonce() }, appKey.privateKeyPem);
const send = (installId: string) => fetch(`${own.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(installId)) });
assert.equal((await send(NEW_ID)).status, 200, 'linked at once');
assert.deepEqual(hubCalls, ['/api/installs/heartbeat']);
assert.equal(await own.db.productLink.count({ where: { installId: NEW_ID } }), 1);
// An install the Hub doesn't list: refused, and within the minute the Hub isn't asked again.
const UNKNOWN = '7e3f9a4b-0c5d-4e6f-8a7b-9c0d1e2f3a4b';
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 1);
clock = new Date(clock.getTime() + 61_000);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 2);
} finally {
await new Promise((r) => hub.close(r));
await own.close();
}
});
});
describe('admin and setup', () => {
+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.getByRole("button", { name: "Turn on" }).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.getByText("thandi@hope.test")).toBeVisible();
// 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",
"version": "1.7.0",
"version": "1.8.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"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 { Button, Checkbox, Field, Notice } from "@crosscode/ui";
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 { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -62,7 +62,7 @@ export function Account({ section = "overview" }: { section?: AccountSection })
const first = me.name.split(" ")[0] || me.name;
return (
<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>}
{section === "overview" && <Overview me={me} />}
{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 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 { 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 { Card, Heading } from "@/components/Panel";
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 [allowed, setAllowed] = useState<boolean | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const [waiting, setWaiting] = useState(0);
useExternalEffect(() => {
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 (who.ok) setMe(who.data);
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; };
}, [s.path]);
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) {
return (
@@ -50,16 +58,20 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
}
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub}>{s.title}</PageTitle>
<AppShell me={me} active={s.path} badges={badges}>
<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>}
{section === "overview" && <Overview />}
{section === "people" && <People flash={flash} />}
<div className="max-w-3xl">
{section === "deletions" && <Deletions flash={flash} />}
<div className="max-w-3xl space-y-6">
{section === "deletions" && <Deletions flash={flash} onChange={setWaiting} />}
{section === "church" && <><Church flash={flash} /><BrandStyle 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 === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{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} 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 === "backups" && <Backups 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 ──────────────────────────────────────────────────────────────────
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 }[] };
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 }) {
const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
@@ -94,28 +213,47 @@ function People({ flash }: { flash: Flash }) {
};
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>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 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" />
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-3 flex gap-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>
</form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
<ul className="divide-y">
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} {list?.total === 1 ? "person" : "people"}</p>
<ul className="-mx-2 divide-y">
{list?.items.map((p) => (
<li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
<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>
<span className="block text-sm text-gray-500">{p.email}</span>
<button type="button" onClick={() => show(p.id)} aria-current={open?.id === p.id ? "true" : undefined}
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="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>
</li>
))}
</ul>
</Card>
{open && (
<Card>
<Heading sub={open.email}>{open.name}</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
{open ? (
<Card className="lg:sticky lg:top-20">
<div className="mb-4 flex items-center gap-3">
<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">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>
@@ -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.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={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>
<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>
<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>
) : (
<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>
);
@@ -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 } };
function Deletions({ flash }: { flash: Flash }) {
function Deletions({ flash, onChange }: { flash: Flash; onChange: (waiting: number) => void }) {
const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => {
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]);
return (
<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>}
<ul className="divide-y">
{items.map((d) => (
@@ -189,7 +333,8 @@ function Church({ flash }: { flash: Flash }) {
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return (
<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) => {
e.preventDefault();
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>;
return (
<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.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<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"],
};
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);
useExternalEffect(() => {
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 };
return (
<Card>
<Heading icon={icon} sub={sub}>{title}</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
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) ?? "");
}
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) => {
const [label, kind] = SETTING_LABELS[k]!;
@@ -318,7 +464,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
return (
<div className="space-y-6">
<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 && (
<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.{" "}
@@ -339,7 +485,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
</form>
</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>
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
</Card>
@@ -357,7 +503,7 @@ function Licence({ flash }: { flash: Flash }) {
if (!s) return <p className="text-gray-600">Loading…</p>;
return (
<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">
<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>
@@ -388,7 +534,7 @@ function Audit() {
}, []);
return (
<Card>
<Heading>Audit log</Heading>
<Heading icon={<ScrollText className="h-4 w-4" />}>Audit log</Heading>
<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.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" };
}
/** 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 }> }) {
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} />;
}
@@ -3,5 +3,5 @@ import { Admin } from "./Admin";
export const metadata = { title: "Admin" };
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). */
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[] = [
{ href: "/account", label: "Overview", icon: LayoutDashboard },
@@ -22,19 +22,21 @@ export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account/activity", label: "Activity", icon: Activity },
];
export const ADMIN_NAV: NavItem[] = [
{ href: "/admin", label: "People", icon: Users },
{ href: "/admin/deletions", label: "Deletion requests", icon: UserX },
{ 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 },
{ 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 },
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
/** 1.8.0: the admin's sections in groups, as Cross Events' settings, with the overview first. */
export const ADMIN_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ title: null, items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
{ title: "People", items: [{ href: "/admin/people", label: "People", icon: Users }, { href: "/admin/deletions", label: "Deletion requests", icon: UserX }] },
{ title: "Church", items: [{ href: "/admin/church", label: "Church profile", icon: Building2 }, { href: "/admin/linked", label: "Linked products", icon: Link2 }] },
{
title: "Signing in",
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 }],
},
{
title: "System",
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. */
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>;
}
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 (
<div className="mb-6">
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-400">{title}</p>
<nav className="space-y-1" aria-label={title}>
{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>
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Your account</p>
<nav aria-label="Your account"><NavLinks items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /></nav>
</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 (
<>
<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} />
</div>
</div>
<NavList title="Your account" items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} />
{me.role === "admin" && <NavList title="Admin" items={ADMIN_NAV} active={active} onNavigate={onNavigate} />}
{(both || !inAdmin) && <AccountNav 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.
* 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 [open, setOpen] = useState(false);
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)} />
<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>
<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">
<LogOut className="h-4 w-4" aria-hidden /> Sign out
</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">
{me && (
<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>
)}
<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. */
export function PageTitle({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
/** 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, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: LucideIcon }) {
return (
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
<div className="mb-6 flex items-start gap-3">
{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>}
<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>
);
}
+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 = {
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." },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account." },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites." },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here." },
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." },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
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." },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
overview: { path: "/admin", title: "Admin", sub: "How Accounts stands, what needs you, and every setting.", tile: "" },
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" },
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" },
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" },
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" },
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" },
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" },
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" },
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" },
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" },
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;
export type AdminSection = keyof typeof ADMIN_SECTIONS;
+6
View File
@@ -13,6 +13,12 @@ Write for the person updating servers: what the agent can now do from the Hub, a
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.6.0
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
eight demo churches on a demo site, as it already could for Cross Events. Needs Website 1.3.0 on
the site. Cross Events' demo data works as before.
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.6.0",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
+3 -1
View File
@@ -59,7 +59,9 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
return ["demo", job.args.church, ...(job.args.product === "website" ? ["website"] : []), "--profile", job.args.profile,
...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.5.0";
export const AGENT_VERSION = "1.6.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+3
View File
@@ -47,6 +47,9 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
// 1.6.0: the Website's demo.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
+13
View File
@@ -5,6 +5,19 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/).
## [3.7.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after this site's last heartbeat can connect straight away.** A connect
(in either direction) was refused while the other install wasn't in the cached copy of the Hub's
list, refreshed every 15 minutes. So a new Church Website couldn't connect for the event feed
until then. Now, for an install it doesn't know, the site sends the Hub a heartbeat to get a fresh
list and looks again (at most one such heartbeat a minute, so unknown installs can't make it call
the Hub more often). Same change as Accounts 1.7.1 and Website 1.0.2.
## [3.7.0] - 2026-11-24
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
+5
View File
@@ -12,6 +12,11 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.7.1
- **Connecting to your new Church Website works straight away**, so its events page can show your
Cross Events events as soon as it's installed, instead of after up to 15 minutes.
## 3.7.0 — requires accounts 1.7.0
- **Your public pages look like the rest of your church's sites.** With sign-in through your
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.0",
"version": "3.7.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+32 -4
View File
@@ -35,6 +35,34 @@ export class LinkError extends Error {
}
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
let refresh: { at: number; run: Promise<unknown> } | null = null;
/** For tests. */
export function forgetRefresh(): void {
refresh = null;
}
/**
* 3.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat, like a new Church Website), the site asks the Hub for a fresh
* list with a heartbeat and looks again, instead of refusing for up to 15 minutes. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make this site call the
* Hub more often than that.
*/
async function listedOrRefreshed(installId: string, now: Date) {
const found = await listedProduct(installId);
if (found) return found;
if (!refresh || now.getTime() - refresh.at >= REFRESH_EVERY_MS) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS, and hub/client.js needs this module's siblings
const run = Promise.resolve().then(() => require('../hub/client').heartbeat())
.catch((e: Error) => console.warn('[links] Asking the Hub for a fresh list failed:', e?.message || e));
refresh = { at: now.getTime(), run };
}
await refresh.run;
return listedProduct(installId);
}
type Self = { installId: string; url: string; privateKeyPem: string };
@@ -81,8 +109,8 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(installId, now);
if (!sibling) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -123,9 +151,9 @@ export async function acceptConnect(body: unknown, ip: string | null, now = new
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(m.from.installId);
const sibling = await listedOrRefreshed(m.from.installId, now);
if (!sibling || sibling.product !== m.from.product) {
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (this site asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -87,6 +87,7 @@ const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
async function setUpSite({ linked = true } = {}) {
db.reset();
store.forgetKeyPair();
connect.forgetRefresh();
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
@@ -286,6 +287,29 @@ describe('Connect from a linked product', () => {
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
});
test('3.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
await store.saveLinkedProducts([]);
const hubClient = require('../src/hub/client');
let listed = [{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }];
const spy = jest.spyOn(hubClient, 'heartbeat').mockImplementation(async () => { await store.saveLinkedProducts(listed); return { ok: true }; });
try {
await connect.acceptConnect(connectMessage(), null, new Date());
expect(spy).toHaveBeenCalledTimes(1);
expect(db.t.productLink.get(WEBSITE_ID)).toMatchObject({ product: 'website' });
// An install the Hub doesn't list: refused, and the Hub isn't asked again within the minute.
listed = [];
await store.saveLinkedProducts([]);
const t = new Date();
await expect(connect.acceptConnect(connectMessage(), null, t)).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(1);
await expect(connect.acceptConnect(connectMessage(), null, new Date(t.getTime() + 61_000))).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(2);
} finally {
spy.mockRestore();
}
});
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
await connect.acceptConnect(connectMessage(), null);
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.0",
"version": "3.7.1",
"private": true,
"scripts": {
"dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.7.0",
"version": "3.7.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+121
View File
@@ -1,5 +1,126 @@
# Changelog — Church Website
## [1.3.0] — 2026-11-27
No migration, no new environment settings. Needs contracts 1.19.0 (in this checkout).
### Added
- **Eight demo churches**, two per template, for the Hub's demo sites (Hub 2.25.0, agent 1.6.0,
`crosscode demo <church> website --profile <p>`): `heritage-parish`, `heritage-city`,
`bold-youth`, `bold-plant`, `community-family`, `community-town`, `clean-modern`,
`clean-campus` (`src/demo/seeds.ts`, ids from contracts `agent.WEBSITE_DEMO_PROFILES`). Each is
its own kind of church: home page, Plan your visit, About, Give, four ministries, four leaders, a
message series with three messages, and three upcoming events. The second of each template starts
on the template's second recommended variant of every homepage section and its second header, so
the eight show every recommended look.
- **They keep the organisation settings:** a profile replaces the content only. The church's
profile (from Accounts, else `church_profile_local`) stays, the copy names the church
(`{name}`, `{short}`, `{city}`) and the illustrations use its colours. The site settings, the
site icon (`favicon_media_id` and its picture) and the admins stay. Acacia Hill's profile is
saved only on a site with no profile at all, so it still has a name. Slug history and preview
links go with the old content.
- `npm run demo -- --profile <p> [--force]` and `--list`. `--template <t>` alone still loads the
Acacia Hill development church exactly as before (its profile too), so the e2e suite and its
screenshots are unchanged.
## [1.2.0] — 2026-11-27
No migration, no new environment settings. Its first start on an existing site adds the missing
fixed pages (below).
### Fixed
- **A new install had no pages**, so its home page (and the live preview of it) showed only the
header and footer whatever was chosen under Template and style, and Plan your visit, About, Give,
Contact and the rest didn't exist. Only `npm run demo` made pages. Now the backend adds the fixed
pages at startup (`src/site/starter.ts`) with starter text: Home with every homepage section,
Plan your visit, About us, Ministries, Leadership, Events, Messages, Give, Contact, and Terms and
Safeguarding (footer links, not in the menu; WEBSITE-1.0-PLAN §2). All of them while a site has
none of them (pages it made itself move after them; an address already taken is skipped), else
only a missing home page. A removed page isn't brought back. They're drafts, published with the
site; the audit log says "Added the starter pages". Found on cross-demo2.
- **Template and style → Home page layout:** the Latest message's Card layout had no name.
- **Media picker:** the "No image" placeholder had too little contrast (WCAG AA).
### Added
- **Site icon** (Settings): a picture from the media library as the favicon, live at once
(setting `favicon_media_id`; `favicon` in the site content). Without one the site uses the
church's icon from its profile, else a default: the church's initial on its brand colour (a cross
before the church is known). Every page links `/site-icon?v=…`, which redirects to the icon or
serves the default SVG; the version changes with the icon.
## [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
No migration, no new settings. Works with Accounts 1.7.0; with Accounts 1.7.1 the first sign-in
after an install links at once.
### Fixed
- **Preview sent admins to the server's own address** (`http://localhost:<web port>`, found on
cross-demo2). `/preview/start`, `/preview/exit` and shared preview links redirected to
`new URL(path, request.url)`, and behind the proxy `request.url` is the address Next.js is reached
on. They now answer with a relative `Location` (`src/lib/localRedirect.ts`), so the browser stays
on the site's address.
- **The admin couldn't be signed in to for up to 30 minutes after an install.** The Website links
itself to the church's Accounts, but only at a heartbeat, and Accounts refused it until Accounts'
own next heartbeat. Now opening `/admin` without a link links on the spot (asking the Hub for a
fresh list first when it has no Accounts in it; tried at most every 15 seconds). A connect
involving an install that isn't in the cached list yet (Accounts, or Events for the event feed)
also asks the Hub for a fresh list (at most once a minute) instead of refusing. Only one connect to
Accounts runs at a time, so a heartbeat and a sign-in can't leave the two sides with different
secrets.
- **The sign-in problem page says when the site isn't linked yet** (`ACCOUNTS_NOT_LINKED`: "This
website isn't linked to your church's sign-in yet"), instead of "can't reach your church's
sign-in", which read like an outage.
## [1.0.1] — 2026-11-26
### Fixed
- **The messages' thumbnails come from the site** (WEBSITE-1.0-PLAN §7): they loaded from YouTube
(`i.ytimg.com`) with the page, so every visitor was in touch with YouTube before pressing play.
The backend now fetches a message's thumbnail once and keeps it (`/api/thumbnails/<id>.jpg`,
kept in `uploads/.thumbnails/`, not counted as storage and left out of the export); only the
site's own messages' videos are fetched, and only a JPEG is kept. The messages page asks for the
first one from the `<head>` (it's the largest thing on screen), and the e2e checks that nothing
is asked of YouTube or Spotify until play is clicked.
- **Calendar events' dates** read "Sun (month: November)": a weekday and month without a day is
printed that way by `Intl`. Now "Sun · November".
- **The variant screenshots no longer flake** (e2e only): a section starting at a fractional
position came out a pixel taller or shorter from run to run. The header's and each section's
height is rounded up before the screenshot; the baselines were taken again with it.
## [1.0.0] — 2026-11-26
### Added
+37
View File
@@ -3,6 +3,43 @@
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).
## 1.3.0
- Nothing changes on your site. Behind the scenes, Cross Code can now load demo content on the
websites it uses for demonstrations.
## 1.2.0
- **Your home page and the other pages are there from the start:** a new website now comes with
its home page, Plan your visit, About us, Give, Contact and the rest, with some starter text to
change. Before, a new website had no pages, so the home page and its preview were empty apart
from the header and footer.
- **Your own site icon:** under **Settings → Site icon**, choose the little picture that shows in
the browser tab and bookmarks. Until you do, your site shows your church's initial in its colour.
## 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
- **Preview works:** pressing Preview in the admin shows your site with your changes, instead of
an error page.
- **Signing in right after your website is installed** works straight away, instead of after up to
half an hour. If it isn't connected to your church's sign-in yet, the page now says so.
## 1.0.1
- **Your visitors' privacy:** the pictures on your messages now come from your own website, so
nothing is loaded from YouTube until someone presses play. The Messages page also shows a little
sooner.
- **Event dates in the Calendar layout** read properly ("Sun · November").
## 1.0.0 — requires accounts 1.7.0
- **Your church's own website**, managed by you. Choose one of four templates (Heritage, Bold,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-backend",
"version": "1.0.0",
"version": "1.3.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
+21 -9
View File
@@ -1,25 +1,37 @@
/**
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
* Loads a demo into the site and publishes it.
*
* npm run demo -- --template heritage|bold|community|clean [--force]
* npm run demo -- --template heritage|bold|community|clean [--force] the Acacia Hill church (development)
* npm run demo -- --profile <profile> [--force] one of the eight demo churches (1.3.0),
* keeping the church's profile and settings
* npm run demo -- --list the profiles
*
* It replaces the site's content, so a site that has been published needs --force.
* It replaces the site's content, so a site that has been published needs --force. On a server,
* `crosscode demo <church> website --profile …` runs it (backup first), for the Hub's demo sites.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { agent, websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadDemo } from '../src/demo/demoChurch.js';
import { demoSeeds } from '../src/demo/seeds.js';
import { loadConfig } from '../src/lib/config.js';
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
};
const template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!template.success) {
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
const usage = 'Usage: npm run demo -- --template heritage|bold|community|clean | --profile <profile> [--force] | --list';
if (process.argv.includes('--list')) {
for (const s of demoSeeds()) console.log(`${s.id.padEnd(18)} ${s.label}`);
process.exit(0);
}
const profileArg = arg('profile');
const what = profileArg !== undefined ? agent.websiteDemoProfileSchema.safeParse(profileArg) : websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!what.success) {
console.error(profileArg !== undefined ? `Unknown profile "${profileArg}" (npm run demo -- --list).` : usage);
process.exit(2);
}
@@ -31,6 +43,6 @@ if (published && !process.argv.includes('--force')) {
await db.$disconnect();
process.exit(1);
}
const version = await loadDemo(ctx, template.data);
console.log(`Demo church loaded on ${template.data} and published (version ${version.number}).`);
const version = await loadDemo(ctx, what.data);
console.log(`Demo ${what.data} loaded and published (version ${version.number}).`);
await db.$disconnect();
+2 -2
View File
@@ -8,7 +8,7 @@ import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { youtubeId, spotifyEmbed } from '../site/content.js';
import { youtubeId, spotifyEmbed, messageThumbnail } from '../site/content.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
@@ -58,7 +58,7 @@ export async function listMessages(ctx: Ctx) {
youtube: { source, lastSync, lastError },
items: rows.map((m) => ({
id: m.id, title: m.title, date: m.date.toISOString(), mediaUrl: m.mediaUrl, source: m.source, speaker: m.speaker, passage: m.passage, notes: m.notes,
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: m.thumbnailUrl,
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: messageThumbnail(m),
})),
};
}
+12 -5
View File
@@ -1,7 +1,9 @@
/**
* The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's
* design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11:
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page. Also the
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page, and the
* site's icon (1.2.0: the favicon, a picture from the media library; without one the site uses the
* church's icon from its profile, else one made from its colour and initial). Also the
* menu's order, and the audit log.
*/
import { z } from 'zod';
@@ -18,13 +20,14 @@ const schema = z.object({
comingSoonText: z.string().trim().max(300).optional(),
googleVerification: code.optional(),
bingVerification: code.optional(),
faviconId: z.string().uuid().nullable().optional(),
});
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null; faviconId: string | null };
export async function getSettings(ctx: Ctx): Promise<SiteSettings> {
const [coming, google, bing] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null };
const [coming, google, bing, favicon] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null, faviconId: favicon || null };
}
export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) {
@@ -35,10 +38,14 @@ export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; ro
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields);
}
const s = r.data;
if (s.faviconId && !(await ctx.db.mediaAsset.findUnique({ where: { id: s.faviconId } }))) {
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', { faviconId: 'That picture isn\'t in the media library' });
}
await ctx.settings.setMany({
...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}),
...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}),
...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}),
...(s.faviconId !== undefined ? { favicon_media_id: s.faviconId || null } : {}),
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } });
return getSettings(ctx);
@@ -59,7 +66,7 @@ export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) {
}
const ACTIONS: Record<string, string> = {
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version',
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version', starter_pages_added: 'Added the starter pages',
preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link',
first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out',
admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access',
+19
View File
@@ -5,6 +5,7 @@
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
* /api/v1/site/… the public site (what visitors see: the latest published version)
* /api/uploads/… the church's uploaded images
* /api/thumbnails/<id>.jpg its messages' YouTube thumbnails, kept here (visitors never ask YouTube)
* /api/auth/… signing in to the admin through the church's Accounts
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
* /api/links/v1/… Connect and Disconnect with the church's other products
@@ -27,6 +28,7 @@ import { linksRouter } from './links/routes.js';
import { defaultUploadDir } from './demo/demoChurch.js';
import { previewContent, siteContent } from './site/content.js';
import { siteStatus } from './site/status.js';
import { thumbnail } from './site/thumbnails.js';
export function createApp(ctx: Ctx) {
const app = express();
@@ -75,6 +77,23 @@ export function createApp(ctx: Ctx) {
},
}));
// A message's YouTube thumbnail, fetched once by the backend and kept (site/thumbnails.ts).
app.get('/api/thumbnails/:file', async (req, res, next) => {
try {
const id = /^([A-Za-z0-9_-]+)\.jpg$/.exec(req.params.file)?.[1];
const body = id ? await thumbnail(ctx, id) : null;
if (!body) {
res.set('Cache-Control', 'no-store');
return sendError(res, new ApiError(404, 'NOT_FOUND', 'There is no such file.'));
}
res.set('Content-Type', 'image/jpeg');
res.set('Cache-Control', 'public, max-age=604800');
res.send(body);
} catch (err) {
next(err);
}
});
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
+11 -4
View File
@@ -8,13 +8,15 @@ import type * as AuthClient from '@crosscode/auth-client';
import type { AccountsClient } from '@crosscode/auth-client';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { linkAccountsNow } from '../links/connect.js';
export type AuthClientModule = typeof AuthClient;
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
export class AccountsUnavailable extends ApiError {
constructor(message: string) {
/** 1.0.2: `not_linked` (no link to Accounts yet) or `unreachable` (linked, but it didn't answer). */
constructor(message: string, public reason: 'not_linked' | 'unreachable' = 'unreachable') {
super(503, 'ACCOUNTS_UNAVAILABLE', message);
}
}
@@ -28,10 +30,15 @@ const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
const link = await accountsLink(ctx);
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet. It links by itself within 15 minutes of being installed.');
let link = await accountsLink(ctx);
if (!link) {
// 1.0.2: link now rather than wait for the next heartbeat.
await linkAccountsNow(ctx);
link = await accountsLink(ctx);
}
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet.', 'not_linked');
const clientId = await ctx.settings.get('hub_install_id');
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.');
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.', 'not_linked');
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
let hit = cache.get(ctx);
if (!hit || hit.key !== key) {
+5 -2
View File
@@ -34,6 +34,9 @@ const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/admin') =>
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** 1.0.2: the problem page says which it is: not linked to Accounts yet, or Accounts not answering. */
const unavailableCode = (e: AccountsUnavailable) => (e.reason === 'not_linked' ? 'ACCOUNTS_NOT_LINKED' : 'ACCOUNTS_UNAVAILABLE');
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
/**
@@ -70,7 +73,7 @@ export function authRouter(ctx: Ctx) {
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
return res.redirect(303, url);
} catch (e) {
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE', returnTo);
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e), returnTo);
console.error('[auth] Starting a sign-in failed:', e);
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
}
@@ -86,7 +89,7 @@ export function authRouter(ctx: Ctx) {
const auth = await accounts(ctx);
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
} catch (e) {
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE');
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e));
const code = (e as { code?: string }).code;
// The person pressed Cancel at Accounts, or the pending cookie expired.
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
+4 -1
View File
@@ -18,13 +18,16 @@ export type Ctx = {
/** `@crosscode/auth-client` (tests give a stand-in). */
authClient: () => Promise<AuthClientModule>;
now: () => Date;
/** Fetches what visitors are shown from outside (YouTube's thumbnails); tests give a stand-in. */
fetch?: (url: string) => Promise<Response>;
};
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule>; fetch?: (url: string) => Promise<Response> } = {}): Ctx {
const secrets = new Secrets(config.secret);
const partial = { config, db, secrets } as Ctx;
partial.settings = new Settings(partial);
partial.authClient = opts.authClient ?? loadAuthClient;
partial.now = opts.now ?? (() => new Date());
if (opts.fetch) partial.fetch = opts.fetch;
return partial;
}
+160 -76
View File
@@ -3,17 +3,24 @@
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
*
* 1.3.0: also the eight demo profiles (seeds.ts, `npm run demo -- --profile bold-plant`), which
* keep the church's own profile (Accounts' organisation settings), the site settings, the site
* icon and the admins, and name the church in the copy. A template alone (development, e2e) is
* still Acacia Hill, profile and all, exactly as before.
*
* It replaces the Website's content (never the admins), so the script refuses on a site that has
* been published unless told otherwise.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { CHURCH_SCHEMA, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import { CHURCH_SCHEMA, WEBSITE_TEMPLATES, type agent, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import type { SectionData } from '../site/sections.js';
import { publish } from '../site/snapshot.js';
import { defaultDesign } from '../site/variants.js';
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js';
import { DEMO_SEEDS, type DemoSeed } from './seeds.js';
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
@@ -48,8 +55,8 @@ export function demoProfile(publicUrl: string): Church {
}
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
function illustration(seed: number, w = 1600, h = 1000): string {
const hues = [DEMO_COLOURS.primary, DEMO_COLOURS.accent, '#7fb7be', '#f3e3c3', '#284b52'];
export function illustration(seed: number, w = 1600, h = 1000, colours: { primary: string; accent: string } = DEMO_COLOURS): string {
const hues = [colours.primary, colours.accent, '#7fb7be', '#f3e3c3', '#284b52'];
const c = (i: number) => hues[(seed + i) % hues.length];
const y = (f: number) => Math.round(h * f);
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
@@ -64,26 +71,17 @@ function illustration(seed: number, w = 1600, h = 1000): string {
type Ids = Record<string, string>;
async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
const items: [string, string, number][] = [
['hero', 'The hills behind Acacia Hill at sunrise (illustration)', 0],
['collage2', 'A path through the veld (illustration)', 1],
['collage3', 'Evening over the valley (illustration)', 2],
['welcome', 'The church garden (illustration)', 3],
['pastor', 'Illustration standing in for the pastor\'s photo', 4],
['invite', 'A sunny Sunday morning (illustration)', 5],
['kids', 'Illustration for Kids church', 6],
['youth', 'Illustration for Youth', 7],
['care', 'Illustration for Care and prayer', 8],
['music', 'Illustration for Worship', 9],
];
const HEX = /^#[0-9a-f]{6}$/i;
async function demoMedia(ctx: Ctx, uploadDir: string, alts: Record<string, string>, colours: { primary: string; accent: string }): Promise<Ids> {
const items: [string, number][] = [['hero', 0], ['collage2', 1], ['collage3', 2], ['welcome', 3], ['pastor', 4], ['invite', 5], ['kids', 6], ['youth', 7], ['care', 8], ['music', 9]];
const ids: Ids = {};
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
for (const [key, alt, seed] of items) {
for (const [key, seed] of items) {
const filename = `demo/${key}.svg`;
const svg = illustration(seed);
const svg = illustration(seed, 1600, 1000, colours);
fs.writeFileSync(path.join(uploadDir, filename), svg);
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } });
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt: alts[key]! } });
ids[key] = row.id;
}
return ids;
@@ -91,57 +89,160 @@ async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
/** Replaces the content with the demo church's on `template`, then publishes it. */
export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uploadDir?: string; publishedBy?: string } = {}) {
/** The development demo church (Acacia Hill), on any template: what a template alone loads. */
const CLASSIC: Omit<DemoSeed, 'template'> & { pastorName: string; ctaText: string; descriptions: Record<string, string>; alts: Record<string, string> } = {
id: 'classic', label: 'Acacia Hill (development)', alternate: false,
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', button: { label: 'Plan your visit', href: '/visit' } },
serviceNote: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.',
welcome: {
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
quote: 'We would love to meet you. Come and say hello at the welcome table.',
},
ministriesIntro: 'There is something for every age and stage.',
teamIntro: null,
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' } },
visit: {
expect: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.',
kids: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.',
cta: 'Questions before you come?',
},
ctaText: 'Send us a WhatsApp and we will get back to you.',
about: { story: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.', quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' },
give: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.'],
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.'],
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.'],
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.'],
],
leaders: [['Thandi Mokoena', 'Lead pastor'], ['Pieter van Wyk', 'Associate pastor'], ['Lerato Dlamini', 'Kids and families'], ['Johan Botha', 'Worship']],
pastorName: 'Pastor Thandi Mokoena',
series: ['hope-for-today', 'Hope for today'],
messages: [['hope-that-holds', 'A hope that holds', 3, 'Psalm 23'], ['bread-for-the-road', 'Bread for the road', 10, 'Psalm 23'], ['the-good-shepherd', 'The good shepherd', 17, 'Psalm 23']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
],
venue: 'Acacia Hill Church',
descriptions: {
home: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.',
visit: 'What to expect on your first Sunday at Acacia Hill Church.',
about: 'Our story, what we believe and what we value.',
ministries: 'Kids, youth, worship, care and prayer at Acacia Hill.',
leadership: 'The team who lead Acacia Hill Church.',
events: 'What is coming up at Acacia Hill Church.',
messages: 'Sunday messages from Acacia Hill Church.',
give: 'How to give to Acacia Hill Church.',
contact: 'Find Acacia Hill Church in Westridge, Pretoria.',
},
alts: {
hero: 'The hills behind Acacia Hill at sunrise (illustration)', collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: 'The church garden (illustration)', pastor: 'Illustration standing in for the pastor\'s photo', invite: 'A sunny Sunday morning (illustration)',
kids: 'Illustration for Kids church', youth: 'Illustration for Youth', care: 'Illustration for Care and prayer', music: 'Illustration for Worship',
},
};
/** A demo profile's design: the template's defaults, or (alternate) its second recommendations and header. */
export function seedDesign(template: WebsiteTemplate, alternate: boolean): SiteDesign {
const design = defaultDesign(template);
if (!alternate) return design;
const variants = Object.fromEntries(SECTION_TYPES.map((s) => {
const options = TEMPLATE_VARIANTS[template][s] as readonly string[];
return [s, options[1] ?? options[0]!];
})) as SiteDesign['variants'];
const headers = TEMPLATE_HEADERS[template] as readonly string[];
return { ...design, variants, style: { ...design.style, header: headers[1] ?? headers[0]! } };
}
export const isDemoTemplate = (v: string): v is WebsiteTemplate => (WEBSITE_TEMPLATES as readonly string[]).includes(v);
/**
* Replaces the content with a demo, then publishes it. `what`: a template (the Acacia Hill church,
* its profile saved too) or a demo profile (keeps the church's profile; Acacia Hill's is saved
* only on a site that has none at all, so the site still has a name).
*/
export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string } = {}) {
const db = ctx.db;
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'mediaAsset', 'siteVersion', 'siteDesign'] as const) {
const classic = isDemoTemplate(what);
const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : DEMO_SEEDS[what];
const extra = classic ? CLASSIC : null;
// The church: Acacia Hill for a template; else whoever the site belongs to.
let church = classic ? null : await churchProfile(ctx);
if (!church) {
church = demoProfile(ctx.config.publicUrl);
await ctx.settings.set('church_profile_local', JSON.stringify(church));
}
const name = church.name;
const short = church.shortName || church.name;
const city = church.contact?.address?.city || church.contact?.address?.suburb || 'town';
const t = (s: string) => s.replaceAll('{name}', name).replaceAll('{short}', short).replaceAll('{city}', city);
const brand = church.branding?.colours;
const colours = classic || !brand?.primary || !HEX.test(brand.primary)
? DEMO_COLOURS
: { primary: brand.primary, accent: brand.accent && HEX.test(brand.accent) ? brand.accent : DEMO_COLOURS.accent };
// The site icon is a setting, so its picture stays; every other picture goes with the content.
const faviconId = classic ? null : await ctx.settings.get('favicon_media_id');
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'siteVersion', 'siteDesign', 'slugHistory', 'previewLink'] as const) {
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
}
const img = await demoMedia(ctx, uploadDir);
const design = defaultDesign(template);
await db.siteDesign.create({ data: { id: 1, template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
await ctx.settings.set('church_profile_local', JSON.stringify(demoProfile(ctx.config.publicUrl)));
await db.mediaAsset.deleteMany(faviconId ? { where: { NOT: { id: faviconId } } } : undefined);
const [pastorName] = seed.leaders[0]!;
const ministryNames = seed.ministries.map(([, n]) => t(n));
const alts = extra?.alts ?? {
hero: `${t(seed.hero.headline)} (illustration)`, collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: `${short} (illustration)`, pastor: `Illustration standing in for ${pastorName}'s photo`, invite: 'A sunny Sunday morning (illustration)',
kids: `Illustration for ${ministryNames[0]}`, youth: `Illustration for ${ministryNames[1]}`, music: `Illustration for ${ministryNames[2]}`, care: `Illustration for ${ministryNames[3]}`,
};
const img = await demoMedia(ctx, uploadDir, alts, colours);
const design = classic ? defaultDesign(seed.template) : seedDesign(seed.template, seed.alternate);
await db.siteDesign.create({ data: { id: 1, template: seed.template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
const speaker = extra?.pastorName ?? pastorName;
const home: SectionData = {
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: { label: 'Plan your visit', href: '/visit' } },
serviceTimes: { heading: 'Join us this Sunday', note: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.' },
hero: { headline: t(seed.hero.headline), subline: t(seed.hero.subline), images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: seed.hero.button },
serviceTimes: { heading: 'Join us this Sunday', note: t(seed.serviceNote) },
welcome: {
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
imageId: img.welcome!, pastor: { name: 'Pastor Thandi Mokoena', role: 'Lead pastor', quote: 'We would love to meet you. Come and say hello at the welcome table.', photoId: img.pastor! },
heading: t(seed.welcome.heading), mission: t(seed.welcome.mission), body: t(seed.welcome.body),
imageId: img.welcome!, pastor: { name: speaker, role: seed.leaders[0]![1], quote: t(seed.welcome.quote), photoId: img.pastor! },
},
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
team: { heading: 'Our team', intro: null },
ministries: { heading: 'Find your place', intro: t(seed.ministriesIntro) },
team: { heading: 'Our team', intro: seed.teamIntro ? t(seed.teamIntro) : null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
invitation: { heading: t(seed.invitation.heading), text: t(seed.invitation.text), button: seed.invitation.button, imageId: img.invite! },
};
const d = (kind: string, fallback: string) => extra?.descriptions[kind] ?? t(fallback);
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: d('home', `${seed.hero.subline}`), sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: 'What to expect on your first Sunday at Acacia Hill Church.', sections: [
{ type: 'text', data: { heading: 'What to expect', body: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.' } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', imageId: img.kids, button: null } },
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Send us a WhatsApp and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.kids, button: null } },
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{
kind: 'about', slug: 'about', title: 'About us', position: 2, description: 'Our story, what we believe and what we value.', sections: [
{ type: 'text', data: { heading: 'Our story', body: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.' } },
{ type: 'quote', data: { quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' } },
kind: 'about', slug: 'about', title: 'About us', position: 2, description: d('about', 'Our story, what we believe and what we value.'), sections: [
{ type: 'text', data: { heading: 'Our story', body: t(seed.about.story) } },
{ type: 'quote', data: { quote: seed.about.quote, by: seed.about.by } },
],
},
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: 'Kids, youth, worship, care and prayer at Acacia Hill.', sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: 'The team who lead Acacia Hill Church.', sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: 'What is coming up at Acacia Hill Church.', sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: 'Sunday messages from Acacia Hill Church.', sections: [] },
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: d('ministries', `${ministryNames.join(', ')} at {short}.`), sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: d('leadership', 'The team who lead {name}.'), sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: d('events', 'What is coming up at {name}.'), sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: d('messages', 'Sunday messages from {name}.'), sections: [] },
{
kind: 'give', slug: 'give', title: 'Give', position: 7, description: 'How to give to Acacia Hill Church.', sections: [
{ type: 'text', data: { heading: 'Giving', body: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).' } },
kind: 'give', slug: 'give', title: 'Give', position: 7, description: d('give', 'How to give to {name}.'), sections: [
{ type: 'text', data: { heading: 'Giving', body: t(seed.give) } },
],
},
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', sections: [] },
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: d('contact', 'Find {name} in {city}.'), sections: [] },
];
for (const p of pages) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
@@ -149,38 +250,21 @@ export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uplo
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
}
const ministries: [string, string, string, string][] = [
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.', img.kids!],
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.', img.youth!],
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.', img.music!],
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.', img.care!],
];
const pictures = [img.kids!, img.youth!, img.music!, img.care!];
let n = 0;
for (const [slug, name, summary, imageId] of ministries) await db.ministry.create({ data: { slug, name, summary, imageId, position: n++ } });
const leaders: [string, string, string | null][] = [
['Thandi Mokoena', 'Lead pastor', img.pastor!],
['Pieter van Wyk', 'Associate pastor', null],
['Lerato Dlamini', 'Kids and families', null],
['Johan Botha', 'Worship', null],
];
for (const [slug, , summary] of seed.ministries) await db.ministry.create({ data: { slug, name: ministryNames[n]!, summary: t(summary), imageId: pictures[n]!, position: n++ } });
n = 0;
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, position: n++ } });
for (const [leader, role] of seed.leaders) await db.leader.create({ data: { name: leader, role, photoId: n === 0 ? img.pastor! : null, position: n++ } });
const now = ctx.now();
const day = 864e5;
const series = await db.messageSeries.create({ data: { slug: 'hope-for-today', title: 'Hope for today' } });
const messages: [string, string, number][] = [['hope-that-holds', 'A hope that holds', 3], ['bread-for-the-road', 'Bread for the road', 10], ['the-good-shepherd', 'The good shepherd', 17]];
for (const [slug, title, ago] of messages) {
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker: 'Pastor Thandi Mokoena', passage: 'Psalm 23', seriesId: series.id, publishedAt: now } });
const series = await db.messageSeries.create({ data: { slug: seed.series[0], title: seed.series[1] } });
for (const [slug, title, ago, passage] of seed.messages) {
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker, passage, seriesId: series.id, publishedAt: now } });
}
const events: [string, string, number, string][] = [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
];
for (const [slug, title, inDays, description] of events) {
for (const [slug, title, inDays, description] of seed.events) {
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: 'Acacia Hill Church', description, publishedAt: now } });
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), publishedAt: now } });
}
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
}
+334
View File
@@ -0,0 +1,334 @@
/**
* The Website's demo profiles (1.3.0, contracts `WEBSITE_DEMO_PROFILES`): eight fictional churches,
* two per template, for the Hub's demo sites (`crosscode demo <church> website --profile …`).
*
* A demo replaces the content only. The church's profile (name, logo, colours, service times,
* contact: Accounts' organisation settings) stays, so the copy names the church with placeholders:
* `{name}` (Hope Family Church), `{short}` (Hope Family) and `{city}` (Pretoria). The second
* profile of each template starts on the template's other recommended variants and header, so the
* eight show every recommended look.
*
* Every person and place in here is made up. A profile id never changes once released.
*/
import { agent, type WebsiteTemplate } from '@crosscode/contracts';
type WebsiteDemoProfile = agent.WebsiteDemoProfile;
type Button = { label: string; href: string };
export type DemoSeed = {
id: WebsiteDemoProfile | 'classic';
template: WebsiteTemplate;
/** What the Hub shows: "Heritage: a parish church". */
label: string;
/** Start on the template's second recommended variant of every section, and its second header. */
alternate: boolean;
hero: { headline: string; subline: string; button: Button };
serviceNote: string;
welcome: { heading: string; mission: string; body: string; quote: string };
ministriesIntro: string;
teamIntro: string | null;
invitation: { heading: string; text: string; button: Button };
visit: { expect: string; kids: string; cta: string };
about: { story: string; quote: string; by: string };
give: string;
/** Four: [slug, name, summary]. Their pictures are the kids, youth, music and care illustrations, in order. */
ministries: [string, string, string][];
/** Four: [name, role]. The first is the pastor on the home page and the speaker of the messages. */
leaders: [string, string][];
series: [string, string];
/** Three: [slug, title, days ago, passage]. */
messages: [string, string, number, string][];
/** Three: [slug, title, in days, description]. */
events: [string, string, number, string][];
/** Where the events are. */
venue: string;
};
const visitButton: Button = { label: 'Plan your visit', href: '/visit' };
export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
'heritage-parish': {
id: 'heritage-parish', template: 'heritage', label: 'Heritage: a parish church with a long history', alternate: false,
hero: { headline: 'Worshipping together since 1896', subline: 'An old church with a warm welcome in the heart of {city}. Traditional services, every generation together.', button: visitButton },
serviceNote: 'Holy Communion on the first Sunday of the month. Tea in the parish hall after every service.',
welcome: {
heading: 'Welcome to {name}', mission: 'Rooted in prayer, open to all, serving {city}.',
body: 'For more than a century people have gathered here to pray, to sing the old hymns and to hear God\'s word. Our services follow the prayer book, our choir sings most Sundays, and our doors are open to anyone who wants to come in out of the noise.',
quote: 'Whether this is your first time in a church or your thousandth, you are welcome here.',
},
ministriesIntro: 'Ways to belong, from the choir stalls to the Sunday school.',
teamIntro: 'The clergy and lay ministers who care for the parish.',
invitation: { heading: 'There is always a place in the pews', text: 'Join us this Sunday. Someone at the door will show you the way.', button: visitButton },
visit: {
expect: 'Our services follow a set order with readings, prayers and hymns. The words are printed in the service sheet, so you can follow along. A service lasts about an hour.',
kids: 'Sunday school meets in the hall during the sermon, and the children come back in for the blessing.',
cta: 'Would you like to talk to the rector before you come?',
},
about: { story: '{name} was founded by a handful of families in 1896, and the stone church was finished in 1912. The stained glass, the organ and the bell are all gifts from the parish over the years.', quote: 'Be still, and know that I am God.', by: 'Psalm 46:10' },
give: 'Thank you for supporting the life of the parish and the upkeep of the church building. You can give by EFT or in the plate on Sundays (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Bible stories, songs and crafts for ages 4 to 11 during the sermon.'],
['servers', 'Altar servers', 'Teenagers who help lead worship on Sunday mornings.'],
['choir', 'The parish choir', 'Choral evensong once a month and anthems every Sunday. New voices welcome.'],
['pastoral-care', 'Pastoral visiting', 'Home communion and visits for those who can\'t come to church.'],
],
leaders: [['The Revd Margaret Pillay', 'Rector'], ['The Revd Sipho Ndlovu', 'Assistant priest'], ['Anne Fourie', 'Director of music'], ['David Smith', 'Churchwarden']],
series: ['the-lords-prayer', 'The Lord\'s Prayer'],
messages: [['your-kingdom-come', 'Your kingdom come', 3, 'Matthew 6:10'], ['our-daily-bread', 'Our daily bread', 10, 'Matthew 6:11'], ['forgive-us', 'Forgive us as we forgive', 17, 'Matthew 6:12']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share on the rectory lawn. Games for the children.'],
['advent-carols', 'Advent carol service', 13, 'Readings and carols by candlelight, sung by the parish choir.'],
['christmas-eve', 'Christmas Eve midnight mass', 27, 'The first Communion of Christmas, with carols from 23:15.'],
],
venue: '{name}',
},
'heritage-city': {
id: 'heritage-city', template: 'heritage', label: 'Heritage: a city-centre church with weekday services', alternate: true,
hero: { headline: 'A quiet place in a busy city', subline: 'In the middle of {city}, open every weekday for prayer, lunchtime services and a cup of tea.', button: { label: 'Come in this week', href: '/visit' } },
serviceNote: 'Lunchtime service on weekdays at 13:05, twenty-five minutes, back at your desk in time.',
welcome: {
heading: 'Right in the heart of {city}', mission: 'A church for the city: for workers, students, visitors and neighbours.',
body: 'Thousands of people walk past our doors every day. Some come in to sit in the quiet, some to light a candle, some for the lunchtime service. On Sundays we worship as a congregation drawn from all over {city}.',
quote: 'The city needs places that are quiet and kind. We try to be one.',
},
ministriesIntro: 'Serving the city through the week.',
teamIntro: null,
invitation: { heading: 'The doors are open', text: 'Monday to Friday from 08:00 to 16:00. Come in for a moment, or for the service.', button: { label: 'When we are open', href: '/visit' } },
visit: {
expect: 'The weekday service is short and simple: a reading, a short talk and prayers. On Sundays the service is longer, with the choir and Communion.',
kids: 'Children are welcome at every service. There are activity bags at the back of the church.',
cta: 'Want to know more about the city ministries?',
},
about: { story: '{name} has stood on this corner since the city was young. Today our congregation is students, office workers, families and people who sleep on the streets nearby, all at the same tables.', quote: 'Seek the welfare of the city, and pray to the Lord on its behalf.', by: 'Jeremiah 29:7' },
give: 'Your gifts keep the doors open on weekdays and fund the soup kitchen (demo details only: this is not a real account).',
ministries: [
['students', 'Students', 'Supper and a Bible study for students on Tuesday evenings.'],
['young-workers', 'Young professionals', 'Breakfast before work on Thursdays at 07:00.'],
['lunchtime-music', 'Lunchtime concerts', 'Free organ and chamber music on Wednesdays.'],
['soup-kitchen', 'The soup kitchen', 'Soup and bread for anyone who needs it, every weekday at noon.'],
],
leaders: [['Canon Peter Mahlangu', 'Vicar'], ['The Revd Claire Jacobs', 'City chaplain'], ['Tom Venter', 'Organist'], ['Nomsa Khumalo', 'Soup kitchen coordinator']],
series: ['songs-of-ascent', 'Songs of Ascent'],
messages: [['unless-the-lord-builds', 'Unless the Lord builds the house', 4, 'Psalm 127'], ['i-lift-up-my-eyes', 'I lift up my eyes', 11, 'Psalm 121'], ['how-good-and-pleasant', 'How good and pleasant', 18, 'Psalm 133']],
events: [
['organ-recital', 'Lunchtime organ recital', 2, 'Bach and Buxtehude, 13:05 to 13:40. Free, with a retiring collection.'],
['blue-christmas', 'Blue Christmas', 16, 'A quiet service for anyone who finds Christmas hard.'],
['city-carols', 'Carols for the city', 23, 'Readings and carols for everyone who works in {city}.'],
],
venue: '{name}',
},
'bold-youth': {
id: 'bold-youth', template: 'bold', label: 'Bold: a young, music-led church', alternate: false,
hero: { headline: 'Loud worship. Real people. Good news.', subline: '{short} is a church for {city}: come for the music, stay for the family.', button: { label: 'Visit this Sunday', href: '/visit' } },
serviceNote: 'Doors open half an hour before. Coffee bar in the foyer, kids church at the morning service.',
welcome: {
heading: 'This is {short}', mission: 'Helping people find and follow Jesus, together.',
body: 'We are a young church with a big heart for {city}. Sundays are full of energy: a live band, a message you can use on Monday, and people who will remember your name. Wherever you are coming from, you belong here.',
quote: 'We are not a perfect church. We are a family learning to follow Jesus together.',
},
ministriesIntro: 'Get connected. There is a place for you.',
teamIntro: null,
invitation: { heading: 'Your seat is waiting', text: 'Tell us you are coming and we will have a coffee ready for you.', button: { label: 'I am coming', href: '/visit' } },
visit: {
expect: 'Expect about 30 minutes of live worship and a 30-minute message. Come as you are: jeans are fine.',
kids: 'Kids church is high energy, safe and fun. Check your kids in at the kids desk when you arrive.',
cta: 'Got questions? Our team will get back to you.',
},
about: { story: '{short} started in a living room with twelve students and a guitar. Today we are a church of every age, but we have never lost the joy of that first night.', quote: 'I have come that they may have life, and have it to the full.', by: 'John 10:10' },
give: 'Generosity is part of who we are. Give online, by EFT or at the giving station (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Ages 2 to 12, every Sunday morning.'],
['youth', 'Youth', 'Grades 8 to 12, Friday nights. Games, worship, real talk.'],
['creative', 'Worship and creative', 'Band, sound, lights and media. Auditions every term.'],
['groups', 'Connect groups', 'Meet in a home during the week and do life together.'],
],
leaders: [['Jason and Lindi Naidoo', 'Lead pastors'], ['Kagiso Molefe', 'Youth pastor'], ['Megan Steyn', 'Worship pastor'], ['Ruan Pretorius', 'Connect groups']],
series: ['unstoppable', 'Unstoppable'],
messages: [['fearless', 'Fearless', 3, 'Joshua 1:9'], ['all-in', 'All in', 10, 'Romans 12:1-2'], ['no-turning-back', 'No turning back', 17, 'Luke 9:62']],
events: [
['worship-night', 'Worship night', 5, 'Two hours of worship and prayer. Bring your friends.'],
['youth-camp', 'Summer youth camp', 19, 'Three days at the river for grades 8 to 12. Registration is open.'],
['christmas-experience', 'The Christmas experience', 26, 'Music, lights and the Christmas story for the whole family.'],
],
venue: 'The {short} auditorium',
},
'bold-plant': {
id: 'bold-plant', template: 'bold', label: 'Bold: a new church plant meeting in a school', alternate: true,
hero: { headline: 'A new church for {city}', subline: 'We are launching soon. Meet us on Sundays in the school hall and be part of something new.', button: { label: 'Find out more', href: '/about' } },
serviceNote: 'We meet in the school hall. Look for the flags at the gate; parking is on the field.',
welcome: {
heading: 'Something new is starting', mission: 'A church for people who don\'t go to church.',
body: '{short} is a brand-new church. We are a small team who moved to {city} to start a church for our neighbours. Every week we set up chairs in a school hall, and every week new people walk in. There is room for you on the team.',
quote: 'Every great church was once a few people setting out chairs.',
},
ministriesIntro: 'Small team, big vision. Find where you fit.',
teamIntro: 'The launch team.',
invitation: { heading: 'Join the launch team', text: 'Help us set up, welcome, play or pray. Every hand matters right now.', button: { label: 'Get involved', href: '/contact' } },
visit: {
expect: 'Our services are relaxed and short: songs, a talk and time to talk over coffee afterwards. Nobody will put you on the spot.',
kids: 'Kids are part of the service for the songs, then go to their own room in the classroom next door.',
cta: 'Want to meet the team first?',
},
about: { story: '{short} was planted last year by a team of eight with the support of churches across the country. We have met in lounges, a coffee shop and now the school hall.', quote: 'See, I am doing a new thing! Now it springs up; do you not perceive it?', by: 'Isaiah 43:19' },
give: 'Every gift helps us reach a new neighbourhood with the good news (demo details only: this is not a real account).',
ministries: [
['kids-room', 'Kids room', 'A safe, fun room for children during the service.'],
['set-up', 'Set-up team', 'Chairs, sound and signs from 07:30. Breakfast is on us.'],
['band', 'Band', 'Guitar, keys, drums or voice. We need you.'],
['dinner-church', 'Dinner church', 'Supper and a conversation about Jesus on Wednesdays.'],
],
leaders: [['Ben and Zanele Moore', 'Church planters'], ['Ayesha Patel', 'Kids'], ['Chris Hendricks', 'Music'], ['Grace Okafor', 'Community']],
series: ['new-beginnings', 'New beginnings'],
messages: [['why-church', 'Why church?', 4, 'Acts 2:42-47'], ['the-first-step', 'The first step', 11, 'Mark 1:16-20'], ['a-seat-at-the-table', 'A seat at the table', 18, 'Luke 14:15-24']],
events: [
['launch-sunday', 'Launch Sunday', 7, 'Our first public service. Bring everyone you know.'],
['street-braai', 'Street braai', 14, 'Food and games for the neighbourhood in the school grounds.'],
['christmas-in-the-hall', 'Christmas in the hall', 24, 'A family carol service with mince pies.'],
],
venue: 'The school hall',
},
'community-family': {
id: 'community-family', template: 'community', label: 'Community: a family church with small groups', alternate: false,
hero: { headline: 'Come as you are, bring the family', subline: 'A friendly church in {city} where kids are noisy, coffee is hot and everyone knows your name.', button: visitButton },
serviceNote: 'Kids church for every age during the service. Coffee and juice afterwards on the lawn.',
welcome: {
heading: 'Hello, we are {short}', mission: 'Families following Jesus together, every day of the week.',
body: 'We are mums, dads, grandparents, singles, teenagers and toddlers. On Sundays we worship together, and during the week we meet in homes across {city} to eat, pray and look after each other.',
quote: 'Church is not a building we go to. It is a family we belong to.',
},
ministriesIntro: 'Something for every member of the family.',
teamIntro: 'The people who look after our church family.',
invitation: { heading: 'Pop in this Sunday', text: 'Let us know you are coming and we will save you a spot (and a muffin).', button: visitButton },
visit: {
expect: 'Our services are friendly and informal and last about an hour and a quarter. You don\'t need to know the songs or the Bible to feel at home.',
kids: 'Babies to grade 7 have their own groups with trained, screened leaders. There is a parents\' room with the service on a screen.',
cta: 'Questions about the kids? Ask us anything.',
},
about: { story: '{short} began when three families started meeting for a Bible study and the kids outnumbered the grown-ups. We still think that is a good sign.', quote: 'As for me and my household, we will serve the Lord.', by: 'Joshua 24:15' },
give: 'Thank you for helping us care for families in {city} (demo details only: this is not a real account).',
ministries: [
['little-ones', 'Little ones', 'Babies and toddlers, with a play area and story time.'],
['teens', 'Teens', 'Grades 6 to 12 on Friday evenings: games, food and faith.'],
['worship-team', 'Worship team', 'Singers and musicians of all ages lead us on Sundays.'],
['home-groups', 'Home groups', 'Twelve groups across {city}, every Tuesday or Wednesday.'],
],
leaders: [['Pastor Andile Zulu', 'Senior pastor'], ['Michelle de Beer', 'Children\'s pastor'], ['Kevin and Tracy Reddy', 'Home groups'], ['Lwazi Mthembu', 'Youth']],
series: ['family-matters', 'Family matters'],
messages: [['love-at-home', 'Love at home', 3, '1 Corinthians 13'], ['raising-faith', 'Raising faith', 10, 'Deuteronomy 6:4-9'], ['better-together', 'Better together', 17, 'Ecclesiastes 4:9-12']],
events: [
['fun-day', 'Family fun day', 6, 'Jumping castles, a cake sale and a soccer match for dads.'],
['holiday-club', 'Holiday club', 15, 'Four mornings of games, crafts and stories for ages 4 to 12.'],
['christmas-family-service', 'Christmas family service', 25, 'Our nativity, sung by the kids, followed by tea.'],
],
venue: '{name}',
},
'community-town': {
id: 'community-town', template: 'community', label: 'Community: a country-town church serving its district', alternate: true,
hero: { headline: 'Neighbours, friends, family', subline: 'The church in {city} that has been part of farm and town life for generations.', button: { label: 'Meet us on Sunday', href: '/visit' } },
serviceNote: 'Combined service on the last Sunday of the month, with a bring-and-share lunch.',
welcome: {
heading: 'Welcome to {name}', mission: 'Loving God and serving our district, farm and town alike.',
body: 'In a small town everyone knows everyone, and the church is where we meet in good times and hard ones. We pray for the rain, we help with the harvest festival, and when someone is in need we turn up with a casserole.',
quote: 'A small church can have a big heart. Come and see.',
},
ministriesIntro: 'Serving town and farm through the week.',
teamIntro: null,
invitation: { heading: 'You are always welcome here', text: 'Visiting the district? Join us on Sunday morning and stay for tea.', button: { label: 'Find us', href: '/contact' } },
visit: {
expect: 'A friendly, simple service with hymns and newer songs, a Bible message and prayers for the district. About an hour.',
kids: 'Children start in the service and go to Sunday school after the first songs.',
cta: 'Need a lift to church? Let us know.',
},
about: { story: 'The first service in {city} was held under a tree in the square. The church was built by local farmers and townspeople, stone by stone, and it is still the heart of the town.', quote: 'While the earth remains, seedtime and harvest shall not cease.', by: 'Genesis 8:22' },
give: 'Your gifts help us support families in the district through hard seasons (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Every Sunday for children of the town and the farms.'],
['youth', 'Youth', 'Friday evenings for high schoolers from the district.'],
['music', 'Choir and band', 'Old hymns and new songs, rehearsing on Thursdays.'],
['outreach', 'Farm outreach', 'Visits, food parcels and prayer for farmworker families.'],
],
leaders: [['Ds. Willem Coetzee', 'Minister'], ['Elsie Maritz', 'Sunday school'], ['Bongani Sithole', 'Farm outreach'], ['Marie Louw', 'Music']],
series: ['seasons', 'Seasons'],
messages: [['a-time-to-plant', 'A time to plant', 4, 'Ecclesiastes 3:1-8'], ['waiting-for-rain', 'Waiting for rain', 11, 'James 5:7-8'], ['the-harvest-is-plentiful', 'The harvest is plentiful', 18, 'Matthew 9:35-38']],
events: [
['harvest-festival', 'Harvest festival', 8, 'Produce, baking and crafts in the church hall, for the district\'s food bank.'],
['farm-carols', 'Carols on the farm', 20, 'An evening carol service at the Botha family\'s farm. Bring a chair.'],
['new-year-prayer', 'New Year prayer breakfast', 36, 'Pray for the year ahead over breakfast in the hall.'],
],
venue: '{name}',
},
'clean-modern': {
id: 'clean-modern', template: 'clean', label: 'Clean: a contemporary church, simply put', alternate: false,
hero: { headline: 'Faith for real life', subline: 'Sundays in {city}. Honest conversations, good coffee, and Jesus at the centre.', button: visitButton },
serviceNote: 'One service, about an hour. Kids programme included.',
welcome: {
heading: 'A church without the fuss', mission: 'Clear about Jesus. Open to questions.',
body: 'We keep things simple so the important things stand out. Our Sundays are thoughtful and relaxed, and our groups are a good place to ask the questions you have been carrying around.',
quote: 'Bring your questions. We are not afraid of them.',
},
ministriesIntro: 'A few things, done well.',
teamIntro: null,
invitation: { heading: 'See you on Sunday', text: 'No pressure, no spotlight. Just come.', button: visitButton },
visit: {
expect: 'A few songs, a talk that takes the Bible and your life seriously, and time to chat afterwards.',
kids: 'Kids have their own programme during the service, in age groups up to grade 7.',
cta: 'Prefer to message first?',
},
about: { story: '{short} began in 2015 with a simple idea: a church where it is normal to doubt, to ask and to grow. We are still that church.', quote: 'Come to me, all you who are weary and burdened, and I will give you rest.', by: 'Matthew 11:28' },
give: 'Giving is simple: by EFT or with a card at the welcome desk (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Age groups up to grade 7, every Sunday.'],
['students', 'Students', 'University and college students, Sunday evenings.'],
['music', 'Music', 'A small band leading simple, honest worship.'],
['alpha', 'Alpha', 'Ten weeks, a meal and a conversation about life and faith.'],
],
leaders: [['Daniel Joubert', 'Pastor'], ['Refilwe Mokoena', 'Kids'], ['Sam Abrahams', 'Music'], ['Nadia Govender', 'Alpha']],
series: ['questions', 'Questions'],
messages: [['why-suffering', 'Why is there suffering?', 3, 'Romans 8:18-28'], ['can-i-trust-the-bible', 'Can I trust the Bible?', 10, '2 Timothy 3:14-17'], ['who-is-jesus', 'Who is Jesus?', 17, 'Mark 8:27-30']],
events: [
['alpha-starts', 'Alpha starts', 9, 'Ten Thursday evenings with dinner. Ask anything.'],
['carols-and-coffee', 'Carols and coffee', 18, 'A short carol service and a coffee cart.'],
['christmas-day', 'Christmas Day', 28, 'One family service at 09:00, about 45 minutes.'],
],
venue: '{name}',
},
'clean-campus': {
id: 'clean-campus', template: 'clean', label: 'Clean: a church near the university', alternate: true,
hero: { headline: 'Students, staff and neighbours', subline: 'A church across the road from campus in {city}. Sunday evenings, with supper.', button: { label: 'First time?', href: '/visit' } },
serviceNote: 'Evening service with free supper afterwards during term.',
welcome: {
heading: 'Welcome to {short}', mission: 'Thinking hard, loving well, following Jesus.',
body: 'Most of us are students or work at the university, and plenty of us live in the streets around it. We meet on Sunday evenings, eat together, and spend the week in small groups across campus.',
quote: 'University is where you ask the big questions. Church is a good place to ask them out loud.',
},
ministriesIntro: 'Find your people.',
teamIntro: 'The staff team.',
invitation: { heading: 'Supper is on us', text: 'Every Sunday in term, after the evening service.', button: { label: 'Come for supper', href: '/visit' } },
visit: {
expect: 'The evening service has songs, a Bible talk and prayer, and ends with supper in the hall. It lasts about an hour before the food.',
kids: 'Staff and neighbours with children: there is a morning family service on the first Sunday of the month.',
cta: 'New to the city? We would love to help you settle in.',
},
about: { story: '{short} started as a student Bible study in a residence common room. It grew into a church for the whole campus community and the neighbourhood around it.', quote: 'Love the Lord your God with all your heart and with all your soul and with all your mind.', by: 'Matthew 22:37' },
give: 'If you are a student, please don\'t worry about giving. If you can, your gifts fund supper every Sunday (demo details only: this is not a real account).',
ministries: [
['families', 'Families', 'A monthly family service for staff and neighbours with children.'],
['res-groups', 'Residence groups', 'Bible studies in every residence, weeknights.'],
['music', 'Music', 'Student musicians lead the evening service.'],
['international', 'International students', 'A welcome, a meal and help settling in.'],
],
leaders: [['Dr Ian Mabaso', 'Pastor'], ['Lisa Roberts', 'Student worker'], ['Thabo Nkosi', 'Music'], ['Priya Singh', 'International students']],
series: ['big-questions', 'Big questions'],
messages: [['what-is-truth', 'What is truth?', 4, 'John 18:37-38'], ['does-god-care', 'Does God care?', 11, 'Psalm 139'], ['what-makes-a-good-life', 'What makes a good life?', 18, 'Micah 6:8']],
events: [
['exam-prayer', 'Exam prayer and pizza', 3, 'A break from studying: prayer, pizza and encouragement.'],
['end-of-term-dinner', 'End of term dinner', 12, 'A three-course dinner to celebrate the end of term.'],
['carols-on-campus', 'Carols on campus', 19, 'Carols on the library lawn for students who are still here.'],
],
venue: '{name}',
},
};
/** The profiles in the contracts' order (what the Hub offers). */
export const demoSeeds = (): DemoSeed[] => agent.WEBSITE_DEMO_PROFILES.map((id: WebsiteDemoProfile) => DEMO_SEEDS[id]);
+5
View File
@@ -11,6 +11,7 @@ import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
import { loadConfig } from './lib/config.js';
import { ensureStarterPages } from './site/starter.js';
import { startYoutubeSync } from './site/youtube.js';
import { startFeedSync } from './feed/feed.js';
@@ -20,6 +21,10 @@ async function main() {
if (!url) throw new Error('DATABASE_URL isn\'t set.');
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
const ctx = createCtx(config, db);
// A new install's fixed pages (home, Plan your visit, …), before anything is served.
await ensureStarterPages(ctx)
.then((kinds) => { if (kinds.length) console.log(`[website] Added the starter pages: ${kinds.join(', ')}.`); })
.catch((e) => console.error('[website] Couldn\'t add the starter pages:', (e as Error).message));
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
const stopHeartbeats = startHeartbeats(ctx);
+67 -5
View File
@@ -27,6 +27,37 @@ export class LinkError extends Error {
/** The products the Website links to. */
const LINKABLE = new Set(['accounts', 'events', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const SIGN_IN_TRY_EVERY_MS = 15 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.0.2: a fresh list of the church's products from the Hub (a heartbeat), at most once a minute,
* so a message from an unknown install can't make the Website call the Hub more often than that.
* Several callers inside that minute share one heartbeat. Never throws.
*/
async function refreshList(ctx: Ctx): Promise<void> {
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
// Imported here: hub/client.ts imports this file (it links to Accounts after each heartbeat).
r = { at: now, run: import('../hub/client.js').then((m) => m.heartbeat(ctx)).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
}
/**
* 1.0.2: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat), the Website asks the Hub for a fresh list and looks again.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
await refreshList(ctx);
return listedProduct(ctx, installId);
}
type Actor = { id: string | null; role: string };
@@ -61,8 +92,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -93,9 +124,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(ctx, m.from.installId);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.product)) {
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (the Website asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -146,7 +177,20 @@ export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request):
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
* Never throws: a failure is tried again at the next heartbeat.
*/
export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
export function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
// 1.0.2: one connect at a time (a heartbeat and a sign-in can both try): two at once would each
// send Accounts a different secret, and the one each side kept last might not be the same.
let run = connecting.get(ctx);
if (!run) {
run = connectAccountsOnce(ctx).finally(() => connecting.delete(ctx));
connecting.set(ctx, run);
}
return run;
}
const connecting = new WeakMap<Ctx, Promise<'connected' | 'skipped' | 'failed'>>();
async function connectAccountsOnce(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
if (!listed) return 'skipped';
@@ -158,3 +202,21 @@ export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | '
return 'failed';
}
}
const signInTries = new WeakMap<Ctx, number>();
/**
* 1.0.2: someone wants to sign in and there's no link to Accounts yet: link now instead of waiting
* for the next heartbeat. If the cached list has no Accounts, the Hub is asked for a fresh one first
* (which links by itself when it lists one). Tried at most every 15 seconds, so visitors opening
* /admin can't make the Website call Accounts or the Hub more often than that.
*/
export async function linkAccountsNow(ctx: Ctx): Promise<void> {
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return;
const now = ctx.now().getTime();
const last = signInTries.get(ctx);
if (last !== undefined && now - last < SIGN_IN_TRY_EVERY_MS) return;
signInTries.set(ctx, now);
if (!(await linkedProducts(ctx)).some((p) => p.product === 'accounts')) await refreshList(ctx);
await connectAccountsIfListed(ctx);
}
+18 -5
View File
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { buildSnapshot, imageOf, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { buildSnapshot, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
@@ -50,6 +50,8 @@ type Common = {
style: { fontPairing: string; corners: string };
/** Search engines' verification codes, for the home page's meta tags (§11). */
verification: { google: string | null; bing: string | null };
/** 1.2.0: the site's own icon (Settings), else null: the church's icon, else one made for it. */
favicon: string | null;
};
export type SiteContent =
@@ -77,6 +79,15 @@ function brandFor(church: Church | null, template: WebsiteTemplate) {
};
}
/** Where the site serves a YouTube video's thumbnail from (site/thumbnails.ts): visitors never ask YouTube. */
export const thumbnailPath = (videoId: string) => `/api/thumbnails/${videoId}.jpg`;
/** A message's thumbnail on the site: its YouTube video's, served from here; none for Spotify. */
export function messageThumbnail(m: { source: string; mediaUrl: string }) {
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
return yt ? thumbnailPath(yt) : null;
}
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
export function youtubeId(url: string): string | null {
try {
@@ -104,7 +115,7 @@ async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
source: m.source === 'spotify' ? 'spotify' : 'youtube',
embedUrl: yt ? `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1` : spotifyEmbed(m.mediaUrl),
url: m.mediaUrl,
thumbnail: m.thumbnailUrl ?? (yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null),
thumbnail: messageThumbnail(m),
};
});
}
@@ -149,13 +160,15 @@ export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTempl
}
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
const [google, bing] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
const [google, bing, faviconId] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
const verification = { google: google || null, bing: bing || null };
const icon = faviconId ? await ctx.db.mediaAsset.findUnique({ where: { id: faviconId } }) : null;
const favicon = icon ? mediaUrl(icon.filename) : null;
if (!published) {
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
return {
mode: 'coming-soon', template, church, ...brandFor(church, template), verification,
mode: 'coming-soon', template, church, ...brandFor(church, template), verification, favicon,
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
@@ -166,5 +179,5 @@ async function contentFrom(ctx: Ctx, church: Church | null, published: { number:
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
}));
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, messages, events };
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, favicon, messages, events };
}
+88
View File
@@ -0,0 +1,88 @@
/**
* The fixed pages (WEBSITE-1.0-PLAN §6) with starter text, for a site that has no pages yet: a new
* install. Without them the home page had no sections (the site and its preview showed only the
* header and footer) and the other pages didn't exist. Terms and Safeguarding come from starter
* text too (§2), linked from the footer rather than the menu.
*
* Checked at startup (ensureStarterPages): a site with none of the fixed pages gets them all, one
* without a home page gets that. A page a church removed (archived) isn't brought back, except home,
* which can't be removed. Nothing is published: the pages are drafts like any other change. The text names no church, since a new install isn't
* always linked to its church profile yet; every section and block can be edited.
*/
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import type { SectionData } from './sections.js';
type Block = { type: string; data: Record<string, unknown> };
type StarterPage = { kind: string; slug: string; title: string; inNav?: boolean; description: string; sections: Block[] };
const VISIT = { label: 'Plan your visit', href: '/visit' };
export const STARTER_HOME: SectionData = {
hero: { headline: 'You are welcome here', subline: 'Join us this Sunday. Come as you are.', images: [], videoId: null, button: VISIT },
serviceTimes: { heading: 'Join us this Sunday', note: null },
welcome: {
heading: 'Welcome', mission: null, imageId: null, pastor: null,
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here.',
},
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
team: { heading: 'Our team', intro: null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: VISIT, imageId: null },
};
const text = (heading: string | null, body: string): Block => ({ type: 'text', data: { heading, body } });
export const STARTER_PAGES: StarterPage[] = [
{ kind: 'home', slug: 'home', title: 'Home', description: 'Join us this Sunday. Come as you are.', sections: Object.entries(STARTER_HOME).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', description: 'What to expect on your first Sunday with us.', sections: [
text('What to expect', 'We sing together, pray, and hear a message from the Bible. Dress is casual, and there is coffee after the service.'),
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Get in touch and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{ kind: 'about', slug: 'about', title: 'About us', description: 'Our story, what we believe and what we value.', sections: [text('Our story', 'Tell your church\'s story here: how it started, what you believe and what you value.')] },
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', description: 'Find your place in our church family.', sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', description: 'The team who lead our church.', sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', description: 'What is coming up at our church.', sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', description: 'Sunday messages from our church.', sections: [] },
{ kind: 'give', slug: 'give', title: 'Give', description: 'How to give to our church.', sections: [text('Giving', 'Thank you for giving. Add how to give here: your bank details, or links to SnapScan, Zapper or PayFast.')] },
{ kind: 'contact', slug: 'contact', title: 'Contact', description: 'How to find us and get in touch.', sections: [] },
{
kind: 'terms', slug: 'terms', title: 'Terms of use', inNav: false, description: 'The terms for using this website.', sections: [
text(null, 'This website is run by our church to share who we are, what we do and when we meet. You may use it for your own, personal purposes.\n\nWe do our best to keep it accurate and up to date, but things change: please check service times and events with us if you are unsure.\n\nLinks to other websites are for your convenience; we are not responsible for what they say.\n\nHow we handle personal information is in our privacy notice, linked at the bottom of every page.'),
],
},
{
kind: 'safeguarding', slug: 'safeguarding', title: 'Safeguarding', inNav: false, description: 'How we keep children and vulnerable adults safe.', sections: [
text(null, 'We are committed to the safety of every child and vulnerable adult in our care. Everyone who serves with children or vulnerable adults is screened and trained, and we follow a written safeguarding policy.\n\nIf you are worried about someone\'s safety, or about how anyone at our church has behaved, please speak to a member of our leadership team. If someone is in immediate danger, contact the police.'),
],
},
];
/**
* Adds the fixed pages a site is missing: all of them while it has none of them (only pages it made
* itself, or nothing at all), else just the home page if that's missing. A page whose address
* another page already has is left out. Custom pages move after them. Returns the kinds added.
*/
export async function ensureStarterPages(ctx: Ctx): Promise<string[]> {
const db = ctx.db;
const existing = await db.page.findMany({ select: { id: true, kind: true, slug: true, position: true, archivedAt: true } });
const fixed = existing.filter((p) => p.kind !== 'custom');
const wanted = fixed.length === 0 ? STARTER_PAGES : fixed.some((p) => p.kind === 'home' && !p.archivedAt) ? [] : STARTER_PAGES.filter((p) => p.kind === 'home');
const slugs = new Set(existing.map((p) => p.slug));
const adding = wanted.filter((p) => !slugs.has(p.slug));
if (!adding.length) return [];
// The site's own pages keep their order, after the fixed ones.
for (const p of existing.filter((x) => x.kind === 'custom')) await db.page.update({ where: { id: p.id }, data: { position: p.position + adding.length } });
let position = 0;
for (const p of adding) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: position++, description: p.description, inNav: p.inNav ?? true } });
let i = 0;
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, position: i++, data: s.data as never } });
}
const kinds = adding.map((p) => p.kind);
await audit(ctx, { actorId: null, actorRole: 'system', action: 'starter_pages_added', targetType: 'page', metadata: { kinds } });
return kinds;
}
@@ -0,0 +1,70 @@
/**
* A message's YouTube thumbnail, served from the site (WEBSITE-1.0-PLAN §7: nothing loads from
* YouTube until a visitor clicks play). The backend fetches `i.ytimg.com/vi/<id>/hqdefault.jpg`
* once and keeps it in `<uploads>/.thumbnails/` (not served from /api/uploads, which denies dot
* folders, and not counted as the church's storage). Only the ids of the site's own messages are
* fetched, so the route is never a proxy for anything else.
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { youtubeId } from './content.js';
export { thumbnailPath } from './content.js';
export type Fetcher = (url: string) => Promise<Response>;
const ID = /^[A-Za-z0-9_-]{6,20}$/;
const MAX_BYTES = 1024 * 1024;
const cacheDir = (ctx: Ctx) => path.join(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), '.thumbnails');
const defaultFetcher: Fetcher = (url) => fetch(url, { signal: AbortSignal.timeout(10_000) });
/** One fetch per video at a time, however many visitors ask at once. */
const inFlight = new Map<string, Promise<Buffer | null>>();
async function isOurVideo(ctx: Ctx, videoId: string) {
const rows = await ctx.db.message.findMany({ where: { mediaUrl: { contains: videoId } }, select: { mediaUrl: true, source: true }, take: 5 });
return rows.some((m) => m.source !== 'spotify' && youtubeId(m.mediaUrl) === videoId);
}
async function download(fetcher: Fetcher, videoId: string): Promise<Buffer | null> {
try {
const res = await fetcher(`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`);
if (!res.ok || !/^image\/jpe?g/.test(res.headers.get('content-type') ?? '')) return null;
const body = Buffer.from(await res.arrayBuffer());
// A JPEG by its bytes, and a sensible size.
if (body.length > MAX_BYTES || body.length < 3 || body[0] !== 0xff || body[1] !== 0xd8 || body[2] !== 0xff) return null;
return body;
} catch {
return null;
}
}
/** The thumbnail's bytes, from the cache or YouTube; null when it isn't one of the site's videos or YouTube has none. */
export async function thumbnail(ctx: Ctx, videoId: string, fetcher: Fetcher = ctx.fetch ?? defaultFetcher): Promise<Buffer | null> {
if (!ID.test(videoId)) return null;
const file = path.join(cacheDir(ctx), `${videoId}.jpg`);
try {
return await fs.readFile(file);
} catch {
// Not cached yet.
}
if (!(await isOurVideo(ctx, videoId))) return null;
let pending = inFlight.get(videoId);
if (!pending) {
pending = (async () => {
const body = await download(fetcher, videoId);
if (body) {
await fs.mkdir(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
await fs.writeFile(tmp, body);
await fs.rename(tmp, file);
}
return body;
})().finally(() => inFlight.delete(videoId));
inFlight.set(videoId, pending);
}
return pending;
}
+67 -1
View File
@@ -10,7 +10,7 @@ import { buildExport } from '../src/export/churchExport.js';
import { stats } from '../src/hub/client.js';
import { connectAccountsIfListed } from '../src/links/connect.js';
import { keyPair, saveLinkedProducts } from '../src/links/store.js';
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID } from './support/harness.js';
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID, SITE } from './support/harness.js';
const accountsKeys = generateEd25519();
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
@@ -88,6 +88,72 @@ describe('linking to the church\'s Accounts', () => {
});
});
/** A Hub answering heartbeats with `list` as the church's products (only what the Website reads). */
async function fakeHub(list: () => unknown[]) {
const calls: string[] = [];
const server = http.createServer((req, res) => {
calls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: list() }));
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, calls };
}
describe('1.0.2: linking right after an install', () => {
it('links to Accounts when someone opens /admin, asking the Hub for a fresh list first', async () => {
let accountsUrl = '';
const hubServer = await fakeHub(() => [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accountsUrl, publicKey: accountsPublic }]);
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true', HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
accountsUrl = accounts.url;
// The Website's cached list has no Accounts yet (it registered before the Hub knew of one).
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//, 'off to Accounts, not the problem page');
assert.deepEqual(hubServer.calls, ['/api/installs/heartbeat']);
assert.equal(accounts.seen.length, 1, 'one connect, not one from the heartbeat and another from the sign-in');
assert.equal(await h.db.productLink.count({ where: { product: 'accounts' } }), 1);
});
it('tries again at most every 15 seconds while it can\'t link', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const hubServer = await fakeHub(() => []);
const h = await harness({ linked: false, env: { HUB_URL: hubServer.url } });
h.ctx.now = () => clock;
await h.ctx.settings.set('hub_install_secret', 'secret');
const problem = `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`;
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal(hubServer.calls.length, 1);
clock = new Date(clock.getTime() + 61_000);
await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(hubServer.calls.length, 2);
});
it('accepts a connect from a product installed after its last heartbeat (Events, for the event feed)', async () => {
const EVENTS_INSTALL_ID = '4d2e8f3a-9b1c-4d0e-8f7a-6b5c4d3e2f1a';
const eventsKeys = generateEd25519();
const events = { product: 'events', installId: EVENTS_INSTALL_ID, url: 'https://events.hope.test', publicKey: ed25519PublicToPem(eventsKeys.publicKey) };
const hubServer = await fakeHub(() => [events]);
const h = await harness({ env: { HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const m = signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'events', installId: EVENTS_INSTALL_ID, url: events.url },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, eventsKeys.privateKeyPem);
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(hubServer.calls.length, 1);
assert.equal(await h.db.productLink.count({ where: { product: 'events' } }), 1);
});
});
describe('the heartbeat and the export', () => {
it('reports aggregate counts the Hub accepts', async () => {
const h = await harness();
@@ -55,6 +55,18 @@ describe('settings, the menu and the audit log', () => {
assert.equal((await go('put', '/settings', { googleVerification: '<script>' })).status, 400);
});
it('sets the site icon from the media library, live at once, and takes it off again', async () => {
const { go, ctx, db } = await site();
assert.equal((await siteContent(ctx)).favicon, null, 'none: the site uses its default');
const m = await db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 100, width: 512, height: 512 } });
assert.equal((await go('put', '/settings', { faviconId: '00000000-0000-4000-8000-0000000000ff' })).body.error.fields.faviconId, 'That picture isn\'t in the media library');
const r = await go('put', '/settings', { faviconId: m.id });
assert.equal(r.body.faviconId, m.id);
assert.equal((await siteContent(ctx)).favicon, '/api/uploads/icon.png');
assert.equal((await go('put', '/settings', { faviconId: null })).body.faviconId, null);
assert.equal((await siteContent(ctx)).favicon, null);
});
it('orders the menu, and the audit log says who did what', async () => {
const { go, db } = await site();
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
+1 -1
View File
@@ -35,7 +35,7 @@ describe('signing in to the admin through Accounts', () => {
const h = await harness({ linked: false });
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_UNAVAILABLE&returnTo=%2Fadmin`);
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`);
});
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
+119 -2
View File
@@ -4,12 +4,14 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
import { loadDemo } from '../src/demo/demoChurch.js';
import { WEBSITE_TEMPLATES, agent } from '@crosscode/contracts';
import { demoProfile, loadDemo, seedDesign } from '../src/demo/demoChurch.js';
import { DEMO_SEEDS, demoSeeds } from '../src/demo/seeds.js';
import { siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
import { parseSectionData } from '../src/site/sections.js';
import { buildSnapshot, cleanDesign, publish } from '../src/site/snapshot.js';
import { thumbnail } from '../src/site/thumbnails.js';
import { defaultDesign } from '../src/site/variants.js';
import { harness } from './support/harness.js';
@@ -121,6 +123,67 @@ describe('the public site\'s content', () => {
});
}
for (const profile of agent.WEBSITE_DEMO_PROFILES) {
it(`1.3.0: loads the ${profile} demo, keeping the church's own profile and naming it`, async () => {
const h = await harness({ linked: false });
const dir = tmp();
const own = { ...demoProfile('http://x.test'), name: 'Grace Point Church', shortName: 'Grace Point', branding: { ...demoProfile('').branding, colours: { primary: '#8a1538', accent: '#f2c14e' } } };
await h.ctx.settings.set('church_profile_local', JSON.stringify(own));
await loadDemo(h.ctx, profile, { uploadDir: dir });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const seed = DEMO_SEEDS[profile];
assert.equal(c.snapshot.design.template, seed.template);
assert.equal(c.church?.name, 'Grace Point Church', 'the organisation settings stay');
assert.equal(c.snapshot.pages.length, 9);
assert.equal(c.snapshot.ministries.length, 4);
assert.equal(c.messages.length, 3);
assert.equal(c.events.length, 3);
const all = JSON.stringify(c.snapshot);
assert.doesNotMatch(all, /\{(name|short|city)\}/, 'every placeholder is filled in');
assert.doesNotMatch(all, /Acacia/, 'nothing of the development church');
assert.equal(c.snapshot.design.variants.hero, seedDesign(seed.template, seed.alternate).variants.hero);
assert.match(fs.readFileSync(path.join(dir, 'demo', 'hero.svg'), 'utf8'), /#8a1538/, 'pictures in the church\'s colours');
});
}
it('1.3.0: the two profiles of a template differ, the second on its other recommended variants and header', () => {
for (const template of WEBSITE_TEMPLATES) {
const [a, b] = demoSeeds().filter((s) => s.template === template);
assert.ok(a && b && !a.alternate && b.alternate, template);
const alt = seedDesign(template, true);
assert.notDeepEqual(alt.variants, seedDesign(template, false).variants);
assert.notEqual(alt.style.header, seedDesign(template, false).style.header);
assert.notEqual(a.hero.headline, b.hero.headline);
}
});
it('1.3.0: a profile keeps the site icon and the settings, and clears the old content, slugs and preview links', async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const icon = (await h.db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 10, width: 64, height: 64, alt: 'Icon' } })) as { id: string };
await h.ctx.settings.set('favicon_media_id', icon.id);
await h.ctx.settings.set('coming_soon_text', 'Soon!');
await h.db.slugHistory.create({ data: { slug: 'old-about', pageId: 'gone' } });
await loadDemo(h.ctx, 'community-town', { uploadDir: dir });
assert.ok(await h.db.mediaAsset.findUnique({ where: { id: icon.id } }), 'the site icon stays');
assert.equal(await h.ctx.settings.get('favicon_media_id'), icon.id);
assert.equal(await h.ctx.settings.get('coming_soon_text'), 'Soon!');
assert.equal(await h.db.mediaAsset.count(), 11, 'the ten pictures and the icon');
assert.equal(await h.db.slugHistory.count(), 0);
assert.equal((await siteContent(h.ctx)).church?.name, 'Acacia Hill Church', 'the profile saved by the first demo stays');
});
it('1.3.0: a profile on a site with no church profile at all saves the demo one, so the site has a name', async () => {
const h = await harness({ linked: false });
await loadDemo(h.ctx, 'clean-campus', { uploadDir: tmp() });
const c = await siteContent(h.ctx);
assert.equal(c.church?.name, 'Acacia Hill Church');
assert.ok(c.mode === 'published' && JSON.stringify(c.snapshot).includes('Welcome to Acacia Hill'));
});
it('serves the uploads, never a folder or outside it, and the content over HTTP', async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
@@ -137,6 +200,60 @@ describe('the public site\'s content', () => {
});
});
describe("the messages' thumbnails, served from the site (§7)", () => {
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const youtube = (body: Buffer | string, type = 'image/jpeg', status = 200) => {
const asked: string[] = [];
const fetcher = async (url: string) => { asked.push(url); return new Response(typeof body === 'string' ? body : new Uint8Array(body), { status, headers: { 'content-type': type } }); };
return { asked, fetcher };
};
it("gives visitors the site's own address, never YouTube's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const content = await siteContent(h.ctx);
assert.ok(content.mode === 'published' && content.messages.length > 0);
for (const m of content.messages) assert.equal(m.thumbnail, '/api/thumbnails/aqz-KE-bpKQ.jpg');
});
it("fetches a message's thumbnail once and keeps it; nothing for a video that isn't the site's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const yt = youtube(jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(yt.asked, ['https://i.ytimg.com/vi/aqz-KE-bpKQ/hqdefault.jpg']);
assert.ok(fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
// Kept out of /api/uploads (a dot folder).
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/.thumbnails/aqz-KE-bpKQ.jpg')).status));
// Not one of the site's messages, or not an id: YouTube isn't asked.
assert.equal(await thumbnail(h.ctx, 'someoneElse1', yt.fetcher), null);
assert.equal(await thumbnail(h.ctx, '../../etc/x', yt.fetcher), null);
assert.equal(yt.asked.length, 1);
});
it("keeps nothing that isn't a JPEG, and says 404 when YouTube has none", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('<html>', 'text/html').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube(Buffer.from('GIF89a'), 'image/jpeg').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('', 'image/jpeg', 404).fetcher), null);
assert.ok(!fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
h.ctx.fetch = youtube('', 'image/jpeg', 404).fetcher;
const missing = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(missing.status, 404);
assert.equal(missing.headers['cache-control'], 'no-store');
h.ctx.fetch = youtube(jpeg).fetcher;
const ok = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(ok.status, 200);
assert.equal(ok.headers['content-type'], 'image/jpeg');
assert.equal((await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.png')).status, 404);
});
});
describe('message links', () => {
it('finds YouTube ids and Spotify embeds', () => {
assert.equal(youtubeId('https://www.youtube.com/watch?v=aqz-KE-bpKQ'), 'aqz-KE-bpKQ');
@@ -0,0 +1,42 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { previewContent } from '../src/site/content.js';
import { ensureStarterPages, STARTER_PAGES } from '../src/site/starter.js';
import { harness } from './support/harness.js';
describe('a new install\'s starter pages', () => {
it('adds the fixed pages to a site with none, and the preview shows every homepage section', async () => {
const { ctx, db } = await harness({ linked: false });
assert.deepEqual(await ensureStarterPages(ctx), STARTER_PAGES.map((p) => p.kind));
const c = await previewContent(ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const home = c.snapshot.pages.find((p) => p.kind === 'home')!;
assert.deepEqual(home.sections.map((s) => s.type).sort(), ['events', 'hero', 'invitation', 'latestMessage', 'ministries', 'serviceTimes', 'team', 'welcome']);
// Every starter block fits its schema (a broken one would be left out of the site).
for (const p of STARTER_PAGES) assert.equal(c.snapshot.pages.find((x) => x.kind === p.kind)!.sections.length, p.sections.length, p.kind);
// Terms and Safeguarding are footer links, not menu items.
assert.equal(c.snapshot.pages.filter((p) => p.inNav).some((p) => p.kind === 'terms' || p.kind === 'safeguarding'), false);
// Only once.
assert.deepEqual(await ensureStarterPages(ctx), []);
assert.equal(await db.page.count(), STARTER_PAGES.length);
});
it('keeps the church\'s own pages, after the fixed ones, and skips an address they already use', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'custom', slug: 'test', title: 'Test', position: 1 } });
await db.page.create({ data: { kind: 'custom', slug: 'give', title: 'Giving', position: 2 } });
const kinds = await ensureStarterPages(ctx);
assert.ok(kinds.includes('home') && !kinds.includes('give'));
const pages = await db.page.findMany({ orderBy: { position: 'asc' } });
assert.equal(pages[0]!.kind, 'home');
assert.deepEqual(pages.slice(-2).map((p) => p.slug), ['test', 'give']);
});
it('adds only a missing home page to a site that has its other fixed pages', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', archivedAt: new Date() } });
assert.deepEqual(await ensureStarterPages(ctx), ['home']);
assert.deepEqual(await ensureStarterPages(ctx), []);
});
});
+26 -1
View File
@@ -21,10 +21,12 @@ async function signIn(context: BrowserContext, role = "editor") {
async function aboutTitle(page: Page, title: string) {
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.
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
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.getByRole("button", { name: "Save details" }).click();
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();
});
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 }) => {
await signIn(context);
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();
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([]);
});
+9 -2
View File
@@ -13,12 +13,13 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import pg from 'pg';
import sharp from 'sharp';
import { PrismaPg } from '@prisma/adapter-pg';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../backend/src/generated/prisma/client.js';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
import { loadDemo } from '../backend/src/demo/demoChurch.js';
import { illustration, loadDemo } from '../backend/src/demo/demoChurch.js';
import { loadConfig } from '../backend/src/lib/config.js';
import { hashToken } from '../backend/src/lib/crypto.js';
import { publish } from '../backend/src/site/snapshot.js';
@@ -55,7 +56,13 @@ async function freshPostgres(url: string) {
// A frozen clock (a Monday morning), so the demo's dates, and so the screenshots, are the same every
// run (variants.spec.ts). E2E_NOW changes it.
const frozen = new Date(process.env.E2E_NOW ?? '2026-11-23T06:00:00Z');
const ctx = createCtx(loadConfig({ WEBSITE_URL: 'http://localhost:3310', NODE_ENV: 'test', JOBS_ENABLED: 'false', HUB_URL: 'http://127.0.0.1:1', UPLOAD_DIR: uploads, TRUST_PROXY: 'true' }), db as never, { now: () => new Date(frozen) });
// YouTube's thumbnails (site/thumbnails.ts) without the network: one of the demo's illustrations,
// as a JPEG the size of YouTube's, for every video.
const thumb = await sharp(Buffer.from(illustration(4, 480, 360))).jpeg().toBuffer();
const fakeYoutube = async (url: string) => url.startsWith('https://i.ytimg.com/')
? new Response(new Uint8Array(thumb), { headers: { 'content-type': 'image/jpeg' } })
: new Response('not here', { status: 404 });
const ctx = createCtx(loadConfig({ WEBSITE_URL: 'http://localhost:3310', NODE_ENV: 'test', JOBS_ENABLED: 'false', HUB_URL: 'http://127.0.0.1:1', UPLOAD_DIR: uploads, TRUST_PROXY: 'true' }), db as never, { now: () => new Date(frozen), fetch: fakeYoutube });
await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'heritage'), { uploadDir: uploads });
const app = express();
+13
View File
@@ -64,6 +64,19 @@ test("the home page has the church's JSON-LD; unknown pages are a real 404", asy
expect((await page.goto("/no-such-page"))?.status()).toBe(404);
});
test("the messages ask nothing of YouTube until play is clicked; their thumbnails come from the site", async ({ page }) => {
await useTemplate(page, "heritage");
const outside: string[] = [];
page.on("request", (r) => { if (/youtube|ytimg|spotify/.test(new URL(r.url()).hostname)) outside.push(r.url()); });
await page.goto("/messages");
const thumb = page.locator("main img").first();
await expect(thumb).toHaveAttribute("src", /^\/api\/thumbnails\/[\w-]+\.jpg$/);
await expect.poll(() => thumb.evaluate((i: HTMLImageElement) => i.naturalWidth)).toBeGreaterThan(0);
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForLoadState("networkidle");
expect(outside).toEqual([]);
});
test("robots.txt keeps the admin out; the sitemap lists the pages", async ({ page }) => {
const robots = await (await page.request.get("/robots.txt")).text();
expect(robots).toContain("Disallow: /admin");
+20 -2
View File
@@ -10,7 +10,7 @@
* (`npx playwright test variants --update-snapshots`, then look through them), and the next
* release's run shows every section that changed. The e2e server freezes the clock (E2E_NOW), so
* the demo's dates never change between runs. What comes from outside is masked: the video, the
* map (OpenStreetMap) and YouTube's thumbnails.
* map (OpenStreetMap) and the messages' thumbnails.
*/
import AxeBuilder from "@axe-core/playwright";
import { expect, test, type Page } from "@playwright/test";
@@ -43,6 +43,23 @@ async function loadImages(page: Page) {
expect(broken, "images that didn't load").toEqual([]);
}
/**
* A section's screenshot is as big as its box, rounded where it starts and ends on the page. With
* fractional heights above it (text, aspect ratios), the same section came out a pixel taller or
* shorter from run to run, which fails `toHaveScreenshot` however small the difference. So the
* header and every section get their own height rounded up first: each section then starts on a
* whole pixel and is the same size every run.
*/
async function wholePixels(page: Page) {
await page.evaluate(() => {
// The header and the sections, not what holds them (main grows to fit).
const blocks = Array.from(document.querySelectorAll<HTMLElement>("header:not(main header), main > section"));
for (const b of blocks) b.style.height = "";
const heights = blocks.map((b) => b.getBoundingClientRect().height);
blocks.forEach((b, n) => { if (getComputedStyle(b).position !== "fixed") b.style.height = `${Math.ceil(heights[n]!)}px`; });
});
}
for (const template of TEMPLATES) {
test.describe(`${template} variants`, () => {
test.beforeAll(async ({ request }) => {
@@ -67,8 +84,9 @@ for (const template of TEMPLATES) {
for (const [name, size] of WIDTHS) {
await page.setViewportSize(size);
await loadImages(page);
await wholePixels(page);
await expect(section).toHaveScreenshot(`${template}-${type}-${variant}-${name}.png`, {
mask: [page.locator("main video"), page.locator("main [data-map]"), page.locator('main img[src*="ytimg.com"]')],
mask: [page.locator("main video"), page.locator("main [data-map]"), page.locator('main img[src*="/api/thumbnails/"]')],
animations: "disabled",
maxDiffPixelRatio: 0.01,
});
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-frontend",
"version": "1.0.0",
"version": "1.3.0",
"private": true,
"description": "Church Website: the church's public site in its template, and the admin",
"scripts": {
@@ -14,6 +14,7 @@
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6",
"react": "^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";
/** 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 { usePathname } from "next/navigation";
import { useMemo, useState } from "react";
import { Eye, Globe, LogOut, Menu, X } from "lucide-react";
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 = [
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/template", label: "Template and style" },
{ href: "/admin/church", label: "Church details" },
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" },
{ href: "/admin/leaders", label: "Leadership" },
{ href: "/admin/messages", label: "Messages" },
{ href: "/admin/events", label: "Events" },
{ href: "/admin/linked", label: "Linked products" },
{ href: "/admin/media", label: "Media library" },
{ href: "/admin/publish", label: "Publish and history" },
{ href: "/admin/settings", label: "Settings" },
{ href: "/admin/people", label: "People", managers: true },
{ href: "/admin/audit", label: "Audit log", managers: true },
];
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
/** Pages that use the whole width: the editors with the preview beside them. */
const wide = (path: string) => path === "/admin/template" || /^\/admin\/pages\/[^/]+$/.test(path);
function SideNav({ role, path, pending, onNavigate }: { role: string; path: string; pending: number; onNavigate?: () => void }) {
const managers = ["owner", "admin"].includes(role);
return (
<nav aria-label="Admin" className="space-y-5">
{NAV_GROUPS.map((g, gi) => {
const items = g.items.filter((n) => !n.managers || managers);
if (!items.length) return null;
return (
<div key={g.title ?? gi}>
{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 }) {
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 (
<div className="min-h-screen bg-gray-50 font-sans text-gray-900">
<header className="border-b border-gray-200 bg-white">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-3">
<Link href="/admin" className="font-semibold">Website admin</Link>
<div className="flex flex-wrap items-center gap-3 text-sm">
{data && data.pending > 0 && <Link href="/admin/publish" className="rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-900">{data.pending} {data.pending === 1 ? "change" : "changes"} not published</Link>}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
<a href="/preview/start" className="rounded-md border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50">Preview</a>
<span className="text-gray-600">{user.name} · {ROLE_NAMES[user.role] ?? user.role}</span>
<form method="post" action="/api/auth/signout"><button type="submit" className="text-gray-600 underline-offset-4 hover:underline">Sign out</button></form>
<OverviewContext.Provider value={ctx}>
<div className="min-h-screen bg-gray-50 font-sans text-gray-900">
<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>
<header className="sticky top-0 z-30 border-b border-gray-200 bg-white/95 backdrop-blur">
<div className="flex items-center justify-between gap-3 px-4 py-2.5">
<div className="flex min-w-0 items-center gap-2">
<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>
<Link href="/admin" className="flex min-w-0 items-center gap-2 font-semibold">
<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>
<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>
</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>
</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>
</OverviewContext.Provider>
);
}
+1 -1
View File
@@ -59,7 +59,7 @@ export function ImagePicker({ value, onChange, label }: { value: string | null;
<span className="block text-sm font-medium text-gray-800">{label}</span>
<div className="mt-1 flex items-center gap-3">
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-400">No image</span>}
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
</div>
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
+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";
/** The admin's own building blocks: plain, calm, the church's colour for the main action. */
import { useCallback, useEffect, useState } from "react";
/** The admin's own building blocks: plain, calm, the church's colour for the main action (as Cross Events' dashboard). */
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";
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 (
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-gray-600">{sub}</p>}
<div className="flex min-w-0 items-start gap-3">
{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>}
<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>
{actions && <div className="flex flex-wrap gap-2">{actions}</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 (
<section className={cx("rounded-lg border border-gray-200 bg-white p-5 shadow-sm", className)}>
{title && <h2 className="mb-4 text-lg font-semibold text-gray-900">{title}</h2>}
<section className={cx("rounded-xl border border-gray-200 bg-white p-5 shadow-sm", className)}>
{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}
</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) {
return (
@@ -36,15 +108,17 @@ export function Btn({ kind = "secondary", busy, className, children, disabled, .
{...rest}
disabled={disabled || busy}
className={cx(
"inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50",
"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 === "secondary" && "border border-gray-300 bg-white text-gray-800 hover:bg-gray-50",
kind === "danger" && "border border-red-300 bg-white text-red-700 hover:bg-red-50",
kind === "link" && "px-0 py-0 text-brand-text underline-offset-4 hover:underline",
kind === "icon" && "h-8 w-8 border border-gray-200 bg-white text-gray-600 hover:bg-gray-50 hover:text-gray-900",
className,
)}
>
{busy ? "Working…" : children}
{busy && kind !== "icon" ? "Working…" : children}
</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 }) {
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. */
@@ -88,8 +162,18 @@ export function useAdmin<T>(path: string | null) {
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() {
const { refresh } = useOverview();
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
const [fields, setFields] = useState<Record<string, string>>({});
@@ -107,8 +191,9 @@ export function useAction() {
return null;
} finally {
setBusy(false);
refresh();
}
}, []);
}, [refresh]);
return { busy, message, fields, run, setMessage };
}
@@ -4,6 +4,7 @@
import { useState } from "react";
import { api } from "@/admin/api";
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 };
@@ -15,7 +16,7 @@ export default function Audit() {
const all = [...first.data, ...more];
return (
<>
<Title sub="Who changed what, newest first.">Audit log</Title>
<Title icon={ScrollText} sub="Who changed what, newest first.">Audit log</Title>
<Panel>
{all.length === 0 && <p className="text-gray-600">Nothing yet.</p>}
<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 { ImagePicker } from "@/admin/media";
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 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];
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></>}>
Church details
</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<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">
<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>
@@ -79,7 +80,7 @@ export default function ChurchDetails() {
</div>
</Panel>
<Panel title="Service times">
<Panel icon={Clock} title="Service times">
<ul className="space-y-3">
{times.map((t, i) => (
<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>
</Panel>
<Panel title="Contact and address">
<Panel icon={MapPin} title="Contact and address">
<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="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>
</Panel>
<Panel title="Social links">
<Panel icon={Share2} title="Social links">
<ul className="space-y-2">
{c.social.map((s, i) => (
<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 { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { CalendarDays } from "lucide-react";
type Ev = {
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 (
<>
<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>}
<div className="space-y-6">
{mayWrite(null) && (
@@ -3,13 +3,14 @@
import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor";
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. */
export default function Leaders() {
const { data } = useAdmin<{ user: { role: string } }>("/me");
return (
<>
<Title sub="The people who lead your church. The first is shown largest in the Featured layout.">Leadership</Title>
<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={[
{ key: "name", label: "Name", kind: "text", max: 120 },
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
@@ -8,6 +8,7 @@
*/
import { api, canEdit } from "@/admin/api";
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 };
@@ -22,7 +23,7 @@ export default function Linked() {
const manager = ["owner", "admin"].includes(me.data.user.role);
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>}
<div className="space-y-6">
<Panel title="Publish my events">
@@ -4,6 +4,7 @@ import { useState } from "react";
import { api } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, 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. */
export default function Media() {
@@ -17,7 +18,7 @@ export default function Media() {
const s = data.storage;
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]">
<Panel>
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
@@ -8,6 +8,7 @@
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
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 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;
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>}
<div className="space-y-6">
<Panel title="From YouTube, automatically">
@@ -3,13 +3,14 @@
import { canEdit } from "@/admin/api";
import { ListEditor } from "@/admin/ListEditor";
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. */
export default function Ministries() {
const { data } = useAdmin<{ user: { role: string } }>("/me");
return (
<>
<Title sub="Your ministries' pages. A ministry leader can edit their own; an editor publishes it.">Ministries</Title>
<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={[
{ 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.”" },
+70 -33
View File
@@ -1,51 +1,88 @@
"use client";
import Link from "next/link";
import { StorageMeter, type Storage } from "@/admin/media";
import { Loading, Notice, Panel, Title, useAdmin, when } from "@/admin/ui";
import { Clock, Globe, HardDrive, History, LayoutGrid, Send } from "lucide-react";
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 = {
pending: number;
lastPublished: { number: number; at: string } | null;
type Full = Overview & {
storage: Storage;
colourNotes: string[];
checklist: { key: string; label: string; done: boolean; href: 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() {
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} />;
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 (
<>
<Title sub={data.lastPublished ? `Last published ${when(data.lastPublished.at)} (version ${data.lastPublished.number}).` : "Your site shows Coming soon until you publish it."}>Dashboard</Title>
<div className="grid gap-6 lg:grid-cols-2">
<Panel title="Getting your site ready">
<ol className="space-y-3">
{data.checklist.map((c) => (
<li key={c.key} className="flex items-start gap-3">
<span aria-hidden="true" className={c.done ? "text-green-700" : "text-gray-400"}>{c.done ? "✓" : "○"}</span>
<span className={c.done ? "text-gray-500 line-through" : ""}>{c.href ? <Link href={c.href} className="underline-offset-4 hover:underline">{c.label}</Link> : c.label}</span>
<span className="sr-only">{c.done ? "(done)" : "(to do)"}</span>
</li>
))}
</ol>
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Welcome back{first ? `, ${first}` : ""}</h1>
<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>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<StatCard icon={Globe} label="Your site" value={live ? "Live" : "Coming soon"} tone={live ? "green" : "amber"}
detail={live ? `Version ${data.lastPublished!.number}` : `${stepsLeft} ${stepsLeft === 1 ? "step" : "steps"} to go`} href="/preview/start" linkLabel="Preview it" />
<StatCard icon={Send} label="Changes not published" value={data.pending} tone={data.pending ? "amber" : "gray"}
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"}
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>
<div className="space-y-6">
<Panel title="Waiting to be published">
{data.pending ? (
<p>{data.pending} {data.pending === 1 ? "change" : "changes"}. <Link href="/admin/publish" className="font-semibold text-brand-text underline-offset-4 hover:underline">Review and publish</Link></p>
) : <p className="text-gray-600">Nothing: the site shows everything you&apos;ve done.</p>}
</Panel>
<Panel title="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>
<Panel title="Storage" icon={HardDrive}><StorageMeter s={data.storage} /></Panel>
{data.colourNotes.length > 0 && (
<Notice tone="info"><p className="font-semibold">About your colours</p><ul className="mt-1 list-disc pl-5">{data.colourNotes.map((n) => <li key={n}>{n}</li>)}</ul></Notice>
)}
@@ -1,19 +1,27 @@
"use client";
/**
* One page (§6): its title, address, menu and search engine details, then its content. The home
* page has one of each homepage section (their layouts are set under Template and style); every
* other page is built from blocks, which can be added, moved and removed.
* One page (§6), with its live preview on the right. Content: the home page has one of each
* 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, 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 { 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 { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { WithPreview } from "@/admin/LivePreview";
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 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 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.",
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 [open, setOpen] = useState(false);
const { busy, message, fields: errors, run } = useAction();
const Icon = ICONS[type] ?? FileText;
const line = summary(initial);
return (
<Panel>
<div className="flex items-center justify-between gap-3">
<h3 className="font-semibold">{title}</h3>
<div className="flex gap-2">{extra}<Btn onClick={() => setOpen(!open)} aria-expanded={open}>{open ? "Close" : "Edit"}</Btn></div>
<section className={cx("rounded-xl border bg-white shadow-sm", open ? "border-brand/40" : "border-gray-200")}>
<div className="flex items-center gap-2 p-3">
<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">
<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>
{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} />
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
<div className="flex flex-wrap items-center gap-3">
<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>
)}
</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 router = useRouter();
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 [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} />;
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.");
const blockCall = (path: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${path}`, { method, body })));
const path = isHome ? "/" : `/${page.slug}`;
const blockCall = (p: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${p}`, { method, body })));
// The home page's sections in the order the site shows them, and whether each shows.
const home = design.data?.design.home ?? HOME_ORDER.map((section) => ({ section, hidden: false }));
return (
<>
<Title sub={page.kind === "home" ? "Your home page" : `Your site/${page.slug}`}
actions={page.kind !== "home" && <Btn kind="danger" onClick={() => details.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); })}>Remove page</Btn>}>
<WithPreview path={path} version={version}>
<Link href="/admin/pages" className="mb-1 inline-block text-sm text-gray-500 hover:text-gray-800">← All pages</Link>
<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}
</Title>
<div className="space-y-6">
<Panel title="Page details">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Title" error={details.fields.title}><input className={inputClass} value={f.title ?? ""} maxLength={120} onChange={(e) => setForm({ ...form, title: e.target.value })} /></Field>
{page.kind !== "home" && <Field label="Address" hint={`Your site/${f.slug}`} error={details.fields.slug}><input className={inputClass} value={f.slug ?? ""} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></Field>}
{page.kind !== "home" && <Field label="Name in the menu" hint="Leave empty to use the title."><input className={inputClass} value={f.navLabel ?? ""} maxLength={40} onChange={(e) => setForm({ ...form, navLabel: e.target.value || null })} /></Field>}
{page.kind !== "home" && <label className="flex items-center gap-2 self-end pb-2 text-sm"><input type="checkbox" checked={!!f.inNav} onChange={(e) => setForm({ ...form, inNav: e.target.checked })} />Show in the menu</label>}
<Field label="Title in search results" hint={`${(f.seoTitle ?? f.title ?? "").length} of 60 characters`} error={details.fields.seoTitle}><input className={inputClass} value={f.seoTitle ?? ""} maxLength={70} onChange={(e) => setForm({ ...form, seoTitle: e.target.value || null })} placeholder={f.title} /></Field>
<Field label="Description in search results" hint={`${(f.description ?? "").length} of 155 characters${f.description ? "" : ": add one, so search engines show what this page is about"}`} error={details.fields.description}>
<textarea className={inputClass} rows={2} value={f.description ?? ""} maxLength={300} onChange={(e) => setForm({ ...form, description: e.target.value || null })} />
</Field>
<div className="sm:col-span-2"><ImagePicker label="Image when shared (optional)" value={f.imageId ?? null} onChange={(imageId) => setForm({ ...form, imageId })} /></div>
</div>
{/* A Google-style preview of the search result (ROADMAP-v3 §11). */}
<div className="mt-4 rounded border border-gray-200 p-3" aria-label="How it may look in search results">
<p className="truncate text-lg text-blue-800">{f.seoTitle || f.title}</p>
<p className="line-clamp-2 text-sm text-gray-600">{f.description || "No description yet."}</p>
</div>
<div className="mt-4 flex items-center gap-3">
<Btn kind="primary" busy={details.busy} onClick={saveDetails}>Save details</Btn>
{details.message && <Notice tone={details.message.tone}>{details.message.text}</Notice>}
</div>
</Panel>
{remove.message?.tone === "error" && <div className="mb-4"><Notice tone="error">{remove.message.text}</Notice></div>}
{page.kind === "home" ? (
<>
<p className="text-sm text-gray-600">Each section&apos;s layout, order and whether it shows are under Template and style.</p>
{HOME_ORDER.map((type) => {
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type]!;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
})}
</>
) : (
<>
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
{page.sections.map((s, i) => {
const spec = BLOCK_FIELDS[s.type];
if (!spec) return null;
return (
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
extra={<>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down">↓</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}`, "PUT", { hidden: !s.hidden })}>{s.hidden ? "Show" : "Hide"}</Btn>
<Btn kind="danger" onClick={() => blockCall(`/blocks/${s.id}`, "DELETE")}>Remove</Btn>
</>} />
);
})}
<Panel title="Add a block">
<div className="flex flex-wrap gap-2">
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => <Btn key={type} busy={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}>{spec.name}</Btn>)}
</div>
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>}
</Panel>
</>
)}
<Tabs label="This page" value={tab} onChange={setTab} tabs={[
{ id: "content", label: isHome ? "Sections" : "Content", icon: LayoutList },
{ id: "details", label: "Page details", icon: Settings2 },
]} />
{/* Both stay mounted, so switching tabs keeps what's not saved yet. */}
<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>
{home.map(({ section: type, hidden }) => {
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type];
if (!spec) return null;
return <SectionEditor key={type} type={type} title={spec.name} 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}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
})}
</div>
) : (
<div className="space-y-3">
{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];
if (!spec) return null;
return (
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data}
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>}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
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>
</>
</WithPreview>
);
}
@@ -3,12 +3,19 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
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 { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type PageRow = { id: string; kind: string; slug: string; title: string; inNav: boolean; path: string };
const KINDS: Record<string, string> = { home: "Home", visit: "Plan your visit", about: "About", leadership: "Leadership", ministries: "Ministries", events: "Events", messages: "Messages", give: "Give", contact: "Contact", terms: "Terms", safeguarding: "Safeguarding", custom: "Your own page" };
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. */
export default function Pages() {
@@ -24,22 +31,29 @@ export default function Pages() {
});
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]">
<Panel>
<ul className="divide-y divide-gray-200">
{data.map((p) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-3">
<div>
<Link href={`/admin/pages/${p.id}`} className="font-medium underline-offset-4 hover:underline">{p.title}</Link>
<p className="text-xs text-gray-500">{KINDS[p.kind] ?? p.kind} · {p.path}{!p.inNav && p.kind !== "home" && " · not in the menu"}</p>
</div>
<Link href={`/admin/pages/${p.id}`} className="text-sm font-semibold text-brand-text">Edit</Link>
</li>
))}
<Panel className="!p-2">
<ul className="divide-y divide-gray-100">
{data.map((p) => {
const [kind, Icon] = KINDS[p.kind] ?? [p.kind, FileText];
return (
<li key={p.id}>
<Link href={`/admin/pages/${p.id}`} className="group flex items-center gap-3 rounded-lg px-3 py-3 hover:bg-gray-50">
<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="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>
</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">
<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>
@@ -7,6 +7,7 @@
import { useState } from "react";
import { api, ROLE_NAMES } from "@/admin/api";
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 };
@@ -50,7 +51,7 @@ export default function People() {
const mayTouch = (p: Person) => p.id !== me.data!.user.id && (owner || p.role !== "owner");
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>}
<div className="grid gap-6 lg:grid-cols-[3fr_2fr]">
<Panel>
@@ -8,6 +8,7 @@
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
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 Version = { number: number; publishedAt: string; by: string | null; note: string | null };
@@ -31,7 +32,7 @@ export default function Publish() {
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={<>
{/* 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>
@@ -40,7 +41,7 @@ export default function Publish() {
</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title={pending.data.length ? `${pending.data.length} ${pending.data.length === 1 ? "change" : "changes"} not published` : "Nothing waiting to be published"}>
<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 && (
<ul className="mb-4 divide-y divide-gray-200">
{pending.data.map((c) => (
@@ -72,7 +73,7 @@ export default function Publish() {
</Panel>
{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>
<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 && (
@@ -91,7 +92,7 @@ export default function Publish() {
</Panel>
)}
<Panel title="History">
<Panel icon={History} title="History">
{versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : (
<ul className="divide-y divide-gray-200">
{versions.data.map((v, i) => (
@@ -8,8 +8,10 @@ import Link from "next/link";
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { AppWindow, Hourglass, ListOrdered, Search, Settings } from "lucide-react";
import { ImagePicker } from "@/admin/media";
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null; faviconId: string | null };
type PageRow = { id: string; kind: string; title: string; inNav: boolean };
export default function SettingsPage() {
@@ -30,10 +32,10 @@ export default function SettingsPage() {
}, "Saved as a draft: publish to change the menu.");
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>}
<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>
<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>
@@ -41,7 +43,19 @@ export default function SettingsPage() {
</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>
</Panel>
<Panel title="Coming soon">
<Panel icon={AppWindow} title="Site icon">
<p className="mb-3 text-sm text-gray-600">The little picture in the browser tab and bookmarks. Choose a square picture (512 × 512 pixels is best; a PNG can have a see-through background). Without one, your site uses your church&apos;s icon, or your church&apos;s initial on its colour. This goes live straight away.</p>
<div className="flex flex-wrap items-end gap-6">
<ImagePicker label="Icon" value={s.faviconId} onChange={(faviconId) => setForm({ ...form, faviconId })} />
{/* What the site shows now (the default when none is chosen). */}
<div className="text-sm text-gray-600">
<span className="block font-medium text-gray-800">In use now</span>
<img src={`/site-icon?saved=${encodeURIComponent(settings.data.faviconId ?? "none")}`} alt="" width={32} height={32} className="mt-1 h-8 w-8 rounded" />
</div>
</div>
{fields.faviconId && <p className="mt-2 text-sm text-red-700">{fields.faviconId}</p>}
</Panel>
<Panel icon={Hourglass} title="Coming soon">
<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 })} />
</Field>
@@ -49,7 +63,7 @@ export default function SettingsPage() {
{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>
)}
<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>
<ul className="divide-y divide-gray-200">
{menu.map((p, i) => (
@@ -5,8 +5,12 @@
* (recommended first), the homepage order, and the style settings. Fonts and corners are the
* church's brand style, shared with its other sites, so they're set in its church profile.
*/
import 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 { 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 Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
@@ -22,7 +26,7 @@ const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes
const VARIANT_NAMES: Record<string, string> = {
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
calendar: "Calendar strip", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
calendar: "Calendar strip", card: "Card", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
};
const ALL_VARIANTS: Record<string, string[]> = {
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
@@ -42,6 +46,7 @@ const STYLE = [
export default function TemplatePage() {
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
const { busy, message, run } = useAction();
const [tab, setTab] = useState<"template" | "home" | "style">("template");
if (!data) return <Loading error={error} />;
const { design, options } = data;
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
@@ -57,37 +62,48 @@ export default function TemplatePage() {
save({ home });
};
return (
<>
<Title sub="Changes here are drafts: preview them, then publish.">Template and style</Title>
<WithPreview path="/" version={JSON.stringify(design)}>
<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>}
<div className="space-y-6">
<Panel title="Template">
<Tabs label="Template and style" value={tab} onChange={setTab} tabs={[
{ 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">
{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")}>
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span>
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
{t.id !== design.template && (
<div className="mt-3 flex flex-wrap gap-2">
<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>
<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>
))}
{TEMPLATES.map((t) => {
const inUse = t.id === design.template;
return (
<div key={t.id} className={cx("rounded-xl border-2 p-4", inUse ? "border-brand bg-brand-tint" : "border-gray-200")}>
<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>
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
{!inUse && (
<div className="mt-3 flex flex-wrap gap-2">
<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>
</Panel>
)}
<Panel title="Home page: sections and layouts">
<p className="mb-4 text-sm text-gray-600">Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best.</p>
<ul className="divide-y divide-gray-200">
{tab === "home" && (
<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-100">
{design.home.map((e, i) => {
const recommended = options.variants[design.template]?.[e.section] ?? [];
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
return (
<li key={e.section} className="flex flex-wrap items-center gap-3 py-3">
<span className="w-40 font-medium">{SECTIONS[e.section]}</span>
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-56`} value={design.variants[e.section]} disabled={busy}
<li key={e.section} className={cx("flex flex-wrap items-center gap-3 py-3", e.hidden && "opacity-60")}>
<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>
<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 } })}>
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
</select>
@@ -96,33 +112,35 @@ export default function TemplatePage() {
Show
</label>
<span className="ml-auto flex gap-1">
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${SECTIONS[e.section]} up`}>↑</Btn>
<Btn onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`}>↓</Btn>
<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 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>
</li>
);
})}
</ul>
</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">
<Field label="Header">
<select className={inputClass} value={design.style.header} disabled={busy} onChange={(e) => save({ style: { header: e.target.value } })}>
{(options.headers[design.template] ?? []).map((h) => <option key={h} value={h}>{HEADER_NAMES[h] ?? h}</option>)}
</select>
</Field>
{STYLE.map((s) => (
<Field key={s.key} label={s.label}>
<select className={inputClass} value={design.style[s.key]} disabled={busy} onChange={(e) => save({ style: { [s.key]: e.target.value } })}>
{Object.entries(s.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
{STYLE.map((st) => (
<Field key={st.key} label={st.label}>
<select className={inputClass} value={design.style[st.key]} disabled={busy} onChange={(e) => save({ style: { [st.key]: e.target.value } })}>
{Object.entries(st.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</Field>
))}
</div>
<p className="mt-4 text-sm text-gray-600">Fonts and corners are your church&apos;s brand style, shared with your Events and sign-in pages: change them in your church profile.</p>
<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>
</div>
</>
)}
</WithPreview>
);
}
@@ -16,6 +16,11 @@ const PROBLEMS: Record<string, { title: string; text: string; retry: boolean }>
text: "Owners and Admins of this website sign in with a second step. Turn on two-step sign-in in your church account, then try again.",
retry: true,
},
ACCOUNTS_NOT_LINKED: {
title: "This website isn't linked to your church's sign-in yet",
text: "It links by itself shortly after it's installed. Please try again in a minute. If this keeps happening, contact Cross Code.",
retry: true,
},
ACCOUNTS_UNAVAILABLE: {
title: "Signing in isn't available right now",
text: "The website can't reach your church's sign-in at the moment. Please try again in a few minutes.",
+10 -1
View File
@@ -6,12 +6,21 @@ import { brandAttributes } from "@crosscode/ui";
import { loadContent } from "@/site/load";
import { PreviewBar } from "@/site/PreviewBar";
/** A short, stable version for the icon's address. */
const iconVersion = (s: string) => {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return (h >>> 0).toString(36);
};
export async function generateMetadata(): Promise<Metadata> {
const c = await loadContent();
const name = c.church?.name ?? "Church Website";
return {
title: { default: name, template: `%s · ${name}` },
icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined,
// 1.2.0: always an icon (app/site-icon): the site's own, the church's, or a default. The
// version changes with it, so browsers don't keep showing an old one.
icons: { icon: `/site-icon?v=${iconVersion(c.favicon ?? c.church?.branding.iconUrl ?? `${c.palette.brand}|${c.church?.shortName ?? c.church?.name ?? ""}`)}` },
// A preview is never indexed (§4).
...(c.mode === "published" && c.preview ? { robots: { index: false, follow: false } } : {}),
};
@@ -1,12 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/**
* A shared preview link (§4): keeps its token in a cookie for the rest of the visit, so every page
* shows the working copy. The backend checks the token (7 days, until revoked) on every page.
*/
export async function GET(request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
export async function GET(_request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
const res = NextResponse.redirect(new URL("/", request.url), 303);
const res = localRedirect("/");
if (/^[A-Za-z0-9_-]{20,100}$/.test(token)) {
res.cookies.set("ccw_preview", token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 7 * 86400 });
}
@@ -1,11 +1,12 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/** Leaves the preview: an admin goes back to editing, someone with a shared link to the live site. */
export function GET(request: NextRequest) {
const admin = request.cookies.get("ccw_preview")?.value === "admin";
const trying = !!request.cookies.get("ccw_preview_template")?.value;
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : trying ? "/admin/template" : "/admin") : "/";
const res = NextResponse.redirect(new URL(to, request.url), 303);
const res = localRedirect(to);
res.cookies.delete("ccw_preview");
res.cookies.delete("ccw_preview_template");
return res;
@@ -1,4 +1,5 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/**
* Preview (WEBSITE-1.0-PLAN §4): a signed-in admin sees the working copy on the site's own
@@ -6,7 +7,9 @@ import { NextResponse, type NextRequest } from "next/server";
* on every page (site/preview), so it shows nothing to anyone else.
*/
export function GET(request: NextRequest) {
const res = NextResponse.redirect(new URL("/", request.url), 303);
// ?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: "/" };
res.cookies.set("ccw_preview", "admin", opts);
// "Choose your template": the church's own content in another template, nothing saved.
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { loadContent } from "@/site/load";
import { localRedirect } from "@/lib/localRedirect";
/**
* 1.2.0: the site's icon (favicon). The one chosen under Settings, else the church's icon from its
* profile, else a default made for the church: its initial on its brand colour (a cross when the
* church isn't known yet). The layout links here with a version, so a new icon shows at once.
*/
export async function GET() {
const c = await loadContent();
if (c.favicon) return localRedirect(c.favicon);
const shared = c.church?.branding.iconUrl;
if (shared && /^https:\/\//.test(shared)) return new NextResponse(null, { status: 303, headers: { Location: shared } });
return new NextResponse(defaultIcon(c.palette.brand, c.palette.onBrand, c.church?.shortName || c.church?.name || null), {
headers: { "Content-Type": "image/svg+xml", "Cache-Control": "public, max-age=300" },
});
}
const rgb = (v: string, otherwise: string) => (/^\d{1,3} \d{1,3} \d{1,3}$/.test(v) ? `rgb(${v.replace(/ /g, ",")})` : otherwise);
function defaultIcon(brand: string, onBrand: string, name: string | null): string {
const bg = rgb(brand, "rgb(31,78,121)");
const fg = rgb(onBrand, "#fff");
const initial = name?.trim().match(/\p{L}|\p{N}/u)?.[0]?.toUpperCase();
const mark = initial
? `<text x="32" y="44" text-anchor="middle" font-family="Georgia, 'Times New Roman', serif" font-size="38" font-weight="700" fill="${fg}">${initial.replace(/[<>&"']/g, "")}</text>`
: `<path d="M28 12h8v12h12v8H36v20h-8V32H16v-8h12z" fill="${fg}"/>`;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${bg}"/>${mark}</svg>`;
}
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
/**
* 1.0.2: a 303 to a page of this site with a relative Location ("/admin"), so the browser stays on the
* address it's on. `new URL(path, request.url)` used the address the request reached Next.js on,
* which behind the proxy is the server's own (http://localhost:<web port>): Preview sent admins there.
*/
export function localRedirect(path: string): NextResponse {
if (!path.startsWith("/") || path.startsWith("//")) throw new Error(`Not a path on this site: ${path}`);
return new NextResponse(null, { status: 303, headers: { Location: path } });
}
@@ -4,7 +4,8 @@ import { useState } from "react";
/**
* A message's video or audio, loaded only when clicked (WEBSITE-1.0-PLAN §7): a thumbnail first,
* then youtube-nocookie or Spotify's player. Nothing loads from YouTube or Spotify until then.
* then youtube-nocookie or Spotify's player. Nothing loads from YouTube or Spotify until then: the
* thumbnail is served by the site (`/api/thumbnails/<id>.jpg`, backend site/thumbnails.ts).
*/
/** `priority`: the first thing on screen (the messages page's first message), so its thumbnail isn't lazy (it's the LCP image). */
export function MessagePlayer({ title, embedUrl, thumbnail, url, source, className, priority }: { title: string; embedUrl: string | null; thumbnail: string | null; url: string; source: "youtube" | "spotify"; className?: string; priority?: boolean }) {
+4 -4
View File
@@ -2,7 +2,7 @@
* A page other than home (WEBSITE-1.0-PLAN §6): its title, what its kind lists (ministries,
* leaders, events, messages, contact details), then its blocks.
*/
import { preconnect } from "react-dom";
import { preload } from "react-dom";
import { MessagePlayer } from "./MessagePlayer";
import { t } from "./load";
import { cx, DateBadge, dayName, fmtDate, Img, Paragraphs } from "./parts";
@@ -70,10 +70,10 @@ function Listing({ page, site }: { page: Page; site: Published }) {
</section>
);
case "messages": {
// The first thumbnail is the largest thing on screen (Lighthouse's LCP): connect to its host
// straight away rather than once the HTML has been read.
// The first thumbnail is the largest thing on screen (Lighthouse's LCP): ask for it from the
// <head>, rather than once the HTML has been read. Thumbnails come from the site itself.
const thumb = site.messages[0]?.thumbnail;
if (thumb?.startsWith("https://")) preconnect(new URL(thumb).origin);
if (thumb) preload(thumb, { as: "image", fetchPriority: "high" });
return (
<section className="cc-section">
<div className="cc-wrap grid gap-10 sm:grid-cols-2">
+17 -1
View File
@@ -13,8 +13,24 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// 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
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;
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 type { Image, Published, SiteContent, Template } from "./types";
@@ -20,8 +20,11 @@ const FALLBACK: 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.
// 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 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) {
try {
const session = jar.get("ccw_session")?.value;
+1 -1
View File
@@ -90,7 +90,7 @@ export function messagesLd(site: Published, messages: SiteMessage[]): string | n
const description = [m.speaker, m.passage, m.series].filter(Boolean).join(" · ") || m.title;
return m.source === "spotify"
? { "@type": "PodcastEpisode", name: m.title, datePublished: m.date.slice(0, 10), description, url: m.url }
: { "@type": "VideoObject", name: m.title, uploadDate: m.date, description, ...(m.thumbnail ? { thumbnailUrl: [m.thumbnail] } : {}), ...(m.embedUrl ? { embedUrl: m.embedUrl.replace("?autoplay=1", "") } : {}), contentUrl: m.url };
: { "@type": "VideoObject", name: m.title, uploadDate: m.date, description, ...(m.thumbnail ? { thumbnailUrl: [abs(site, m.thumbnail)] } : {}), ...(m.embedUrl ? { embedUrl: m.embedUrl.replace("?autoplay=1", "") } : {}), contentUrl: m.url };
}),
});
}
@@ -301,7 +301,8 @@ function Events(p: SectionProps) {
{list.map((e) => (
<li key={e.url + e.startsAt} className="cc-card w-64 shrink-0 snap-start p-5">
<p className="font-heading text-4xl font-bold cc-brand-text">{fmtDate(e.startsAt, zone, { day: "numeric" })}</p>
<p className="cc-eyebrow">{fmtDate(e.startsAt, zone, { month: "long", weekday: "short" })}</p>
{/* A weekday and month without a day is "Sun (month: November)" to Intl: two parts. */}
<p className="cc-eyebrow">{fmtDate(e.startsAt, zone, { weekday: "short" })} · {fmtDate(e.startsAt, zone, { month: "long" })}</p>
<h3 className="cc-h3 mt-3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h3>
{!e.allDay && <p className="cc-muted text-sm">{fmtTime(e.startsAt, zone)}</p>}
</li>
+5 -1
View File
@@ -72,7 +72,11 @@ export type SiteMessage = {
thumbnail: string | null;
};
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null } };
type Common = {
church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null };
/** 1.2.0: the site's own icon (Settings); absent from a backend before 1.2.0. */
favicon?: string | null;
};
export type ComingSoon = Common & { mode: "coming-soon"; template: Template; comingSoonText: string };
+14 -8
View File
@@ -34,7 +34,7 @@ every release).
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.7.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` released 2026-11-26** (not installed for a church yet); Hope Family Church next |
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26, not deployed yet. Left: deploy the site, Hope Family Church, a second church |
| 6–7 | App 1.0.0 → App 1.x | Not started |
## Released 2026-11-23
@@ -105,13 +105,19 @@ out").
and deployed 2026-11-25; the plan said 2.13.0) → ~~`website@1.0.0`~~ (released 2026-11-26, with
`contracts@1.18.0` and Hub `v2.22.0`, deployed 2026-11-26; the release checks are in
WEBSITE-1.0-PLAN §13, "Where they are"; the VM test was skipped, so watch the first install
closely) → **Hope Family Church**: roll out Accounts 1.7.0 and Events 3.7.0 first (neither is
rolled out yet), then New install → Website → a second church on a different template →
crosscode-site 1.7.0 (the Website on sale; prices in the site and the Hub together, below).
Loose ends from the checks: run `npx playwright test variants` once on the release build to finish
the screenshot baselines (36 of 104 taken), and the message thumbnails load from YouTube
(`i.ytimg.com`) with the page, though MessagePlayer's comment says nothing loads from YouTube
before a click.
closely) → ~~`website@1.0.1`~~ (released 2026-11-26: the messages' thumbnails served from the
site, the Calendar dates; VERSIONS.md) → **Hope Family Church**: roll out Accounts 1.7.0 and
Events 3.7.0 first (neither is rolled out yet), then New install → Website (1.0.1) → a second
church on a different template. ~~crosscode-site 1.7.0~~ (the Website on sale, released 2026-11-26;
the Hub already had its prices): **deploy it** (`deploy/deploy.sh` on the server) once Hope
Family Church's Website is live, so the first church to buy it isn't the first install.
The release checks are all run on 1.0.1's build (WEBSITE-1.0-PLAN §13, "Where they are"): every
variant passes axe, the 312 screenshots have baselines (taken again with whole-pixel section
heights), Lighthouse passes 12 of 12. Still to do:
- **Look through the variant baselines** once (the contact sheet: Bold, Community and Clean were
taken, not compared, the first time). A section drawn wrong there is the reference until then.
- **The VM test was skipped**: before Hope Family Church, a throwaway install from the Hub (New
install → Website 1.0.0, update it to 1.0.1, uninstall with its export) in its place.
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
+78 -10
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-25. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-27. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -10,13 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.0** | `events@3.7.0` | 2026-11-24 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.0.0** | `website@1.0.0` | 2026-11-26 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.0** | `accounts@1.7.0` | 2026-11-24 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.2.0** | `website@1.2.0` | 2026-11-27 |
| 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 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
| Cross Code Hub | `events-hub` | **2.22.0** | `v2.22.0` | 2026-11-25 |
| crosscode.co.za | `crosscode-site` | **1.6.1** | `v1.6.1` | 2026-11-23 |
| Cross Code Hub | `events-hub` | **2.24.1** | `v2.24.1` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.7.0** | `v1.7.0` | 2026-11-26 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
@@ -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/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) |
| Website | `apps/website` | 1.0.0 (released 2026-11-26; not installed for a church yet: Hope Family Church first, after Accounts 1.7.0 and Events 3.7.0 are rolled out) |
| Website | `apps/website` | 1.2.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0 on 2026-11-27; installed for the demo church cross-demo2 (1.2.0) only, Hope Family Church next) |
| 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
@@ -38,6 +38,64 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Hub 2.24.1 (2026-11-27):** Servers → Updates offers every product. Its tabs were a fixed list of
Cross Events and Accounts from before the Church Website, so Website installs couldn't be updated
in a batch there; now Events, Accounts, the Church Website, and the App once it has an install.
Frontend only, plus one error message. No migration. Checked: the backend tests (279), frontend
typecheck and lint. **Deployed 2026-11-27.**
- **Church Website 1.2.0 + Hub 2.24.0 (2026-11-27):** Website: a new install had no pages, so the
home page and its live preview showed only the header and footer (found on cross-demo2); the
backend now adds the fixed pages with starter text at startup (all of them to a site with none,
else a missing home page; never one a church removed), Terms and Safeguarding included. Settings →
Site icon (a favicon from the media library; else the church's icon, else its initial on its
colour). The Latest message's Card layout got its name. No migration. Hub: "Update everything to
latest" on a customer's Sites card plans every product that's behind in one batch (Accounts
first, one at a time, stopping at the first failure), scheduled or as an emergency, planned whole
or not at all; later products keep Accounts at the batch's new version. No migration. Checked:
the Website's backend tests (104), the admin e2e (11, with axe), typechecks and lint; the Hub's
backend tests (279), frontend typecheck and lint. **Hub 2.24.0 deployed 2026-11-27; Website
1.2.0 on cross-demo2 the same day** (its health check says 1.2.0, `/site-icon` serves the default).
- **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
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)
instead of refusing, so a new product links straight away. Before, the new Website's admin
couldn't sign in for up to 30 minutes ("can't reach your church's sign-in"). Accounts also sends a
heartbeat on every start. The Website links on the spot when someone opens `/admin`, its problem
page says "not linked yet" (`ACCOUNTS_NOT_LINKED`), and **Preview no longer redirects to the
server's own `http://localhost:<web port>`** (the preview routes built absolute URLs from
`request.url`; now relative). No migrations. Checked: the backend tests (Accounts 80, Website 100,
Events 801), typechecks, the Website's frontend lint and build, the preview redirects against
`next start`, and the Website's e2e suite (129 tests). **Deployed 2026-11-26 on cross-demo2 (the
demo church) only.** Open there: the Website's preview doesn't show the events synced from
Events, although Events' feed has 8 upcoming ones (not looked into yet).
- **Hub 2.23.1 (2026-11-26):** New install reads a church's Accounts version from its heartbeat,
not the install record. The record only changed with the Hub's own jobs for that product, so
cross-demo2's Accounts, updated alongside Events 3.7.0, still showed 1.6.0 there. New install →
Website was refused ("this church has 1.6.0") while the installs list showed 1.7.0. Each heartbeat
now also updates the record's version. No migration. **Deployed 2026-11-26.**
- **Hub 2.23.0 (2026-11-26):** release requirements carry forward. A release needs what every
earlier release of its product needed (the highest version per product; a later heading can raise
it, never lower or drop it), so `— requires accounts 1.7.0` is written once in WHATS-NEW.md, on
the release that first needs it. Found when New install → Website 1.0.1 sent a Website-only
`install` job, which agent 1.5.0 refused ("installs one product at a time: Events or Accounts"):
1.0.1's heading didn't repeat 1.0.0's requirement, so Accounts wasn't installed first. No
migration; the next release sync fixes the stored requirements. **Deployed 2026-11-26.**
- **Church Website 1.0.1 (2026-11-26):** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`, fetched once by the backend and kept in `uploads/.thumbnails/`), so a
visitor asks nothing of YouTube until pressing play (plan §7); the Calendar events' dates read
"Sun · November", not "Sun (month: November)". No migration. Checked: the backend tests (97),
the whole e2e suite on the release build (Lighthouse 12 of 12, performance 90–100: Heritage's
messages from 89 to 95), the 312 variant screenshots (taken again with whole-pixel section heights,
which ended a one-pixel flake), and an e2e check that the messages page makes no request to
YouTube or Spotify before a click. The `crosscode` script's Website export leaves out
`uploads/.thumbnails`. **Not installed for a church yet.**
- **Church Website 1.0.0 (2026-11-26):** the first release (WEBSITE-1.0-PLAN): four templates with
section variants and style settings, drafts, preview and one Publish, people and roles, messages
from YouTube, simple events and the event feed, church details through Accounts, SEO, Get more
@@ -63,13 +121,15 @@ need their own tags until something outside this repo depends on them.
church footer from its profile in Accounts (`GET /api/v2/church`, kept 10 minutes), with links to
its other sites in the header; `church.changed` from Accounts is now accepted (it answered 404
before). The dashboard and setup screens are unchanged. `@crosscode/ui` 0.3.0. No migrations.
Requires Accounts 1.7.0 (the Hub updates it first). **Not deployed yet.**
Requires Accounts 1.7.0 (the Hub updates it first). **On cross-demo2 only** (by 2026-11-26, now
3.7.1); not rolled out to the churches yet.
- **Contracts 1.17.0 + Accounts 1.7.0 (2026-11-24):** the first piece of the Church Website. Contracts:
the 8 font pairings, corner styles and template ids (`./style`), an optional `branding.style` on the
church profile, `church.update` (the Website changes shared profile facts), an optional `website`
part of the church export and an optional `limits.storageBytes` on the licence. Accounts: Brand
style under Church profile, the church's fonts, corners and shared footer on its pages, and
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **Not deployed yet.**
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **On cross-demo2
only** (by 2026-11-26, now 1.7.1); not rolled out to the churches yet.
- **Hub 2.20.0 (2026-11-23):** the port list says what each port is for (church, product, web or API,
linked to the install); a church server's hand-written frpc tunnels are listed as taken on each frp
config read. frps's allow_ports is checked against the port list (the Hub's range plus listed ports
@@ -111,6 +171,13 @@ need their own tags until something outside this repo depends on them.
release in a ⋯ menu); contact and billing details are one form; the history is one timeline with
a filter. Record payment is a popup on Billing too. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **crosscode.co.za 1.7.0 (2026-11-26):** the Church Website on sale (ROADMAP §9, phase 5): its own
page (`/products/church-website/`: features, the four templates with the same fictional demo church
in each, the section layouts, R99 a month, founding R64, extra storage R20 per 5 GB, the 15% bundle
with Cross Events, FAQ, `SoftwareApplication` JSON-LD with its offer) and a page per template; the
products and home pages, the contact form's topics, the Cross Events page and the brochure updated.
Screenshots from the Website's e2e demo (`npm run screenshots:website`). The Hub already had these
prices (2.21.0). **Not deployed yet** (`deploy/deploy.sh` on the server).
- **crosscode.co.za 1.6.1 (2026-11-23):** the web address choices on the Cross Events page are three
cards (name, price, "best if", an example address, short points); the option names were white on
a light background and couldn't be seen. Prices unchanged. Deployed 2026-11-23.
@@ -239,9 +306,10 @@ you deploy one.
| What | Running | Since | Notes |
|------|---------|-------|-------|
| Hub | 2.22.0 | 2026-11-26 | Get more storage for the Church Website (`POST /api/installs/storage-request`, the church emailed at 80% and full); vendors contracts 1.18.0. Before it, 2.21.0 (2026-11-25): the Website in New install, extra storage on the licence |
| Hub | 2.24.1 | 2026-11-27 | Servers → Updates offers every product (the Church Website too). Before it, 2.24.0 (2026-11-27): "Update everything to latest" on a customer's Sites card: every product that's behind, in one batch (Accounts first); before that, 2.23.1 (2026-11-26): a church's Accounts version comes from its heartbeat in New install, and heartbeats keep the install record's version current; 2.23.0 (2026-11-26): release requirements carry forward (`requires accounts …` written once in WHATS-NEW.md) |
| Agent on church-server1 | 1.5.0 | 2026-11-23 | Uninstalls one product of a church at a time |
| Agent on the central server | 1.5.0 | 2026-11-23 | Reads and changes frps's config from the Hub (no longer read-only; decision 35 superseded) |
| Cross Events (churches) | 3.6.1 | 2026-11-20 | Every install adopted onto the monorepo and signing in through Accounts |
| Accounts (churches) | 1.6.0 | 2026-11-20 | |
| cross-demo2 (demo church) | Accounts 1.7.1, Cross Events 3.7.1, Church Website 1.2.0 | 2026-11-27 | The first Church Website install (`demo2.crosscode.co.za`, added next to the church's Accounts) |
| crosscode.co.za | 1.6.1 | 2026-11-23 | Clearer web address choices on the Cross Events page |
+19
View File
@@ -535,6 +535,25 @@ baselines kept on the machine that runs them, not in git), `lighthouse.spec.ts`
of three runs with the CPU slowdown calibrated to the machine). `E2E_DATABASE_URL=…_e2e` runs the
whole suite on real Postgres.
**Run again on the release build (2026-11-26):** `npx playwright test variants lighthouse`, 19.6 minutes.
Every variant in every template passes axe. The screenshot baselines are complete: the 37 that existed
(Heritage, and Bold up to Ministries) matched, and the other 67 variants' 201 screenshots were taken
(they still need a look through). Lighthouse (mobile): SEO and accessibility 100 on every page;
performance 92–99 except Heritage's messages, 89 (LCP 3.0 s: the first message's YouTube thumbnail,
from `i.ytimg.com`). Community's home, 84 in the run before, was 97: the machine's benchmark moved
between 1169 and 2542 in one run, so a score within a few points of 90 is worth a second run before
it counts as a regression. Found in the screenshots: the Calendar events variant prints the date as
"Sun (month: November)" (for `website@1.0.1`).
**On 1.0.1 (2026-11-26):** the whole suite, `npx playwright test` (129 tests, 34.6 minutes): the admin
flows, every template's pages, Lighthouse 12 of 12 (performance 90–100; Heritage's messages 95, the
thumbnail now from the site), and a new check that the messages page asks nothing of YouTube or
Spotify before play. Seven variant screenshots failed by a pixel of height in that run and passed
when run again: a section starting at a fractional position came out 534 or 535 pixels tall.
`variants.spec.ts` now rounds the header's and each section's height up before the screenshot
(`wholePixels`), and the 312 baselines were taken again with it (113 came out the same), then
compared in a second full run of the variants.
## 14. Releasing and rolling it out
1. `contracts@1.17.0`, then `accounts@1.7.0` (the profile's brand style), then `events@3.7.0`.
+9 -8
View File
@@ -51,7 +51,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.7.0",
"version": "1.8.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -88,7 +88,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.7.0",
"version": "1.8.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -114,7 +114,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.6.0",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*",
@@ -133,7 +133,7 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "3.7.0",
"version": "3.7.1",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
@@ -183,7 +183,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.7.0",
"version": "3.7.1",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -360,7 +360,7 @@
},
"apps/website/backend": {
"name": "@crosscode/website-backend",
"version": "1.0.0",
"version": "1.3.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/auth-client": "*",
@@ -387,11 +387,12 @@
},
"apps/website/frontend": {
"name": "@crosscode/website-frontend",
"version": "1.0.0",
"version": "1.3.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6",
"react": "^19.3.1",
"react-dom": "^19.3.1"
@@ -23182,7 +23183,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.18.0",
"version": "1.19.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.18.0",
"version": "1.19.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED",
"type": "commonjs",
+28 -4
View File
@@ -819,13 +819,37 @@
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"profile": {
"product": {
"type": "string",
"enum": [
"small",
"events",
"ministry",
"multicampus"
"website"
]
},
"profile": {
"anyOf": [
{
"type": "string",
"enum": [
"small",
"events",
"ministry",
"multicampus"
]
},
{
"type": "string",
"enum": [
"heritage-parish",
"heritage-city",
"bold-youth",
"bold-plant",
"community-family",
"community-town",
"clean-modern",
"clean-campus"
]
}
]
},
"adminEmail": {
+39 -4
View File
@@ -59,9 +59,33 @@ export const DEMO_PROFILES = ["small", "events", "ministry", "multicampus"] as c
export const demoProfileSchema = z.enum(DEMO_PROFILES);
export type DemoProfile = z.infer<typeof demoProfileSchema>;
/**
* The Church Website's demo data sets (1.19.0, `apps/website/backend/src/demo/seeds.ts`): two per
* template, each its own kind of church, the second on the template's other recommended variants.
*/
export const WEBSITE_DEMO_PROFILES = [
"heritage-parish", "heritage-city",
"bold-youth", "bold-plant",
"community-family", "community-town",
"clean-modern", "clean-campus",
] as const;
export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES);
export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>;
/** The products with demo data (`seed-demo` jobs). */
export const DEMO_PRODUCTS = ["events", "website"] as const;
export const demoProductSchema = z.enum(DEMO_PRODUCTS);
export type DemoProduct = z.infer<typeof demoProductSchema>;
/** Each demo product's profiles. */
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = { events: DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES };
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
export const SEED_DEMO_MIN_AGENT = "1.2.0";
/** The first agent that runs `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */
export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0";
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
export const ENV_JOBS_MIN_AGENT = "1.3.0";
@@ -135,11 +159,22 @@ export const jobArgsSchemas = {
/** `crosscode restart <church> [product] --json` (PM2 reload) */
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
/**
* `crosscode demo <church> --profile <profile> [--admin-email <email>] --json`: replaces Cross
* Events' data with a demo set (a backup is taken first). The Hub only makes it for installs
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
* `crosscode demo <church> [website] --profile <profile> [--admin-email <email>] --json`: replaces
* Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo
* set (a backup is taken first). The Hub only makes it for installs marked as demo sites.
* `adminEmail` (Events only): the account kept (default: the release's own choice). No `product`
* is Events, so older Hubs' jobs mean what they did.
*/
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
"seed-demo": z.strictObject({
church: shortNameSchema,
product: demoProductSchema.optional(),
profile: z.union([demoProfileSchema, websiteDemoProfileSchema]),
adminEmail: z.email().max(254).optional(),
}).superRefine((a, ctx) => {
const product = a.product ?? "events";
if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` });
if (product === "website" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: "the Website's demo keeps every admin" });
}),
/**
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
* whether they're set). The report's `result` is an {@link envReadResultSchema}.
+9
View File
@@ -165,6 +165,15 @@ describe("seed-demo jobs", () => {
expect(agent.JOB_TYPES).toContain("seed-demo");
expect(agent.CENTRAL_JOB_TYPES).not.toContain("seed-demo");
});
it("1.19.0: a Website demo names the product and takes only a Website profile", () => {
expect(args({ church: "hope", product: "website", profile: "bold-plant" })).toBe(true);
expect(args({ church: "hope", product: "events", profile: "small" })).toBe(true);
expect(args({ church: "hope", product: "website", profile: "small" })).toBe(false);
expect(args({ church: "hope", profile: "bold-plant" })).toBe(false);
expect(args({ church: "hope", product: "website", profile: "clean-campus", adminEmail: "jane@hope.test" })).toBe(false);
expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false);
expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8);
});
});
describe("env-read and env-set jobs (1.12.0)", () => {
+1 -1
View File
@@ -96,7 +96,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
crosscode adopt <church> --undo go back to the old folder (within 14 days)
crosscode restart <church> [events] reload the PM2 processes
crosscode demo <church> --profile <profile> replace Events' data with a demo set
crosscode demo <church> [website] --profile <p> replace Events' (or the Website's) data with a demo
crosscode env <church> <product> [--set NAME=value] show or change a product's .env values
crosscode export <church> [product …] --out <zip> the church's data and uploads
crosscode uninstall <church> [product …] --confirm <church>
+46 -1
View File
@@ -10,6 +10,12 @@ crosscode demo <church> --profile <profile> [--admin-email <email>]
replace Cross Events' data with a demo set
(small, events, ministry, multicampus); a backup
is taken first, one admin account is kept
crosscode demo <church> website --profile <profile>
replace the Website's content with a demo church
(heritage-parish, heritage-city, bold-youth,
bold-plant, community-family, community-town,
clean-modern, clean-campus); a backup is taken
first; the church's profile, settings and admins stay
crosscode env <church> <product> the product's .env values (secrets hidden)
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
change values (a copy is kept; never secrets or
@@ -83,22 +89,32 @@ cmd_restart() {
}
DEMO_PROFILES="small events ministry multicampus"
# The Website's (contracts WEBSITE_DEMO_PROFILES): two per template.
WEBSITE_DEMO_PROFILES="heritage-parish heritage-city bold-youth bold-plant community-family community-town clean-modern clean-campus"
# Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's
# user (its .env is readable only by that user). The Hub sends it only for installs marked as demo
# sites. Afterwards Events is reloaded: the demo switches campuses on or off.
# `crosscode demo <church> website --profile <p>`: the Website's content instead (cmd_demo_website).
cmd_demo() {
local church="" profile="" email="" dir user app
local church="" product="events" profile="" email="" dir user app
while [ $# -gt 0 ]; do
case "$1" in
--profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;;
--admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help demo)." ;;
events|website) [ -n "$church" ] || die "Name the church first (crosscode demo hope website …)."; product="$1"; shift ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
if [ "$product" = website ]; then
[[ " $WEBSITE_DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $WEBSITE_DEMO_PROFILES."
[ -z "$email" ] || die "--admin-email: the Website's demo keeps every admin."
cmd_demo_website "$church" "$profile"
return
fi
[[ " $DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $DEMO_PROFILES."
[ -z "$email" ] || [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "--admin-email: not an email address."
require_root
@@ -128,6 +144,35 @@ cmd_demo() {
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
}
# The Website's demo (Website 1.3.0+, backend/src/demo/seeds.ts): its content replaced with one of
# the eight demo churches, keeping the church's profile, the site settings and the admins. Backup
# first; then reloaded, so nothing cached from before is shown.
cmd_demo_website() {
local church="$1" profile="$2" dir user app
require_root
load_church "$church"
church_has_product website || die "$church has no Church Website."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/website.sh"
dir="$(pvar website DIR)"
user="$(pvar website USER)"
app="$(website_app "$dir")"
[ -f "$app/backend/src/demo/seeds.ts" ] || die "This release of the Website ($(checkout_ref "$dir" website)) has no demo profiles (1.3.0 or later has)."
step "Website: backup first"
website_backup "$dir" "$user" || die "The backup failed, so the demo wasn't loaded."
step "Website: demo ($profile)"
run_as "$user" "$app/backend" npm run --silent demo -- --profile "$profile" --force ||
die "The demo wasn't loaded (see above). If it got as far as changing anything, the backup from just now has the content from before."
step "Website: reloading PM2"
website_reload "$dir" "$user"
step "Website: waiting for it to answer"
wait_for_version "$(website_health_url)" "$(website_expected_version "$dir")" 60 ||
die "The Website didn't answer after the reload (sudo -u $user pm2 logs)."
}
# crosscode env <church> <product>: the product's .env values, secrets hidden (the Hub's env-read).
# With --set / --unset (the Hub's env-set): changes one file (--file, default backend/.env), keeping
# a copy first; when the frontend's file changed, the frontend is rebuilt (Next.js builds its values
+2 -1
View File
@@ -98,7 +98,8 @@ website_copy_uploads() {
local uploads
uploads="$(website_app "$1")/backend/uploads"
mkdir -p "$2"
[ ! -d "$uploads" ] || rsync -a "$uploads/" "$2/"
# .thumbnails is the messages' YouTube thumbnails kept by the site (fetched again), not the church's.
[ ! -d "$uploads" ] || rsync -a --exclude .thumbnails "$uploads/" "$2/"
}
# What uninstall keeps for 30 days: the backups and the .env (its WEBSITE_SECRET decrypts what's stored).

Some files were not shown because too many files have changed in this diff Show More