Compare commits

..
Author SHA1 Message Date
joshuaandClaude Opus 5.5 5ed7201efa feat(website): the four templates and the public site
Heritage, Bold, Community and Clean drawing all 26 section variants
with their headers, homepage order and style settings; colours made
safe (WCAG AA) by the backend; fonts and corners from the shared brand
style. Publishing into numbered versions, the content API with live
messages and events and the church profile from Accounts, uploads,
every page kind, simple event pages, Coming soon, 404, sitemap, SEO
basics and the church's JSON-LD. The demo church (npm run demo) and
Playwright e2e: every template's pages pass axe and the SEO checks.
website.sh builds packages/seo. Decision 17 (first Owner) recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:59:03 +02:00
joshua 138c73e20c Merge branch 'feat/website-signin' 2026-11-25 09:27:08 +02:00
45 changed files with 2704 additions and 63 deletions
+19
View File
@@ -17,6 +17,25 @@
roles; the **first Owner** is whoever signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`,
verified in Accounts) while the site has none. Owners and Admins sign in with a second step
(`two_factor_required_for_admins`, on by default); asked of Accounts once, then explained.
- **The four templates and the public site** (§3, §5, §6): Heritage, Bold, Community and Clean,
each drawing all 26 section variants its own way, with its headers, homepage order and style
settings (section colour, spacing, buttons, image treatment). The church's colours are made safe
by the backend (`site/palette.ts`: tints, shades and text colours checked against WCAG AA, with a
note for the admin when one is changed); fonts and corners come from its shared brand style, else
the template's suggestion. Pages: home, every page kind (visit, about, ministries, leadership,
events, messages, give, contact, custom) with its blocks, simple event pages, a real 404,
Coming soon from the church profile, `sitemap.xml` and `robots.txt`. Every page has a title,
description, canonical, Open Graph and one `<h1>`; home and contact have the church's JSON-LD.
Messages load YouTube (youtube-nocookie) or Spotify only when clicked; maps are OpenStreetMap.
- **Publishing** (`site/snapshot.ts`): Publish copies the working copy into a numbered version;
visitors see the latest (`GET /api/v1/site/content`, with live messages and events and the church
profile from Accounts, kept 10 minutes). Section data is checked per type (`site/sections.ts`); a
section that doesn't fit is left out, never shown broken. Uploads are served from
`/api/uploads/` (SVGs sandboxed).
- **The demo church** (`npm run demo -- --template <id>`): Acacia Hill Church, fictional, with
illustrated images; refuses to replace a site its admins published unless `--force`.
- **End to end** (`npx playwright test` in apps/website, no database): every template's pages pass
axe (WCAG 2.2 AA) and the SEO basics; screenshots at phone and desktop in `e2e/screens/`.
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
- **The church's export** (`scripts/export-church.ts`): `export.json` in
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
+2 -1
View File
@@ -7,7 +7,8 @@ The church picks one of four templates (Heritage, Bold, Community, Clean) and ma
section variants and style settings. Changes are drafts until an editor previews the whole site and
presses Publish; until the first publish visitors see Coming soon.
**State:** being built (2026-11-25): the skeleton and signing in through Accounts. Not released;
**State:** being built (2026-11-25): signing in through Accounts, the four templates and the public
site, publishing, and the demo church. The admin's editing screens are next. Not released;
`website@1.0.0` is tagged when the plan is built.
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
+2 -1
View File
@@ -14,7 +14,8 @@
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status"
"prisma:status": "prisma migrate status",
"demo": "tsx scripts/demo.ts"
},
"dependencies": {
"@crosscode/auth-client": "*",
+36
View File
@@ -0,0 +1,36 @@
/**
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
*
* npm run demo -- --template heritage|bold|community|clean [--force]
*
* It replaces the site's content, so a site that has been published needs --force.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { 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 { 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]');
process.exit(2);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const ctx = createCtx(loadConfig(), db);
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
if (published && !process.argv.includes('--force')) {
console.error('This site has been published by its admins: loading the demo would replace their content. Add --force to do it anyway.');
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}).`);
await db.$disconnect();
+23 -2
View File
@@ -4,13 +4,15 @@
*
* /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/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
* /api/v1/admin/… the admin (signed in, by role)
*
* To come (§1): the admin's content, publish and preview links, /api/uploads/…, the event feed.
* To come (§1): the admin's content, publish and preview links, uploading, the event feed.
*/
import path from 'node:path';
import express from 'express';
import type { Ctx } from './context.js';
import { authRouter } from './auth/routes.js';
@@ -19,6 +21,8 @@ import { dbUp } from './hub/client.js';
import { ApiError, handle, sendError } from './http.js';
import { appVersion } from './lib/version.js';
import { linksRouter } from './links/routes.js';
import { defaultUploadDir } from './demo/demoChurch.js';
import { siteContent } from './site/content.js';
import { siteStatus } from './site/status.js';
export function createApp(ctx: Ctx) {
@@ -41,8 +45,22 @@ export function createApp(ctx: Ctx) {
const site = express.Router();
site.get('/status', handle(() => siteStatus(ctx)));
site.get('/content', handle(async (_req, res) => {
// Short: Publish shows within a minute even where a proxy caches.
res.set('Cache-Control', 'public, max-age=30');
return siteContent(ctx);
}));
app.use('/api/v1/site', site);
// Uploaded files: never a directory listing, never outside the folder (express.static checks).
app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), {
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d',
setHeaders: (res) => {
// An uploaded SVG is shown as an image, never run as a page.
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
},
}));
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
@@ -58,8 +76,11 @@ export function createApp(ctx: Ctx) {
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
if (res.headersSent) return next(err);
const e = err as { type?: string };
if (err instanceof ApiError) return sendError(res, err);
const e = err as { type?: string; status?: number };
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
// A missing upload (express.static), or another known client error.
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
return sendError(res, err);
});
return app;
@@ -0,0 +1,71 @@
/**
* The church profile (`crosscode.church/1`) from the church's Accounts (WEBSITE-1.0-PLAN §2): name,
* logo, colours, brand style, service times, contact, social, the church's other sites. Accounts
* owns it; the Website shows it and never stores it (§2: shared facts aren't drafts). As Events
* 3.7's accounts/church.ts: kept in memory for 10 minutes, the last copy kept while Accounts can't
* be reached (tried again after a minute).
*
* Before the Website is linked to Accounts (and in local development) the profile saved in
* AppSetting `church_profile_local` is used, if any (`npm run demo` saves the demo church's).
*/
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { accountsLink } from '../auth/accounts.js';
const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000;
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
async function fetchProfile(accountsUrl: string): Promise<Church> {
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
const parsed = churchSchema.safeParse(await res.json());
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
return parsed.data;
}
async function localProfile(ctx: Ctx): Promise<Church | null> {
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
const parsed = raw ? churchSchema.safeParse(raw) : null;
return parsed?.success ? parsed.data : null;
}
/** The church's profile, or null when there's none yet. Never throws. */
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
let link;
try {
link = await accountsLink(ctx);
} catch {
link = null;
}
if (!link) return localProfile(ctx).catch(() => null);
let state = caches.get(ctx);
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
const { cached } = state;
const url = link.url;
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
if (!state.pending) {
const last = cached?.url === url ? cached.church : null;
const s = state;
s.pending = fetchProfile(url)
.then((church) => {
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
return church;
}, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message);
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
return last;
})
.finally(() => { s.pending = null; });
}
return state.pending;
}
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
export function churchChanged(ctx: Ctx): void {
const state = caches.get(ctx);
if (state?.cached) state.cached = { ...state.cached, at: 0 };
}
+186
View File
@@ -0,0 +1,186 @@
/**
* The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and
* 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`.
*
* 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 type { Ctx } from '../context.js';
import type { SectionData } from '../site/sections.js';
import { publish } from '../site/snapshot.js';
import { defaultDesign } from '../site/variants.js';
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
export function demoProfile(publicUrl: string): Church {
return {
schema: CHURCH_SCHEMA,
customerId: '00000000-0000-4000-8000-000000000001',
updatedAt: '2026-11-25T08:00:00.000Z',
name: 'Acacia Hill Church',
shortName: 'Acacia Hill',
timezone: 'Africa/Johannesburg',
locale: 'en-ZA',
branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } },
campuses: [],
serviceTimes: [
{ day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null },
{ day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' },
{ day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null },
],
contact: {
email: 'hello@acaciahill.example',
phone: '+27125550123',
whatsapp: '+27825550123',
address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } },
},
social: [
{ network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' },
{ network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' },
],
links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' },
} as 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'];
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}">
<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c(3)}"/><stop offset="1" stop-color="#fffaf0"/></linearGradient></defs>
<rect width="${w}" height="${h}" fill="url(#sky)"/>
<circle cx="${Math.round(w * (0.2 + (seed % 5) * 0.15))}" cy="${y(0.3)}" r="${Math.round(h * 0.12)}" fill="${c(1)}" opacity="0.85"/>
<path d="M0 ${y(0.62)} Q ${w * 0.25} ${y(0.45)} ${w * 0.5} ${y(0.6)} T ${w} ${y(0.55)} V ${h} H 0 Z" fill="${c(2)}"/>
<path d="M0 ${y(0.75)} Q ${w * 0.35} ${y(0.6)} ${w * 0.7} ${y(0.74)} T ${w} ${y(0.7)} V ${h} H 0 Z" fill="${c(0)}"/>
<path d="M${w * 0.45} ${h} C ${w * 0.5} ${y(0.85)} ${w * 0.6} ${y(0.8)} ${w * 0.62} ${y(0.72)}" stroke="${c(3)}" stroke-width="${Math.round(h * 0.03)}" fill="none" stroke-linecap="round"/>
</svg>`;
}
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 ids: Ids = {};
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
for (const [key, alt, seed] of items) {
const filename = `demo/${key}.svg`;
const svg = illustration(seed);
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 } });
ids[key] = row.id;
}
return 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 } = {}) {
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) {
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)));
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.' },
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! },
},
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: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
};
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: '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: '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: '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: '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: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', 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 } });
let i = 0;
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!],
];
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],
];
n = 0;
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, 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 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) {
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 } });
}
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
}
+150
View File
@@ -0,0 +1,150 @@
/**
* Everything the public site needs to draw a page (WEBSITE-1.0-PLAN §1): the latest published
* snapshot, the church profile from Accounts, the colours made safe, the fonts and corners, and
* the messages and events (which publish on their own, so they're read live). Before the first
* publish: Coming soon, from the profile alone (§5).
*/
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
title: string;
summary: string | null;
startsAt: string;
endsAt: string | null;
allDay: boolean;
location: string | null;
image: Image | null;
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
url: string;
from: 'website' | 'events' | 'app';
registration: { status: string; priceFromCents: number | null } | null;
};
export type SiteMessage = {
slug: string;
title: string;
date: string;
speaker: string | null;
series: string | null;
passage: string | null;
source: 'youtube' | 'spotify';
/** For the embed (youtube-nocookie) or the Spotify player, loaded only when clicked. */
embedUrl: string | null;
url: string;
thumbnail: string | null;
};
type Common = {
church: Church | null;
palette: Palette;
/** The shared brand style, else what the template suggests (§3). */
style: { fontPairing: string; corners: string };
};
export type SiteContent =
| (Common & { mode: 'coming-soon'; template: WebsiteTemplate; comingSoonText: string })
| (Common & {
mode: 'published';
version: number;
snapshot: Snapshot;
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
transparentHeader: Record<string, boolean>;
messages: SiteMessage[];
events: SiteEvent[];
});
const DEFAULT_COLOUR = '#1f4e79';
function brandFor(church: Church | null, template: WebsiteTemplate) {
return {
palette: buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null),
style: {
fontPairing: church?.branding.style?.fontPairing ?? TEMPLATE_FONT_PAIRINGS[template][0],
corners: church?.branding.style?.corners ?? TEMPLATE_STYLE[template].suggestedCorners,
},
};
}
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
export function youtubeId(url: string): string | null {
try {
const u = new URL(url);
if (u.hostname === 'youtu.be') return u.pathname.slice(1) || null;
if (/(^|\.)youtube(-nocookie)?\.com$/.test(u.hostname)) return u.searchParams.get('v') ?? (/^\/(embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[2] ?? null);
} catch {
// Not a URL.
}
return null;
}
/** `https://open.spotify.com/episode/abc` → the embed address; null for anything else. */
export function spotifyEmbed(url: string): string | null {
const m = /^https:\/\/open\.spotify\.com\/(episode|show)\/([A-Za-z0-9]+)/.exec(url);
return m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : null;
}
async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
const rows = await ctx.db.message.findMany({ where: { hidden: false, publishedAt: { not: null } }, orderBy: { date: 'desc' }, take: 24, include: { series: true } });
return rows.map((m) => {
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
return {
slug: m.slug, title: m.title, date: m.date.toISOString(), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage,
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),
};
});
}
async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
const now = ctx.now();
const [simple, imported, media] = await Promise.all([
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, cancelled: false, OR: [{ startsAt: { gte: now } }, { endsAt: { gte: now } }] }, orderBy: { startsAt: 'asc' }, take: 50 }),
ctx.db.importedEvent.findMany({ where: { startsAt: { gte: new Date(now.getTime() - 7 * 864e5) } }, orderBy: { startsAt: 'asc' }, take: 50 }),
ctx.db.mediaAsset.findMany(),
]);
const image = (id: string | null) => {
const m = id ? media.find((x) => x.id === id) : null;
return m ? { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } : null;
};
const own: SiteEvent[] = simple.map((e) => ({
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null,
}));
const copies: SiteEvent[] = imported.flatMap((row) => {
const e = row.data as unknown as CrosscodeEvent;
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
return [{
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, from: e.origin.product,
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
} satisfies SiteEvent];
});
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
}
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
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),
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
const { snapshot } = published;
const template = snapshot.design.template;
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
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), messages, events };
}
+95
View File
@@ -0,0 +1,95 @@
/**
* The site's colours from the church's two (WEBSITE-1.0-PLAN §3, "Colours from the church, made
* safe"): tints and shades, the text colour on each, all checked against WCAG AA (4.5:1 for text).
* A colour that fails is darkened (or lightened) until it passes, and the admin is told why.
*/
export type Rgb = [number, number, number];
const AA = 4.5;
const WHITE: Rgb = [255, 255, 255];
const INK: Rgb = [17, 24, 39];
export function hexToRgb(hex: string): Rgb {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
const n = parseInt(m ? m[1]! : '1f4e79', 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
function luminance([r, g, b]: Rgb): number {
const lin = (v: number) => {
const s = v / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}
export function contrast(a: Rgb, b: Rgb): number {
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
return (x + 0.05) / (y + 0.05);
}
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
for (let t = 0; t <= 1; t += 0.02) {
const d = mix(c, [0, 0, 0], t);
if (contrast(d, against) >= ratio) return d;
}
return [0, 0, 0];
}
export type Palette = {
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
brand: string;
brandDark: string;
onBrand: string;
/** The church's colour as text or a link on white: darkened when it's too light to read. */
brandText: string;
/** A soft background in the church's colour (Section colour "Tinted"). */
brandTint: string;
accent: string;
onAccent: string;
/** What was changed and why, for the admin (§3: "the admin is told why"). */
notes: string[];
};
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
const notes: string[] = [];
const primary = hexToRgb(primaryHex);
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
// background is darkened until white does.
let brand = primary;
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
if (!onBrand) {
brand = darkenUntil(primary, WHITE);
onBrand = WHITE;
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
}
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
return {
brand: triple(brand),
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
onBrand: triple(onBrand),
brandText: triple(brandTextRgb),
brandTint: triple(mix(primary, WHITE, 0.92)),
accent: triple(accent),
onAccent: triple(onAccent),
notes,
};
}
+68
View File
@@ -0,0 +1,68 @@
/**
* What an admin fills in for each homepage section (WEBSITE-1.0-PLAN §2: "every section stores its
* data, validated with a zod schema per section type"). Never tied to a template: every template
* draws every variant from the same data (§3). Lists (ministries, leaders, events, messages) come
* from their own tables; the section only holds its heading and intro.
*
* Images are media ids here; the published snapshot turns them into `{ url, alt }`.
*/
import { z } from 'zod';
import type { SectionType } from './variants.js';
const text = (max: number) => z.string().trim().max(max);
const optional = (max: number) => text(max).nullable().default(null);
const mediaId = z.string().uuid();
/** A link on the site (`/visit`) or elsewhere (https only). */
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
export const SECTION_SCHEMAS = {
hero: z.object({
headline: text(120).min(1),
subline: optional(300),
/** `photo` and `split` use the first; `collage` up to three. */
images: z.array(mediaId).max(3).default([]),
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
videoId: mediaId.nullable().default(null),
button,
}),
serviceTimes: z.object({
heading: optional(80),
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
note: optional(300),
}),
welcome: z.object({
heading: optional(120),
/** The mission line, above the introduction in every variant (§3). */
mission: optional(200),
body: text(4000).default(''),
imageId: mediaId.nullable().default(null),
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
}),
ministries: z.object({ heading: optional(80), intro: optional(400) }),
team: z.object({ heading: optional(80), intro: optional(400) }),
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
latestMessage: z.object({ heading: optional(80) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
} as const satisfies Record<SectionType, z.ZodType>;
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
export const BLOCK_SCHEMAS = {
text: z.object({ heading: optional(120), body: text(20000) }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
} as const;
export type BlockType = keyof typeof BLOCK_SCHEMAS;
export const isBlockType = (t: string): t is BlockType => t in BLOCK_SCHEMAS;
/** A section's or block's data, checked; null when it doesn't fit (it's then left out, never shown broken). */
export function parseSectionData(type: string, data: unknown): Record<string, unknown> | null {
const schema = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
if (!schema) return null;
const r = schema.safeParse(data ?? {});
return r.success ? (r.data as Record<string, unknown>) : null;
}
+142
View File
@@ -0,0 +1,142 @@
/**
* Published versions (WEBSITE-1.0-PLAN §4): Publish copies the working copy into an immutable
* snapshot (`SiteVersion.snapshot`), and visitors always see the latest. The snapshot holds the
* site's design and every page with its sections, ministries and leaders, with images already
* turned into `{ url, alt }`, so showing the site never reads the working copy.
*
* Messages and simple events aren't in it: they publish on their own (decision 9) and are read
* live (content.ts).
*/
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1;
export type Image = { url: string; alt: string; width: number | null; height: number | null };
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
export type SnapshotPage = {
kind: string;
slug: string;
/** `/` for home, else `/<slug>`. */
path: string;
title: string;
seoTitle: string | null;
description: string | null;
navLabel: string;
inNav: boolean;
image: Image | null;
sections: SnapshotSection[];
};
export type Snapshot = {
v: typeof SNAPSHOT_VERSION;
design: SiteDesign;
pages: SnapshotPage[];
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
/** Every image the sections refer to, by media id. */
media: Record<string, Image>;
};
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
/** The design as saved, made safe: an unknown template, variant or section falls back to the default. */
export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign {
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
const base = defaultDesign(template);
if (!saved) return base;
const variants = { ...base.variants } as Record<SectionType, string>;
const v = (saved.variants ?? {}) as Record<string, unknown>;
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
const home = Array.isArray(saved.home)
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
: base.home;
// Every section listed once: any missing one is added at the end, hidden.
for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
const style = { ...base.style, ...Object.fromEntries(Object.entries((saved.style ?? {}) as Record<string, unknown>).filter(([, x]) => typeof x === 'string')) };
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
}
/** The working copy as a snapshot. */
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
const db = ctx.db;
const [design, pages, ministries, leaders, media] = await Promise.all([
db.siteDesign.findUnique({ where: { id: 1 } }),
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
db.mediaAsset.findMany(),
]);
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
const used: Record<string, Image> = {};
const collect = (data: unknown) => {
// Every media id anywhere in a section's data (images, videoId, imageId, photoId).
const walk = (x: unknown) => {
if (typeof x === 'string' && images.has(x)) used[x] = images.get(x)!;
else if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
};
walk(data);
};
const d = cleanDesign(design);
const snapshotPages: SnapshotPage[] = pages.map((p) => {
const sections: SnapshotSection[] = [];
if (p.kind === 'home') {
// The homepage: the design's order and variants, each section's data from the page.
const byType = new Map(p.sections.map((s) => [s.type, s]));
for (const entry of d.home) {
if (entry.hidden) continue;
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
if (!data) continue;
collect(data);
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
}
} else {
for (const s of p.sections) {
if (s.hidden) continue;
const data = parseSectionData(s.type, s.data);
if (!data) continue;
collect(data);
sections.push({ type: s.type, variant: s.variant, data });
}
}
return {
kind: p.kind, slug: p.slug, path: p.kind === 'home' ? '/' : `/${p.slug}`, title: p.title, seoTitle: p.seoTitle, description: p.description,
navLabel: p.navLabel || p.title, inNav: p.inNav && p.kind !== 'home', image: image(p.imageId), sections,
};
});
return {
v: SNAPSHOT_VERSION,
design: d,
pages: snapshotPages,
ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
media: used,
};
}
/** Publish (§4): the whole working copy becomes the next version, at once. */
export async function publish(ctx: Ctx, by: { id: string; role: string }, note: string | null = null) {
const snapshot = await buildSnapshot(ctx);
const last = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true } });
const version = await ctx.db.siteVersion.create({
data: { number: (last?.number ?? 0) + 1, snapshot: snapshot as never, note, publishedBy: by.id, publishedAt: ctx.now() },
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'site_published', targetType: 'site_version', targetId: String(version.number), metadata: { note } });
return version;
}
/** The latest published snapshot, or null before the first publish (Coming soon). */
export async function publishedSnapshot(ctx: Ctx): Promise<{ number: number; publishedAt: Date; snapshot: Snapshot } | null> {
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } });
if (!latest) return null;
const snap = latest.snapshot as unknown as Snapshot;
if (!snap || snap.v !== SNAPSHOT_VERSION) return null;
return { number: latest.number, publishedAt: latest.publishedAt, snapshot: { ...snap, design: cleanDesign(snap.design as never) } };
}
+149
View File
@@ -0,0 +1,149 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
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 { 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 { defaultDesign } from '../src/site/variants.js';
import { harness } from './support/harness.js';
const rgb = (triple: string) => triple.split(' ').map(Number) as [number, number, number];
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-'));
describe('colours from the church, made safe (§3)', () => {
it('keeps a dark colour as it is, with white text', () => {
const p = buildPalette('#1d5c63', '#e0a458');
assert.equal(p.brand, '29 92 99');
assert.equal(p.onBrand, '255 255 255');
assert.deepEqual(p.notes, []);
});
it('darkens a light colour for text on white, and says why', () => {
const p = buildPalette('#f5c542', null);
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5);
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5);
assert.ok(p.notes.some((n) => n.includes('darker shade')));
});
it('always gives readable text on the brand colour, whatever the church picks', () => {
for (const hex of ['#ff0000', '#00ff00', '#0000ff', '#888888', '#ffffff', '#000000', '#ff8800', '#00aaaa']) {
const p = buildPalette(hex, hex);
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5, hex);
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5, hex);
}
assert.deepEqual(hexToRgb('nonsense'), [31, 78, 121]);
});
});
describe('section data', () => {
it('fills defaults and refuses what doesn\'t fit', () => {
assert.deepEqual(parseSectionData('latestMessage', {}), { heading: null });
assert.equal(parseSectionData('hero', { headline: '' }), null);
assert.equal(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: 'javascript:alert(1)' } }), null);
assert.ok(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: '/visit' } }));
assert.equal(parseSectionData('nothing', {}), null);
});
});
describe('publishing (§4)', () => {
it('makes an unknown template, variant or section safe', () => {
const d = cleanDesign({ template: 'fancy', variants: { hero: 'spinning', team: 'list' }, home: [{ section: 'team' }, { section: 'nope' }], style: { spacing: 'compact', bad: 3 } });
assert.equal(d.template, 'heritage');
assert.equal(d.variants.hero, 'photo');
assert.equal(d.variants.team, 'list');
assert.equal(d.home[0]!.section, 'team');
assert.equal(d.home.length, 8);
assert.ok(d.home.slice(1).every((e) => e.hidden));
assert.equal(d.style.spacing, 'compact');
});
it('draws the homepage in the design\'s order and variants, leaving out hidden and broken sections', async () => {
const h = await harness();
const design = defaultDesign('clean');
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: design.variants, home: design.home, style: design.style } });
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
await h.db.section.create({ data: { pageId: home.id, type: 'hero', data: { headline: 'Welcome' } } });
await h.db.section.create({ data: { pageId: home.id, type: 'invitation', data: { heading: '' } } });
await h.db.section.create({ data: { pageId: home.id, type: 'team', data: {} } });
const snap = await buildSnapshot(h.ctx);
const types = snap.pages[0]!.sections.map((s) => s.type);
assert.deepEqual(types, ['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage'], 'Clean hides Team; the empty invitation is left out');
assert.equal(snap.pages[0]!.sections[0]!.variant, 'text');
assert.equal(snap.pages[0]!.path, '/');
});
it('numbers versions and keeps every one', async () => {
const h = await harness();
await publish(h.ctx, { id: 'u1', role: 'owner' }, 'First');
const v2 = await publish(h.ctx, { id: 'u1', role: 'owner' });
assert.equal(v2.number, 2);
assert.equal(await h.db.siteVersion.count(), 2);
});
});
describe('the public site\'s content', () => {
it('is Coming soon before the first publish, from the church profile', async () => {
const h = await harness({ linked: false });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'coming-soon');
assert.equal(c.church, null);
assert.equal(c.style.fontPairing, 'classic', 'Heritage\'s default pairing');
assert.equal(c.style.corners, 'sharp');
});
for (const template of WEBSITE_TEMPLATES) {
it(`loads and publishes the demo church on ${template}`, async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, template, { uploadDir: dir });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
assert.equal(c.snapshot.design.template, template);
assert.equal(c.church?.name, 'Acacia Hill Church');
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);
assert.ok(c.events[0]!.startsAt < c.events[1]!.startsAt);
assert.equal(c.transparentHeader['/'], template === 'bold', 'only Bold\'s header sits over the hero');
const hero = c.snapshot.pages[0]!.sections[0]!;
assert.equal(hero.type, 'hero');
const firstImage = (hero.data.images as string[])[0]!;
assert.match(c.snapshot.media[firstImage]!.url, /^\/api\/uploads\/demo\/hero\.svg$/);
assert.ok(fs.existsSync(path.join(dir, 'demo', 'hero.svg')));
});
}
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 } });
await loadDemo(h.ctx, 'community', { uploadDir: dir });
const svg = await request(h.app).get('/api/uploads/demo/hero.svg');
assert.equal(svg.status, 200);
assert.match(String(svg.headers['content-security-policy']), /sandbox/);
assert.equal((await request(h.app).get('/api/uploads/demo/')).status, 404);
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/..%2f..%2fpackage.json')).status));
assert.equal((await request(h.app).get('/api/uploads/missing.png')).status, 404);
const content = await request(h.app).get('/api/v1/site/content');
assert.equal(content.body.mode, 'published');
assert.equal(content.body.snapshot.design.template, 'community');
});
});
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');
assert.equal(youtubeId('https://youtu.be/abc123'), 'abc123');
assert.equal(youtubeId('https://www.youtube.com/live/xyz'), 'xyz');
assert.equal(youtubeId('https://example.com/watch?v=abc'), null);
assert.equal(spotifyEmbed('https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk?si=1'), 'https://open.spotify.com/embed/episode/4rOoJ6Egrf8K2IrywzwOMk');
assert.equal(spotifyEmbed('https://evil.example/episode/x'), null);
});
});
@@ -9,6 +9,9 @@ import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
messageSeries: () => ({ summary: null, imageId: null }),
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
+4
View File
@@ -0,0 +1,4 @@
test-results/
playwright-report/
.uploads/
screens/
+4
View File
@@ -0,0 +1,4 @@
{
"private": true,
"type": "module"
}
+47
View File
@@ -0,0 +1,47 @@
/**
* The e2e backend (playwright.config.ts): the Website's backend on port 5310 with the in-memory
* database from the backend tests (no Postgres needed) and the demo church published. The pages
* run with `next dev` on 3310 and send /api here.
*
* Test helpers: POST /test/demo?template=<id> loads the demo church on that template;
* POST /test/design { variants?, style?, home? } changes the design and publishes again.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
import { loadDemo } from '../backend/src/demo/demoChurch.js';
import { loadConfig } from '../backend/src/lib/config.js';
import { publish } from '../backend/src/site/snapshot.js';
import { memoryDb } from '../backend/tests/support/memoryDb.js';
const here = path.dirname(fileURLToPath(import.meta.url));
const uploads = path.join(here, '.uploads');
fs.mkdirSync(uploads, { recursive: true });
const db = memoryDb();
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);
await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'heritage'), { uploadDir: uploads });
const app = express();
app.post('/test/demo', async (req, res) => {
const t = websiteTemplateSchema.safeParse(req.query.template);
if (!t.success) return res.status(400).json({ error: 'template' });
await loadDemo(ctx, t.data, { uploadDir: uploads });
return res.json({ ok: true, template: t.data });
});
app.post('/test/design', express.json(), async (req, res) => {
const d = (await db.siteDesign.findUnique({ where: { id: 1 } })) as { variants: object; style: object; home: unknown };
await db.siteDesign.update({ where: { id: 1 }, data: {
variants: { ...d.variants, ...(req.body.variants ?? {}) },
style: { ...d.style, ...(req.body.style ?? {}) },
home: req.body.home ?? d.home,
} });
const v = await publish(ctx, { id: 'e2e', role: 'system' });
res.json({ ok: true, version: v.number });
});
app.use(createApp(ctx));
app.listen(5310, '127.0.0.1', () => console.log('[e2e] Website backend on 5310 with the demo church.'));
+73
View File
@@ -0,0 +1,73 @@
/**
* Every template with the demo church (WEBSITE-1.0-PLAN §13): the pages render at phone and desktop
* width, axe finds no violations, and the §11 basics are there (title, description, canonical,
* one <h1>, JSON-LD that parses). Screenshots go to e2e/screens/ for a look (not compared yet).
*/
import AxeBuilder from "@axe-core/playwright";
import { expect, test, type Page } from "@playwright/test";
const TEMPLATES = ["heritage", "bold", "community", "clean"] as const;
const PAGES = ["/", "/visit", "/ministries", "/events", "/messages", "/contact"];
async function useTemplate(page: Page, template: string) {
const res = await page.request.post(`http://127.0.0.1:5310/test/demo?template=${template}`);
expect(res.ok()).toBeTruthy();
}
async function seoBasics(page: Page) {
await expect(page).toHaveTitle(/.+/);
expect(await page.locator('meta[name="description"]').getAttribute("content")).toBeTruthy();
expect(await page.locator('link[rel="canonical"]').getAttribute("href")).toBeTruthy();
await expect(page.locator("h1")).toHaveCount(1);
for (const ld of await page.locator('script[type="application/ld+json"]').allTextContents()) JSON.parse(ld);
expect(await page.locator("html").getAttribute("lang")).toBe("en-ZA");
}
for (const template of TEMPLATES) {
test.describe(template, () => {
test.beforeEach(async ({ page }) => useTemplate(page, template));
test("its pages: accessible, with the SEO basics", async ({ page }) => {
for (const path of PAGES) {
const res = await page.goto(path);
expect(res?.status(), path).toBe(200);
await expect(page.locator("html")).toHaveAttribute("data-template", template);
await seoBasics(page);
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([]);
}
});
test("screenshots at phone and desktop", async ({ page }) => {
for (const [name, size] of [["desktop", { width: 1366, height: 900 }], ["phone", { width: 390, height: 844 }]] as const) {
await page.setViewportSize(size);
await page.goto("/");
// Scroll through, so lazy images load before the full-page shot.
await page.evaluate(async () => {
for (let y = 0; y < document.body.scrollHeight; y += 600) { window.scrollTo(0, y); await new Promise((r) => setTimeout(r, 60)); }
window.scrollTo(0, 0);
});
// The page's own images (not the map, which loads from OpenStreetMap).
await page.waitForFunction(() => Array.from(document.images).every((i) => i.complete), null, { timeout: 30_000 });
await page.screenshot({ path: `e2e/screens/${template}-home-${name}.png`, fullPage: true });
}
});
});
}
test("the home page has the church's JSON-LD; unknown pages are a real 404", async ({ page }) => {
await useTemplate(page, "heritage");
await page.goto("/");
const ld = JSON.parse((await page.locator('script[type="application/ld+json"]').first().textContent())!);
expect(ld["@type"]).toBe("Church");
expect(ld.name).toBe("Acacia Hill Church");
expect((await page.goto("/no-such-page"))?.status()).toBe(404);
});
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");
const sitemap = await (await page.request.get("/sitemap.xml")).text();
expect(sitemap).toContain("/visit</loc>");
expect(sitemap).not.toContain("/admin");
});
+7
View File
@@ -6,5 +6,12 @@ import nextTs from "eslint-config-next/typescript";
export default defineConfig([
...nextVitals,
...nextTs,
{
rules: {
// Uploads are resized into responsive sizes by the backend (WEBSITE-1.0-PLAN §3), and the
// logo and message thumbnails come from elsewhere: no Next image server.
"@next/next/no-img-element": "off",
},
},
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
]);
+1
View File
@@ -12,6 +12,7 @@
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"next": "^16.4.6",
"react": "^19.3.1",
@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { loadContent } from "@/site/load";
import { churchLd, pageMetadata } from "@/site/meta";
import { PageView } from "@/site/PageView";
import { Shell } from "@/site/Shell";
type Props = { params: Promise<{ slug: string }> };
async function find(slug: string) {
const c = await loadContent();
if (c.mode !== "published") return { c, page: null };
return { c, page: c.snapshot.pages.find((p) => p.kind !== "home" && p.slug === slug) ?? null };
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { c, page } = await find((await params).slug);
return c.mode === "published" && page ? pageMetadata(c, page) : { robots: { index: false } };
}
export default async function SitePage({ params }: Props) {
const { slug } = await params;
const { c, page } = await find(slug);
// Before the first publish every address shows Coming soon, on the home page.
if (c.mode !== "published") redirect("/");
if (!page) notFound();
const ld = page.kind === "contact" ? churchLd(c, page.path) : null;
return (
<Shell site={c} path={page.path}>
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
<PageView page={page} site={c} />
</Shell>
);
}
@@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { loadPublished } from "@/site/load";
import { fmtDate, fmtTime, Img } from "@/site/parts";
import { siteBase } from "@/site/meta";
import { Shell } from "@/site/Shell";
type Props = { params: Promise<{ slug: string }> };
async function find(slug: string) {
const site = await loadPublished();
const event = site?.events.find((e) => e.from === "website" && e.url === `/events/${slug}`) ?? null;
return { site, event };
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { site, event } = await find((await params).slug);
if (!site || !event) return { robots: { index: false } };
return { metadataBase: siteBase(site), title: event.title, description: event.summary ?? undefined, alternates: { canonical: event.url } };
}
/** A simple event made in the Website (§8). Cross Events' own events link to Cross Events instead. */
export default async function EventPage({ params }: Props) {
const { site, event } = await find((await params).slug);
if (!site || !event) notFound();
const zone = site.church?.timezone ?? "Africa/Johannesburg";
const events = site.snapshot.pages.find((p) => p.kind === "events");
return (
<Shell site={site} path={event.url}>
<article className="cc-section">
<div className="cc-wrap grid gap-10 md:grid-cols-2">
<Img image={event.image} priority />
<div>
<p className="cc-eyebrow">{fmtDate(event.startsAt, zone, { weekday: "long", day: "numeric", month: "long", year: "numeric" })}{!event.allDay && `, ${fmtTime(event.startsAt, zone)}`}</p>
<h1 className="cc-h1 mt-2">{event.title}</h1>
{event.location && <p className="cc-muted mt-3 text-lg">{event.location}</p>}
{event.summary && <p className="cc-prose mt-6">{event.summary}</p>}
{events && <a href={events.path} className="cc-link mt-8 inline-block font-semibold">All events</a>}
</div>
</div>
</article>
</Shell>
);
}
+118 -3
View File
@@ -2,15 +2,44 @@
@tailwind components;
@tailwind utilities;
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
/*
* The four templates (WEBSITE-1.0-PLAN §3). The layout sets, on <html>:
* data-template heritage | bold | community | clean
* data-spacing airy | compact (style setting)
* data-buttons solid | outline | pill (style setting)
* data-images natural | mono | duotone
* data-section-colour light | tinted | mixed
* data-cc-fonts / data-cc-corners (the church's shared brand style, @crosscode/ui)
* and the colours as CSS variables (--brand, --on-brand, --brand-text, --brand-tint, --accent, …).
* Section components use the cc-* classes below; each template restyles them.
*/
:root {
--brand: 31 78 121;
--brand-dark: 21 55 85;
--brand-dark: 25 62 97;
--on-brand: 255 255 255;
--brand-text: 31 78 121;
--brand-tint: 241 244 248;
--accent: 87 113 148;
--on-accent: 255 255 255;
--cc-section-y: 5rem;
--cc-wrap: 72rem;
--cc-text: 42rem;
}
[data-spacing="compact"] { --cc-section-y: 3rem; }
@media (max-width: 640px) {
:root { --cc-section-y: 3.5rem; }
[data-spacing="compact"] { --cc-section-y: 2.25rem; }
}
[data-template="heritage"] { --cc-wrap: 60rem; --cc-text: 40rem; }
[data-template="bold"] { --cc-wrap: 80rem; --cc-text: 46rem; }
[data-template="community"] { --cc-wrap: 72rem; --cc-text: 42rem; }
[data-template="clean"] { --cc-wrap: 48rem; --cc-text: 40rem; }
body {
@apply bg-white text-gray-900 antialiased;
/* The church's font pairing (@crosscode/ui fonts.css); the template's default until it picks one. */
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
}
@@ -18,3 +47,89 @@ h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
@layer components {
.cc-wrap { @apply mx-auto w-full px-4 sm:px-6; max-width: var(--cc-wrap); }
.cc-text { @apply mx-auto w-full; max-width: var(--cc-text); }
.cc-section { padding-block: var(--cc-section-y); }
/* Heritage: thin rules between sections, in one centred column. */
[data-template="heritage"] .cc-section + .cc-section { border-top: 1px solid rgb(var(--brand-text) / 0.18); }
/*
* Section colour: tinted alternates the church colour as a soft background; mixed adds dark bands.
* Never on a section that sets its own background (cc-own-bg: a banner, a photo, a dark band).
*/
[data-section-colour="tinted"] .cc-section:not(.cc-own-bg):nth-of-type(even) { background: rgb(var(--brand-tint)); }
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) { background: rgb(var(--brand-dark)); color: rgb(var(--on-brand)); }
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-card { background: rgb(255 255 255 / 0.06); border-color: rgb(255 255 255 / 0.2); color: inherit; }
/* Text on a dark background (Bold's cards and bands, a dark section): light, and still AA. */
.cc-dark .cc-muted, [data-template="bold"] .cc-card .cc-muted,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-muted { color: rgb(255 255 255 / 0.8); }
.cc-dark .cc-link, .cc-dark .cc-eyebrow, [data-template="bold"] .cc-card .cc-link, [data-template="bold"] .cc-card .cc-eyebrow,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-link,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-eyebrow { color: rgb(255 255 255); }
.cc-muted { color: rgb(75 85 99); }
.cc-link { color: rgb(var(--brand-text)); @apply underline-offset-4 hover:underline; }
.cc-eyebrow { @apply text-sm font-semibold uppercase tracking-widest; color: rgb(var(--brand-text)); }
[data-template="heritage"] .cc-eyebrow { @apply font-normal tracking-[0.25em]; font-variant: small-caps; text-transform: none; }
[data-template="community"] .cc-eyebrow { @apply normal-case tracking-normal; }
/* Headings: each template's voice. */
.cc-h1 { @apply text-4xl leading-tight sm:text-5xl; }
.cc-h2 { @apply text-3xl leading-tight sm:text-4xl; }
.cc-h3 { @apply text-xl leading-snug; }
[data-template="heritage"] .cc-h1, [data-template="heritage"] .cc-h2 { @apply font-normal tracking-wide; }
[data-template="heritage"] .cc-h3 { @apply font-normal; }
[data-template="bold"] .cc-h1 { @apply text-5xl font-bold uppercase leading-[0.95] sm:text-7xl; letter-spacing: -0.01em; }
[data-template="bold"] .cc-h2 { @apply text-4xl font-bold uppercase leading-none sm:text-5xl; }
[data-template="bold"] .cc-h3 { @apply font-bold uppercase; }
[data-template="community"] .cc-h1, [data-template="community"] .cc-h2 { @apply font-extrabold; }
[data-template="community"] .cc-h3 { @apply font-bold; }
[data-template="clean"] .cc-h1 { @apply font-semibold sm:text-6xl; letter-spacing: -0.03em; }
[data-template="clean"] .cc-h2 { @apply text-2xl font-semibold sm:text-3xl; letter-spacing: -0.02em; }
[data-template="clean"] .cc-h3 { @apply font-semibold; }
/* Buttons: solid, outline or pill (style setting); corners from the church's brand style. */
.cc-btn {
@apply inline-flex items-center justify-center gap-2 px-6 py-3 text-base font-semibold no-underline transition-colors;
border-radius: var(--cc-radius-button, 0.5rem);
background: rgb(var(--brand)); color: rgb(var(--on-brand)); border: 2px solid rgb(var(--brand));
}
.cc-btn:hover { background: rgb(var(--brand-dark)); border-color: rgb(var(--brand-dark)); }
.cc-btn:focus-visible { outline: 3px solid rgb(var(--accent)); outline-offset: 2px; }
[data-buttons="outline"] .cc-btn { background: transparent; color: rgb(var(--brand-text)); border-color: currentColor; }
[data-buttons="outline"] .cc-btn:hover { background: rgb(var(--brand)); color: rgb(var(--on-brand)); border-color: rgb(var(--brand)); }
[data-buttons="pill"] .cc-btn { border-radius: 9999px; }
[data-template="bold"] .cc-btn { @apply uppercase tracking-wider; }
/* A button on a photo or a dark band: always light on dark. */
.cc-on-dark .cc-btn, .cc-dark .cc-btn, [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-btn {
background: rgb(255 255 255); color: rgb(17 24 39); border-color: rgb(255 255 255);
}
/* Cards. */
.cc-card { @apply overflow-hidden bg-white; border-radius: var(--cc-radius, 0.5rem); }
[data-template="heritage"] .cc-card { border: 1px solid rgb(var(--brand-text) / 0.2); }
[data-template="bold"] .cc-card { @apply bg-gray-900 text-white; }
[data-template="community"] .cc-card { @apply shadow-md; box-shadow: 0 10px 30px -12px rgb(var(--brand) / 0.35); }
[data-template="clean"] .cc-card { border-bottom: 1px solid rgb(229 231 235); border-radius: 0; }
/* Images: natural, black and white, or duotone in the church colour (style setting). */
.cc-img { @apply block h-full w-full object-cover; border-radius: var(--cc-radius-sm, 0); }
.cc-frame { @apply relative overflow-hidden; border-radius: var(--cc-radius, 0); }
[data-images="mono"] .cc-img { filter: grayscale(1) contrast(1.05); }
[data-images="duotone"] .cc-img { filter: grayscale(1) contrast(1.1); mix-blend-mode: multiply; }
[data-images="duotone"] .cc-frame { background: rgb(var(--brand)); }
/* Heritage frames its images. */
[data-template="heritage"] .cc-frame { padding: 0.5rem; background: white; border: 1px solid rgb(var(--brand-text) / 0.25); }
[data-template="heritage"][data-images="duotone"] .cc-frame { background: rgb(var(--brand)); }
/* Prose for text the admins write (paragraphs only; no HTML is ever rendered). */
.cc-prose p + p { margin-top: 1em; }
.cc-prose { @apply text-lg leading-relaxed; }
}
@media (prefers-reduced-motion: reduce) {
.cc-motion { display: none !important; }
}
+28 -7
View File
@@ -2,16 +2,37 @@ import type { Metadata } from "next";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { loadContent } from "@/site/load";
// The church's name, colours, fonts and corners come from its profile in Accounts once the Website
// is linked (docs/WEBSITE-1.0-PLAN.md §2); until then, plain defaults.
export const metadata: Metadata = {
title: { default: "Church Website", template: "%s" },
};
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 };
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
/**
* Every page: the church's fonts and corners (shared brand style), the template and the style
* settings as attributes (globals.css), and its colours, made safe by the backend, as variables.
*/
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const c = await loadContent();
const p = c.palette;
const template = c.mode === "published" ? c.snapshot.design.template : c.template;
const s = c.mode === "published" ? c.snapshot.design.style : null;
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
return (
<html lang="en-ZA" {...brandAttributes(null)}>
<html
lang="en-ZA"
{...brandAttributes(c.style)}
data-template={template}
data-spacing={s?.spacing ?? "airy"}
data-buttons={s?.buttons ?? "solid"}
data-images={s?.images ?? "natural"}
data-section-colour={s?.sectionColour ?? "light"}
>
<head>
<style>{vars.replace(/[<>]/g, "")}</style>
</head>
<body>{children}</body>
</html>
);
@@ -0,0 +1,17 @@
import Link from "next/link";
import { loadPublished } from "@/site/load";
import { Shell } from "@/site/Shell";
export default async function NotFound() {
const site = await loadPublished();
const body = (
<section className="cc-section">
<div className="cc-wrap text-center">
<h1 className="cc-h1">Page not found</h1>
<p className="cc-muted mt-4 text-lg">That page isn&apos;t here. It may have moved.</p>
<Link href="/" className="cc-btn mt-8">Go to the home page</Link>
</div>
</section>
);
return site ? <Shell site={site} path="/404">{body}</Shell> : <main>{body}</main>;
}
+24 -22
View File
@@ -1,31 +1,33 @@
import type { Metadata } from "next";
import { loadStatus } from "@/lib/site";
// Rendered per request from the backend's status; the published site is cached once it exists (§1).
export const dynamic = "force-dynamic";
import { cookies } from "next/headers";
import { ComingSoon } from "@/site/ComingSoon";
import { loadContent } from "@/site/load";
import { churchLd, pageMetadata } from "@/site/meta";
import { Sections } from "@/site/sections";
import { Shell } from "@/site/Shell";
export async function generateMetadata(): Promise<Metadata> {
const status = await loadStatus();
// Coming soon is a real page (HTTP 200) but never indexed (§5, decision 14).
return status.mode === "coming-soon" ? { title: "Coming soon", robots: { index: false, follow: true } } : { title: "Home" };
const c = await loadContent();
if (c.mode === "coming-soon") {
// A real page (HTTP 200) that's never indexed (§5, decision 14).
return { title: { absolute: c.church ? `${c.church.name}: coming soon` : "Coming soon" }, robots: { index: false, follow: true } };
}
const home = c.snapshot.pages.find((p) => p.kind === "home");
return home ? pageMetadata(c, home) : {};
}
export default async function Home() {
const status = await loadStatus();
if (status.mode === "coming-soon") {
// The full Coming soon page (logo, service times, contact, links to Events) comes with the
// church profile (§5).
return (
<main className="mx-auto flex min-h-screen max-w-xl flex-col items-center justify-center gap-4 px-4 text-center">
<h1 className="text-3xl font-semibold text-brand">Coming soon</h1>
<p className="text-gray-600">Our new website is on its way.</p>
</main>
);
}
const c = await loadContent();
if (c.mode === "coming-soon") return <ComingSoon c={c} signedInAdmin={(await cookies()).has("ccw_session")} />;
const home = c.snapshot.pages.find((p) => p.kind === "home");
const sections = home?.sections ?? [];
const ld = churchLd(c, "/");
return (
<main className="mx-auto max-w-3xl px-4 py-16">
<h1 className="text-3xl font-semibold">Welcome</h1>
<p className="mt-2 text-gray-600">Published version {status.version}. The templates come next (§3).</p>
</main>
<Shell site={c} path="/">
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
{/* Exactly one <h1> (§11): the hero's, else the church's name. */}
{sections[0]?.type !== "hero" && <h1 className="sr-only">{c.church?.name ?? "Home"}</h1>}
<Sections site={c} sections={sections} />
</Shell>
);
}
+19
View File
@@ -0,0 +1,19 @@
import type { MetadataRoute } from "next";
import { loadContent } from "@/site/load";
import { siteBase } from "@/site/meta";
/**
* The published pages and the Website's own events (ROADMAP-v3 §11). Events copied from Cross
* Events aren't listed: their canonical page is at the origin. Before the first publish: empty.
*/
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const c = await loadContent();
if (c.mode !== "published") return [];
const base = siteBase(c);
if (!base) return [];
const at = (path: string) => new URL(path, base).toString();
return [
...c.snapshot.pages.map((p) => ({ url: at(p.path), changeFrequency: "weekly" as const, priority: p.kind === "home" ? 1 : 0.7 })),
...c.events.filter((e) => e.from === "website" && e.url.startsWith("/")).map((e) => ({ url: at(e.url), changeFrequency: "weekly" as const, priority: 0.5 })),
];
}
-16
View File
@@ -1,16 +0,0 @@
/** What the public site shows right now, from the backend (src/site/status.ts there). */
export type SiteStatus =
| { mode: "coming-soon" }
| { mode: "published"; version: number; publishedAt: string; template: string | null };
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
export async function loadStatus(): Promise<SiteStatus> {
try {
const res = await fetch(`${api}/api/v1/site/status`, { next: { revalidate: 30 } });
if (res.ok) return (await res.json()) as SiteStatus;
} catch {
// The backend is starting or down: Coming soon is the safe thing to show.
}
return { mode: "coming-soon" };
}
@@ -0,0 +1,52 @@
/**
* Coming soon (WEBSITE-1.0-PLAN §5): until the first publish, the church's details from its
* profile (logo, service times, address, contact, social), links to its Events and App, and a line
* the admin can change. `noindex`, a real HTTP 200.
*/
import Link from "next/link";
import { dayName } from "./parts";
import type { ComingSoon as Content } from "./types";
export function ComingSoon({ c, signedInAdmin }: { c: Content; signedInAdmin: boolean }) {
const church = c.church;
const a = church?.contact.address;
const links = church ? ([["Events", church.links.events], ["App", church.links.app]] as const).filter(([, u]) => u) : [];
return (
<main className="flex min-h-screen flex-col items-center justify-center bg-brand-tint px-4 py-16 text-center">
{signedInAdmin && (
<p className="mb-8 rounded-cc bg-white px-4 py-3 text-sm shadow">
Your site isn&apos;t published yet. <Link href="/admin" className="cc-link font-semibold">Preview it or publish it</Link>.
</p>
)}
{church?.branding.logoUrl
? <img src={church.branding.logoUrl} alt={church.name} className="mb-8 h-20 w-auto max-w-[16rem] object-contain" />
: church && <p className="cc-eyebrow mb-4">{church.name}</p>}
<h1 className="cc-h1 text-brand-text">{church ? `${church.name}: coming soon` : "Coming soon"}</h1>
<p className="cc-muted mt-4 max-w-xl text-lg">{c.comingSoonText}</p>
{church && (
<div className="mt-10 grid w-full max-w-2xl gap-8 rounded-cc bg-white p-8 text-left shadow sm:grid-cols-2">
{church.serviceTimes.length > 0 && (
<div>
<h2 className="cc-h3 mb-2">Service times</h2>
<ul className="space-y-1">{church.serviceTimes.map((s, i) => <li key={i}>{dayName(s.day)} {s.time}{s.label && <span className="cc-muted"> · {s.label}</span>}</li>)}</ul>
</div>
)}
<div>
<h2 className="cc-h3 mb-2">Find us</h2>
{a && <address className="not-italic">{[a.line1, a.line2, a.suburb, a.city].filter(Boolean).join(", ")}</address>}
<ul className="mt-2 space-y-1">
{church.contact.phone && <li><a className="cc-link" href={`tel:${church.contact.phone}`}>{church.contact.phone}</a></li>}
{church.contact.email && <li><a className="cc-link break-all" href={`mailto:${church.contact.email}`}>{church.contact.email}</a></li>}
{church.social.map((s) => <li key={s.url}><a className="cc-link capitalize" href={s.url} rel="me noopener">{s.network.replace("-", " ")}</a></li>)}
</ul>
</div>
</div>
)}
{links.length > 0 && (
<div className="mt-8 flex flex-wrap justify-center gap-3">
{links.map(([label, url]) => <a key={label} href={url!} className="cc-btn">Our {label}</a>)}
</div>
)}
</main>
);
}
+132
View File
@@ -0,0 +1,132 @@
/**
* Each template's header (WEBSITE-1.0-PLAN §3, "Headers"), with its options from the Header style
* setting. Every header collapses to a Menu button on phones (a <details>, so it works without
* JavaScript). Links to the church's other sites (Events, App) sit next to the pages (§9).
*/
import Link from "next/link";
import { productLinks } from "@crosscode/ui";
import { ScrollSolid } from "./ScrollSolid";
import { cx } from "./parts";
import type { Published } from "./types";
type Item = { label: string; href: string; current: boolean };
function items(site: Published, path: string): { nav: Item[]; visit: Item | null } {
const pages = site.snapshot.pages;
const nav: Item[] = pages.filter((p) => p.inNav).map((p) => ({ label: p.navLabel, href: p.path, current: p.path === path }));
for (const l of site.church ? productLinks(site.church.links, "website") : []) nav.push({ label: l.label, href: l.href, current: false });
const v = pages.find((p) => p.kind === "visit");
return { nav, visit: v ? { label: v.navLabel, href: v.path, current: v.path === path } : null };
}
function Brand({ site, className, light }: { site: Published; className?: string; light?: boolean }) {
const church = site.church;
const name = church?.name ?? "Home";
return (
<Link href="/" className={cx("inline-flex items-center gap-3 no-underline", className)} aria-label={`${name}, home`}>
{church?.branding.logoUrl
? <img src={church.branding.logoUrl} alt="" className={cx("h-10 w-auto max-w-[12rem] object-contain", light && "brightness-0 invert")} />
: <span className="font-heading text-xl font-semibold">{name}</span>}
</Link>
);
}
function Links({ nav, className, linkClass }: { nav: Item[]; className?: string; linkClass?: string }) {
return (
<ul className={className}>
{nav.map((n) => (
<li key={n.href}>
<a href={n.href} aria-current={n.current ? "page" : undefined} className={cx("no-underline hover:underline underline-offset-8", n.current && "underline", linkClass)}>{n.label}</a>
</li>
))}
</ul>
);
}
function MobileMenu({ nav, visit, className, always = false }: { nav: Item[]; visit: Item | null; className?: string; always?: boolean }) {
return (
<details className={cx("group relative", !always && "md:hidden", className)}>
<summary className="cursor-pointer list-none rounded-cc-sm border border-current px-3 py-1.5 text-sm font-semibold [&::-webkit-details-marker]:hidden">Menu</summary>
<nav aria-label="Main" className="absolute right-0 z-50 mt-2 w-64 rounded-cc bg-white p-4 text-gray-900 shadow-xl">
<Links nav={nav} className="space-y-3 text-base" />
{visit && <a href={visit.href} className="cc-btn mt-4 w-full">{visit.label}</a>}
</nav>
</details>
);
}
export function Header({ site, path }: { site: Published; path: string }) {
const { template, style } = site.snapshot.design;
const { nav, visit } = items(site, path);
const option = style.header;
if (template === "heritage") {
const nextService = site.church?.serviceTimes[0];
return (
<header className="bg-white">
{option === "centred-top-bar" && (nextService || visit) && (
<div className="bg-brand text-sm text-brand-on">
<div className="cc-wrap flex items-center justify-center gap-4 py-2">
{nextService && <span>Sundays {site.church!.serviceTimes.filter((s) => s.day === "sunday").map((s) => s.time).join(" & ") || nextService.time}</span>}
{visit && <a href={visit.href} className="font-semibold underline underline-offset-4">{visit.label}</a>}
</div>
</div>
)}
<div className="cc-wrap flex flex-col items-center gap-5 py-8">
<Brand site={site} className="text-center text-2xl" />
<nav aria-label="Main" className="hidden w-full border-y border-brand-text/20 py-3 md:block">
<Links nav={nav} className="flex flex-wrap justify-center gap-x-8 gap-y-2 text-sm uppercase tracking-[0.18em]" />
</nav>
<MobileMenu nav={nav} visit={visit} />
</div>
</header>
);
}
if (template === "bold") {
const transparent = !!site.transparentHeader[path];
return (
<ScrollSolid transparent={transparent} className="sticky top-0 z-40">
<div className="cc-wrap flex items-center justify-between gap-6 py-4">
<Brand site={site} className="text-white" light={transparent} />
<nav aria-label="Main" className="hidden items-center gap-8 md:flex">
<Links nav={nav} className="flex gap-6 text-sm font-semibold uppercase tracking-wider" />
{visit && <a href={visit.href} className="cc-btn px-5 py-2 text-sm">{visit.label}</a>}
</nav>
<MobileMenu nav={nav} visit={visit} />
</div>
</ScrollSolid>
);
}
if (template === "community") {
return (
<header className={cx(option === "logo-left-tinted" ? "bg-brand-tint" : "bg-white", "border-b border-brand/10")}>
<div className="cc-wrap flex items-center justify-between gap-6 py-4">
<Brand site={site} />
<nav aria-label="Main" className="hidden items-center gap-6 md:flex">
<Links nav={nav} className="flex gap-5 font-semibold" linkClass="text-gray-800" />
{visit && <a href={visit.href} className="cc-btn px-5 py-2">{visit.label}</a>}
</nav>
<MobileMenu nav={nav} visit={visit} />
</div>
</header>
);
}
// Clean: small, logo left, text navigation (or a menu on every width).
const menuOnly = option === "small-menu";
return (
<header className="bg-white">
<div className="mx-auto flex w-full max-w-5xl items-center justify-between gap-6 px-4 py-5 sm:px-6">
<Brand site={site} className="text-lg" />
{!menuOnly && (
<nav aria-label="Main" className="hidden md:block">
<Links nav={nav} className="flex gap-6 text-sm text-gray-700" />
</nav>
)}
<MobileMenu nav={nav} visit={visit} always={menuOnly} />
</div>
</header>
);
}
@@ -0,0 +1,33 @@
"use client";
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.
*/
export function MessagePlayer({ title, embedUrl, thumbnail, url, source, className }: { title: string; embedUrl: string | null; thumbnail: string | null; url: string; source: "youtube" | "spotify"; className?: string }) {
const [playing, setPlaying] = useState(false);
const ratio = source === "spotify" ? "aspect-[16/7]" : "aspect-video";
if (playing && embedUrl) {
return (
<div className={`cc-frame ${ratio} ${className ?? ""}`}>
<iframe src={embedUrl} title={title} className="h-full w-full" allow="autoplay; encrypted-media; picture-in-picture" allowFullScreen referrerPolicy="strict-origin-when-cross-origin" />
</div>
);
}
return (
<div className={`cc-frame relative ${ratio} ${className ?? ""} bg-gray-900`}>
{thumbnail && <img src={thumbnail} alt="" className="cc-img absolute inset-0 opacity-80" loading="lazy" />}
{embedUrl ? (
<button type="button" onClick={() => setPlaying(true)} className="absolute inset-0 flex items-center justify-center" aria-label={`Play ${title}`}>
<span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/95 text-gray-900 shadow-lg">
<svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" aria-hidden="true"><path fill="currentColor" d="M8 5v14l11-7z" /></svg>
</span>
</button>
) : (
<a href={url} rel="noopener" className="absolute inset-0 flex items-center justify-center font-semibold text-white underline">Open the message</a>
)}
</div>
);
}
+120
View File
@@ -0,0 +1,120 @@
/**
* 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 { MessagePlayer } from "./MessagePlayer";
import { t } from "./load";
import { cx, DateBadge, dayName, fmtDate, Img, Paragraphs } from "./parts";
import { EventLine, Sections } from "./sections";
import type { Page, Published } from "./types";
function PageTitle({ page, site }: { page: Page; site: Published }) {
const template = site.snapshot.design.template;
return (
<div className={t(template, { bold: "bg-gray-950 pb-14 pt-28 text-white", community: "bg-brand-tint py-14", heritage: "py-14 text-center", clean: "pb-6 pt-16" })}>
<div className="cc-wrap">
<h1 className="cc-h1">{page.title}</h1>
{page.description && <p className={cx("mt-4 max-w-2xl text-lg", template === "bold" ? "text-white/80" : "cc-muted", template === "heritage" && "mx-auto")}>{page.description}</p>}
</div>
</div>
);
}
function Listing({ page, site }: { page: Page; site: Published }) {
const zone = site.church?.timezone ?? "Africa/Johannesburg";
const template = site.snapshot.design.template;
switch (page.kind) {
case "ministries":
return (
<section className="cc-section">
<div className="cc-wrap space-y-14">
{site.snapshot.ministries.map((m, i) => (
<article key={m.slug} id={m.slug} className="grid scroll-mt-24 items-center gap-8 md:grid-cols-2">
<Img image={m.image} className={cx(i % 2 === 1 && "md:order-2", template === "community" && "rounded-[2rem]")} />
<div><h2 className="cc-h2">{m.name}</h2>{m.summary && <p className="cc-muted mt-3 text-lg">{m.summary}</p>}<Paragraphs text={m.body} className="mt-4" /></div>
</article>
))}
</div>
</section>
);
case "leadership":
return (
<section className="cc-section">
<div className="cc-wrap grid gap-10 sm:grid-cols-2 lg:grid-cols-3">
{site.snapshot.leaders.map((l) => (
<article key={l.name}>
<Img image={l.photo} ratio="aspect-square" className={cx((template === "heritage" || template === "community") && "rounded-full", "mx-auto max-w-[14rem]")} />
<h2 className="cc-h3 mt-4 text-center">{l.name}</h2>
{l.role && <p className="cc-muted text-center">{l.role}</p>}
<Paragraphs text={l.bio} className="mt-3 !text-base" />
</article>
))}
</div>
</section>
);
case "events":
return (
<section className="cc-section">
<div className="cc-wrap">
{site.events.length === 0 && <p className="cc-muted">Nothing on the calendar just now. Check back soon.</p>}
<ul className="divide-y divide-gray-200">
{site.events.map((e) => (
<li key={e.url + e.startsAt} className="flex gap-5 py-6">
<DateBadge iso={e.startsAt} timeZone={zone} />
<div><h2 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h2><EventLine e={e} timeZone={zone} />{e.summary && <p className="mt-2">{e.summary}</p>}</div>
</li>
))}
</ul>
</div>
</section>
);
case "messages":
return (
<section className="cc-section">
<div className="cc-wrap grid gap-10 sm:grid-cols-2">
{site.messages.map((m) => (
<article key={m.slug} id={m.slug} className="scroll-mt-24">
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} />
{m.series && <p className="cc-eyebrow mt-4">{m.series}</p>}
<h2 className="cc-h3 mt-1">{m.title}</h2>
<p className="cc-muted text-sm">{[m.speaker, m.passage, fmtDate(m.date, zone, { day: "numeric", month: "long", year: "numeric" })].filter(Boolean).join(" · ")}</p>
</article>
))}
</div>
</section>
);
case "contact": {
const c = site.church;
if (!c) return null;
const a = c.contact.address;
return (
<section className="cc-section">
<div className="cc-wrap grid gap-10 md:grid-cols-2">
<div className="space-y-6">
{a && <div><h2 className="cc-h3">Address</h2><address className="not-italic">{[a.line1, a.line2, a.suburb, a.city, a.postalCode].filter(Boolean).join(", ")}</address></div>}
{c.contact.phone && <div><h2 className="cc-h3">Phone</h2><a className="cc-link" href={`tel:${c.contact.phone}`}>{c.contact.phone}</a></div>}
{c.contact.whatsapp && <div><h2 className="cc-h3">WhatsApp</h2><a className="cc-link" href={`https://wa.me/${c.contact.whatsapp.replace(/\D/g, "")}`}>{c.contact.whatsapp}</a></div>}
{c.contact.email && <div><h2 className="cc-h3">Email</h2><a className="cc-link break-all" href={`mailto:${c.contact.email}`}>{c.contact.email}</a></div>}
</div>
<div>
<h2 className="cc-h3">Service times</h2>
<ul className="mt-2 space-y-1">{c.serviceTimes.map((s, i) => <li key={i}>{dayName(s.day)} {s.time}{s.label && ` · ${s.label}`}</li>)}</ul>
</div>
</div>
</section>
);
}
default:
return null;
}
}
export function PageView({ page, site }: { page: Page; site: Published }) {
return (
<>
<PageTitle page={page} site={site} />
<Listing page={page} site={site} />
<Sections site={site} sections={page.sections} />
</>
);
}
@@ -0,0 +1,26 @@
"use client";
import { useEffect, useState } from "react";
/**
* Bold's header: transparent over the hero, solid once the page scrolls (§3). Without JavaScript,
* or on a page whose first section isn't a photo, video or collage hero, it's always solid.
*/
export function ScrollSolid({ transparent, className, children }: { transparent: boolean; className?: string; children: React.ReactNode }) {
const [solid, setSolid] = useState(!transparent);
useEffect(() => {
if (!transparent) return;
const onScroll = () => setSolid(window.scrollY > 40);
onScroll();
window.addEventListener("scroll", onScroll, { passive: true });
return () => window.removeEventListener("scroll", onScroll);
}, [transparent]);
return (
<header
className={`${className ?? ""} ${transparent ? "-mb-[72px]" : ""} transition-colors duration-200 ${solid ? "bg-gray-950 text-white shadow-lg" : "bg-transparent text-white"}`}
data-solid={solid ? "true" : "false"}
>
{children}
</header>
);
}
+37
View File
@@ -0,0 +1,37 @@
/** Every public page: the template's header, the page, and the shared church footer (§9). */
import { ChurchFooter } from "@crosscode/ui";
import { Header } from "./Header";
import { t } from "./load";
import type { Published } from "./types";
export function Shell({ site, path, children }: { site: Published; path: string; children: React.ReactNode }) {
const template = site.snapshot.design.template;
const terms = site.snapshot.pages.find((p) => p.kind === "terms");
const safeguarding = site.snapshot.pages.find((p) => p.kind === "safeguarding");
return (
<>
<a href="#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-4 focus:py-2 focus:text-gray-900">Skip to the content</a>
<Header site={site} path={path} />
<main id="main">{children}</main>
{site.church && (
<ChurchFooter
church={site.church}
current="website"
privacyUrl={`${site.church.links.accounts.replace(/\/+$/, "")}/privacy`}
className={t(template, {
heritage: "border-t-4 border-double border-brand-text/30 bg-brand-tint/60",
bold: "border-0 bg-gray-950 text-gray-300 [&_h2]:text-white [&_a:hover]:text-white",
community: "border-0 bg-brand-tint",
clean: "border-gray-200 bg-white",
})}
bottom={(terms || safeguarding) && (
<>
{terms && <a href={terms.path} className="hover:underline">{terms.navLabel}</a>}
{safeguarding && <a href={safeguarding.path} className="hover:underline">{safeguarding.navLabel}</a>}
</>
)}
/>
)}
</>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { cache } from "react";
import type { Image, Published, SiteContent, Template } from "./types";
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
const FALLBACK: SiteContent = {
mode: "coming-soon",
template: "heritage",
comingSoonText: "Our new website is on its way.",
church: null,
palette: { brand: "31 78 121", brandDark: "25 62 97", onBrand: "255 255 255", brandText: "31 78 121", brandTint: "241 244 248", accent: "87 113 148", onAccent: "255 255 255", notes: [] },
style: { fontPairing: "classic", corners: "sharp" },
};
/**
* The site as visitors see it: one fetch per request (React `cache`), kept by Next for 30 seconds,
* so Publish shows within half a minute. While the backend can't answer: Coming soon, never an
* error page.
*/
export const loadContent = cache(async (): Promise<SiteContent> => {
try {
// In development (and the e2e run) always fresh, so a Publish shows at once.
const res = await fetch(`${api}/api/v1/site/content`, process.env.NODE_ENV === "production" ? { next: { revalidate: 30 } } : { cache: "no-store" });
if (res.ok) return (await res.json()) as SiteContent;
} catch {
// Starting or down.
}
return FALLBACK;
});
export async function loadPublished(): Promise<Published | null> {
const c = await loadContent();
return c.mode === "published" ? c : null;
}
/** An image from a section's data (a media id), or null. */
export const media = (site: Published, id: unknown): Image | null => (typeof id === "string" ? site.snapshot.media[id] ?? null : null);
/** Per-template class names: `t(template, { heritage: "…", bold: "…" }, "fallback")`. */
export const t = (template: Template, by: Partial<Record<Template, string>>, otherwise = "") => by[template] ?? otherwise;
export const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v : null);
+37
View File
@@ -0,0 +1,37 @@
/**
* Search engine basics on every page (ROADMAP-v3 §11): a unique title and description, a
* canonical address, Open Graph with an image, and the church's JSON-LD on home and contact.
*/
import type { Metadata } from "next";
import { churchJsonLd, jsonLdString, pageMeta } from "@crosscode/seo";
import type { Page, Published } from "./types";
export function siteBase(site: Published): URL | undefined {
try {
return site.church?.links.website ? new URL(site.church.links.website) : undefined;
} catch {
return undefined;
}
}
export function pageMetadata(site: Published, page: Page): Metadata {
const name = site.church?.name ?? "Church";
const meta = pageMeta({ title: page.kind === "home" ? null : page.seoTitle || page.title, description: page.description, fallbackDescription: `${name}: ${page.title}` });
const firstImage = page.image ?? Object.values(site.snapshot.media)[0] ?? null;
const image = firstImage?.url.endsWith(".svg") ? null : firstImage;
return {
metadataBase: siteBase(site),
title: page.kind === "home" ? { absolute: page.seoTitle || name } : meta.title,
description: meta.description,
alternates: { canonical: page.path },
openGraph: { type: "website", siteName: name, title: page.kind === "home" ? name : page.title, description: meta.description, url: page.path, locale: "en_ZA", ...(image ? { images: [{ url: image.url, alt: image.alt }] } : site.church?.branding.logoUrl ? { images: [site.church.branding.logoUrl] } : {}) },
twitter: { card: image ? "summary_large_image" : "summary" },
};
}
/** `<script type="application/ld+json">` contents for the church (home and contact pages). */
export function churchLd(site: Published, path: string): string | null {
if (!site.church) return null;
const base = siteBase(site);
return jsonLdString(churchJsonLd(site.church, base ? { url: new URL(path, base).toString() } : {}));
}
+73
View File
@@ -0,0 +1,73 @@
/** Small building blocks every template uses. */
import type { Image } from "./types";
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
/** An image in a frame (Heritage frames, duotone tints), or a soft placeholder when there's none. */
export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) {
return (
<div className={cx("cc-frame", ratio, className)}>
{image ? (
<img src={image.url} alt={image.alt} sizes={sizes} width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className="cc-img" />
) : (
<div aria-hidden="true" className="h-full w-full bg-gradient-to-br from-brand/25 via-brand-tint to-accent/30" />
)}
</div>
);
}
export type ButtonData = { label: string; href: string } | null | undefined;
export function Button({ button, className }: { button: ButtonData; className?: string }) {
if (!button?.label || !button.href) return null;
const external = button.href.startsWith("https://");
return (
<a href={button.href} className={cx("cc-btn", className)} {...(external ? { rel: "noopener" } : {})}>
{button.label}
</a>
);
}
/** Text the admins wrote, as paragraphs (blank lines). Never HTML. */
export function Paragraphs({ text, className }: { text: string | null | undefined; className?: string }) {
if (!text) return null;
const paras = text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
return (
<div className={cx("cc-prose", className)}>
{paras.map((p, i) => <p key={i}>{p.split("\n").map((line, j) => <span key={j}>{j > 0 && <br />}{line}</span>)}</p>)}
</div>
);
}
const DAYS: Record<string, string> = { monday: "Monday", tuesday: "Tuesday", wednesday: "Wednesday", thursday: "Thursday", friday: "Friday", saturday: "Saturday", sunday: "Sunday" };
export const dayName = (d: string) => DAYS[d] ?? d;
export function fmtDate(iso: string, timeZone: string, opts: Intl.DateTimeFormatOptions = { weekday: "short", day: "numeric", month: "long" }) {
return new Intl.DateTimeFormat("en-ZA", { timeZone, ...opts }).format(new Date(iso));
}
export function fmtTime(iso: string, timeZone: string) {
return new Intl.DateTimeFormat("en-ZA", { timeZone, hour: "2-digit", minute: "2-digit", hour12: false }).format(new Date(iso));
}
/** Day and month in a box (event cards and lists). */
export function DateBadge({ iso, timeZone, className }: { iso: string; timeZone: string; className?: string }) {
return (
<div className={cx("flex w-16 shrink-0 flex-col items-center justify-center rounded-cc-sm bg-brand py-2 text-brand-on", className)} aria-hidden="true">
<span className="text-2xl font-bold leading-none">{fmtDate(iso, timeZone, { day: "numeric" })}</span>
<span className="text-xs uppercase tracking-wide">{fmtDate(iso, timeZone, { month: "short" })}</span>
</div>
);
}
export function SectionHeading({ eyebrow, heading, intro, centred = false, as: H = "h2" }: { eyebrow?: string | null; heading?: string | null; intro?: string | null; centred?: boolean; as?: "h1" | "h2" }) {
if (!heading && !eyebrow && !intro) return null;
return (
<div className={cx("mb-10", centred && "text-center")}>
{eyebrow && <p className="cc-eyebrow mb-2">{eyebrow}</p>}
{heading && <H className={H === "h1" ? "cc-h1" : "cc-h2"}>{heading}</H>}
{intro && <p className={cx("cc-muted mt-3 text-lg", centred && "mx-auto max-w-2xl")}>{intro}</p>}
</div>
);
}
@@ -0,0 +1,167 @@
/**
* The hero (WEBSITE-1.0-PLAN §3): Photo · Video · Collage · Split · Text only, each drawn in the
* template's way. Bold fills the screen with the headline over a dark scrim; Heritage frames the
* image under its centred header; Community overlaps rounded photos; Clean never puts text on a
* photo.
*/
import { media } from "../load";
import { Button, cx, Img, type ButtonData } from "../parts";
import type { Image, SectionProps } from "../types";
type HeroData = { headline: string; subline: string | null; images: string[]; videoId: string | null; button: ButtonData };
function Words({ d, centred, light, size = "cc-h1" }: { d: HeroData; centred?: boolean; light?: boolean; size?: string }) {
return (
<div className={cx(centred && "text-center")}>
<h1 className={cx(size, light && "text-white")}>{d.headline}</h1>
{d.subline && <p className={cx("mt-5 text-lg sm:text-xl", light ? "text-white/90" : "cc-muted", centred && "mx-auto max-w-2xl")}>{d.subline}</p>}
{d.button && <div className={cx("mt-8", light && "cc-on-dark")}><Button button={d.button} /></div>}
</div>
);
}
/** A muted loop over its still; phones and reduced motion get the still only (§3). */
function Video({ video, still, className }: { video: Image | null; still: Image | null; className?: string }) {
return (
<div className={cx("relative h-full w-full", className)}>
{still ? <img src={still.url} alt={still.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : <div className="absolute inset-0 bg-brand" />}
{video && (
<video className="cc-motion cc-img absolute inset-0 hidden sm:block" src={video.url} poster={still?.url} autoPlay muted loop playsInline aria-hidden="true" />
)}
</div>
);
}
function Fullbleed({ d, site, children }: { d: HeroData; site: SectionProps["site"]; children: React.ReactNode }) {
return (
<section className="cc-section-hero relative isolate flex min-h-[85vh] items-end overflow-hidden bg-gray-900 pb-16 pt-32 sm:pb-24">
<div className="absolute inset-0 -z-10">{children}</div>
{/* The scrim the headline's contrast is checked against, not the photo (§3). */}
<div className="absolute inset-0 -z-10 bg-gradient-to-t from-black/85 via-black/50 to-black/30" aria-hidden="true" />
<div className="cc-wrap">
<div className="max-w-3xl"><Words d={d} light /></div>
</div>
{site.snapshot.design.style.images === "duotone" && <div className="absolute inset-0 -z-10 bg-brand mix-blend-multiply" aria-hidden="true" />}
</section>
);
}
export function Hero({ section, site, template }: SectionProps) {
const d = section.data as unknown as HeroData;
const variant = section.variant ?? "photo";
const imgs = (d.images ?? []).map((id) => media(site, id));
const first = imgs[0] ?? null;
const video = media(site, d.videoId);
const services = (site.church?.serviceTimes ?? []).filter((s) => s.day === "sunday").map((s) => s.time);
if (variant === "text") {
if (template === "bold") {
return (
<section className="cc-section-hero bg-brand pb-20 pt-36 text-brand-on sm:pb-28">
<div className="cc-wrap"><div className="max-w-4xl"><Words d={d} light /></div></div>
</section>
);
}
return (
<section className={cx("cc-section-hero py-20 sm:py-28", template === "community" && "bg-brand-tint")}>
<div className={cx("cc-wrap", template === "heritage" && "text-center")}>
<div className={cx(template === "heritage" ? "mx-auto max-w-3xl" : "max-w-3xl")}>
<Words d={d} centred={template === "heritage"} size={template === "clean" ? "cc-h1 sm:text-7xl" : "cc-h1"} />
{template === "clean" && services.length > 0 && <p className="mt-8 border-l-4 border-accent pl-4 text-lg">Sundays {services.join(" & ")}</p>}
</div>
</div>
</section>
);
}
if (variant === "split") {
const words = <div className="flex flex-col justify-center p-8 sm:p-12"><Words d={d} /></div>;
if (template === "bold") {
return (
<section className="cc-section-hero grid bg-gray-950 text-white md:min-h-[80vh] md:grid-cols-2">
<div className="relative min-h-[50vh] md:order-2">{first && <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" />}</div>
<div className="flex flex-col justify-center px-6 pb-16 pt-32 sm:px-12"><Words d={d} light /></div>
</section>
);
}
return (
<section className={cx("cc-section-hero py-10 sm:py-16", template === "community" && "bg-brand-tint")}>
<div className="cc-wrap grid items-center gap-8 md:grid-cols-2">
{words}
<Img image={first} priority ratio="aspect-[4/3]" className={cx(template === "community" && "rounded-[2rem]")} />
</div>
</section>
);
}
if (variant === "collage") {
const three = [imgs[0] ?? null, imgs[1] ?? null, imgs[2] ?? null];
if (template === "bold") {
return (
<Fullbleed d={d} site={site}>
<div className="grid h-full grid-cols-3 gap-1">
{three.map((im, i) => <div key={i} className="relative">{im ? <img src={im.url} alt={im.alt} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
</div>
</Fullbleed>
);
}
if (template === "community") {
return (
<section className="cc-section-hero overflow-hidden bg-brand-tint py-14 sm:py-20">
<div className="cc-wrap grid items-center gap-12 md:grid-cols-2">
<Words d={d} />
<div className="relative mx-auto h-80 w-full max-w-md sm:h-96" aria-hidden={three.every((x) => !x) ? "true" : undefined}>
<div className="absolute -right-10 top-4 h-72 w-72 rounded-full bg-accent/30 blur-2xl" aria-hidden="true" />
<Img image={three[0]} priority ratio="" className="absolute left-0 top-0 h-56 w-56 rotate-[-4deg] rounded-[2rem] shadow-xl sm:h-64 sm:w-64" />
<Img image={three[1]} ratio="" className="absolute bottom-0 left-16 h-44 w-44 rotate-[3deg] rounded-[2rem] shadow-xl sm:h-52 sm:w-52" />
<Img image={three[2]} ratio="" className="absolute right-0 top-16 h-40 w-40 rotate-[6deg] rounded-full shadow-xl sm:h-48 sm:w-48" />
</div>
</div>
</section>
);
}
return (
<section className="cc-section-hero py-12 sm:py-16">
<div className="cc-wrap">
{template === "clean" && <div className="mb-10 max-w-3xl"><Words d={d} /></div>}
<div className="grid grid-cols-3 gap-3 sm:gap-4">
{three.map((im, i) => <Img key={i} image={im} priority={i === 0} ratio={template === "heritage" ? "aspect-[3/4]" : "aspect-square"} />)}
</div>
{template !== "clean" && <div className="mx-auto mt-10 max-w-3xl"><Words d={d} centred /></div>}
</div>
</section>
);
}
// photo (and video, drawn the same way with its loop).
const visual = variant === "video" ? <Video video={video} still={first} /> : first ? <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : null;
if (template === "bold") return <Fullbleed d={d} site={site}>{visual ?? <div className="h-full w-full bg-brand" />}</Fullbleed>;
if (template === "heritage") {
return (
<section className="cc-section-hero pb-14">
<div className="cc-wrap">
<div className="cc-frame relative aspect-[16/7]">{visual}</div>
<div className="mx-auto mt-12 max-w-3xl"><Words d={d} centred /></div>
</div>
</section>
);
}
if (template === "community") {
return (
<section className="cc-section-hero pb-12">
<div className="relative aspect-[16/9] max-h-[75vh] w-full overflow-hidden sm:aspect-[21/9]" style={{ clipPath: "ellipse(120% 100% at 50% 0%)" }}>{visual}</div>
<div className="cc-wrap -mt-24 relative sm:-mt-32">
<div className="max-w-2xl rounded-[2rem] bg-white p-8 shadow-xl sm:p-10"><Words d={d} /></div>
</div>
</section>
);
}
return (
<section className="cc-section-hero py-16 sm:py-24">
<div className="cc-wrap">
<div className="max-w-3xl"><Words d={d} /></div>
<div className="cc-frame relative mt-12 aspect-[16/9]">{visual}</div>
</div>
</section>
);
}
@@ -0,0 +1,478 @@
/**
* The homepage sections after the hero (WEBSITE-1.0-PLAN §3), each in its variants. Templates
* restyle the same markup through globals.css (cc-* classes) and the `t()` choices here.
*/
import { MessagePlayer } from "../MessagePlayer";
import { media, str, t } from "../load";
import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, SectionHeading, type ButtonData } from "../parts";
import type { SectionProps, SiteEvent } from "../types";
import { Hero } from "./Hero";
const Section = ({ children, className, id }: { children: React.ReactNode; className?: string; id?: string }) => (
<section id={id} className={cx("cc-section", className)}>{children}</section>
);
const tz = (p: SectionProps) => p.site.church?.timezone ?? "Africa/Johannesburg";
// ─── Service times and location: Panel · Inline strip · With map ─────────────────
function addressLines(p: SectionProps): string[] {
const a = p.site.church?.contact.address;
return a ? [a.line1, a.line2, [a.suburb, a.city].filter(Boolean).join(", ")].filter((x): x is string => !!x) : [];
}
function directions(p: SectionProps): string | null {
const a = p.site.church?.contact.address;
if (!a) return null;
return a.geo ? `https://www.openstreetmap.org/?mlat=${a.geo.lat}&mlon=${a.geo.lng}#map=17/${a.geo.lat}/${a.geo.lng}` : `https://www.openstreetmap.org/search?query=${encodeURIComponent([a.line1, a.suburb, a.city].filter(Boolean).join(", "))}`;
}
function Times({ p, className }: { p: SectionProps; className?: string }) {
const times = p.site.church?.serviceTimes ?? [];
if (!times.length) return <p className="cc-muted">Service times are coming soon.</p>;
return (
<ul className={cx("space-y-3", className)}>
{times.map((s, i) => (
<li key={i} className="flex flex-wrap items-baseline gap-x-3">
<span className="font-heading text-2xl font-semibold tabular-nums">{s.time}</span>
<span>{dayName(s.day)}{s.label && <> · {s.label}</>}</span>
{s.note && <span className="cc-muted w-full text-sm">{s.note}</span>}
</li>
))}
</ul>
);
}
function ServiceTimes(p: SectionProps) {
const d = p.section.data as { heading: string | null; note: string | null };
const lines = addressLines(p);
const dir = directions(p);
const heading = d.heading ?? "Service times";
if (p.section.variant === "strip") {
const sundays = (p.site.church?.serviceTimes ?? []).filter((s) => s.day === "sunday").map((s) => s.time);
return (
<section className={cx("cc-section cc-own-bg !py-6", t(p.template, { bold: "cc-dark bg-brand text-brand-on", clean: "border-y border-gray-200", heritage: "bg-brand-tint", community: "bg-brand-tint" }))}>
<div className="cc-wrap flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-lg"><strong className="font-heading">{heading}:</strong> {sundays.length ? `Sundays ${sundays.join(" & ")}` : "see below"}{lines[0] && <> · {lines.join(", ")}</>}</p>
{dir && <a href={dir} rel="noopener" className="cc-link shrink-0 whitespace-nowrap font-semibold underline underline-offset-4">Get directions</a>}
</div>
</section>
);
}
const panel = (
<div className={cx("p-8", t(p.template, { heritage: "border-4 border-double border-brand-text/40 text-center", bold: "bg-gray-950 text-white", community: "cc-card", clean: "border-l-4 border-accent" }))}>
<h2 className="cc-h2 mb-6">{heading}</h2>
<Times p={p} className={p.template === "heritage" ? "inline-block text-left" : ""} />
{d.note && <p className="cc-muted mt-6">{d.note}</p>}
{lines.length > 0 && (
<address className="mt-6 not-italic">
{lines.map((l) => <span key={l} className="block">{l}</span>)}
{dir && <a href={dir} rel="noopener" className="cc-link mt-2 inline-block font-semibold">Get directions</a>}
</address>
)}
</div>
);
if (p.section.variant === "map") {
const geo = p.site.church?.contact.address?.geo;
return (
<Section>
<div className="cc-wrap grid items-stretch gap-8 md:grid-cols-2">
{panel}
{geo ? (
<div className="cc-frame min-h-[18rem]">
{/* OpenStreetMap, loaded only when scrolled to (no Google, no cookies). */}
<iframe title="Map" loading="lazy" className="h-full min-h-[18rem] w-full border-0"
src={`https://www.openstreetmap.org/export/embed.html?bbox=${geo.lng - 0.006}%2C${geo.lat - 0.004}%2C${geo.lng + 0.006}%2C${geo.lat + 0.004}&layer=mapnik&marker=${geo.lat}%2C${geo.lng}`} />
</div>
) : <Img image={null} ratio="min-h-[18rem]" />}
</div>
</Section>
);
}
return <Section><div className="cc-wrap"><div className={cx(p.template === "heritage" ? "mx-auto max-w-xl" : "max-w-2xl")}>{panel}</div></div></Section>;
}
// ─── Welcome: Text · Image and text · With pastor's photo and quote ────────────────
function Welcome(p: SectionProps) {
const d = p.section.data as { heading: string | null; mission: string | null; body: string; imageId: string | null; pastor: { name: string; role: string | null; quote: string | null; photoId: string | null } | null };
const centred = p.template === "heritage";
const words = (
<div className={cx(centred && "text-center")}>
{d.mission && <p className="cc-eyebrow mb-4">{d.mission}</p>}
{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}
<Paragraphs text={d.body} />
</div>
);
if (p.section.variant === "pastor" && d.pastor) {
const photo = media(p.site, d.pastor.photoId);
return (
<Section>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]">
<figure className={cx(centred && "text-center")}>
<Img image={photo} ratio="aspect-[4/5]" className={cx(p.template === "community" && "rounded-[2rem]", centred && "mx-auto max-w-xs")} />
{d.pastor.quote && <blockquote className="font-heading mt-6 text-xl italic">“{d.pastor.quote}”</blockquote>}
<figcaption className="cc-muted mt-3">{d.pastor.name}{d.pastor.role && <>, {d.pastor.role}</>}</figcaption>
</figure>
{words}
</div>
</Section>
);
}
if (p.section.variant === "image-text") {
return (
<Section>
<div className={cx("grid items-center gap-10 md:grid-cols-2", p.template === "bold" ? "px-0 md:gap-0" : "cc-wrap")}>
<Img image={media(p.site, d.imageId)} ratio={p.template === "bold" ? "aspect-square md:aspect-auto md:h-full md:min-h-[28rem]" : "aspect-[4/3]"} className={cx(p.template === "community" && "rounded-[2rem]", p.template === "bold" && "rounded-none")} />
<div className={cx(p.template === "bold" && "px-6 py-10 sm:px-12")}>{words}</div>
</div>
</Section>
);
}
return <Section><div className="cc-wrap"><div className="cc-text">{words}</div></div></Section>;
}
// ─── Ministries: Cards · List · Alternating bands ───────────────────────────────
function Ministries(p: SectionProps) {
const d = p.section.data as { heading: string | null; intro: string | null };
const list = p.site.snapshot.ministries;
if (!list.length) return null;
const page = p.site.snapshot.pages.find((x) => x.kind === "ministries");
const href = (slug: string) => (page ? `${page.path}#${slug}` : `#${slug}`);
const head = <SectionHeading heading={d.heading ?? "Ministries"} intro={d.intro} centred={p.template === "heritage"} />;
if (p.section.variant === "bands") {
return (
<Section className="!pb-0">
<div className="cc-wrap">{head}</div>
<div className={cx(p.template === "bold" ? "" : "cc-wrap space-y-10")}>
{list.map((m, i) => (
<div key={m.slug} className={cx("grid items-center md:grid-cols-2", p.template === "bold" ? "" : "gap-8")}>
<Img image={m.image} ratio={p.template === "bold" ? "aspect-[4/3]" : "aspect-[16/10]"} className={cx(i % 2 === 1 && "md:order-2", p.template === "bold" && "rounded-none", p.template === "community" && "rounded-[2rem]")} />
<div className={cx(p.template === "bold" && "px-6 py-10 sm:px-12")}>
<h3 className="cc-h3 mb-2">{m.name}</h3>
{m.summary && <p className="cc-muted text-lg">{m.summary}</p>}
<a href={href(m.slug)} className="cc-link mt-4 inline-block font-semibold">Find out more</a>
</div>
</div>
))}
</div>
<div className="pb-[var(--cc-section-y)]" />
</Section>
);
}
if (p.section.variant === "list") {
return (
<Section>
<div className="cc-wrap">
{head}
<ul className={cx("divide-y", p.template === "heritage" ? "mx-auto max-w-2xl divide-brand-text/20" : "divide-gray-200")}>
{list.map((m) => (
<li key={m.slug} className="flex flex-col gap-1 py-5 sm:flex-row sm:items-baseline sm:justify-between">
<a href={href(m.slug)} className="cc-h3 no-underline hover:underline">{m.name}</a>
{m.summary && <span className="cc-muted sm:max-w-md sm:text-right">{m.summary}</span>}
</li>
))}
</ul>
</div>
</Section>
);
}
return (
<Section>
<div className="cc-wrap">
{head}
<ul className={cx("grid gap-6", list.length > 3 ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-3")}>
{list.map((m) => (
<li key={m.slug} className="cc-card flex flex-col">
<Img image={m.image} ratio="aspect-[4/3]" className="rounded-none" />
<div className="flex flex-1 flex-col p-5">
<h3 className="cc-h3">{m.name}</h3>
{m.summary && <p className={cx("mt-2 flex-1", p.template === "bold" ? "text-white/80" : "cc-muted")}>{m.summary}</p>}
<a href={href(m.slug)} className={cx("mt-4 font-semibold", p.template === "bold" ? "text-white underline" : "cc-link")}>Find out more<span className="sr-only"> about {m.name}</span></a>
</div>
</li>
))}
</ul>
</div>
</Section>
);
}
// ─── Team: Faces grid · List · Featured ─────────────────────────────────────────
function Team(p: SectionProps) {
const d = p.section.data as { heading: string | null; intro: string | null };
const people = p.site.snapshot.leaders;
if (!people.length) return null;
const head = <SectionHeading heading={d.heading ?? "Our team"} intro={d.intro} centred={p.template !== "clean"} />;
const face = (l: (typeof people)[number], big = false) => (
<figure key={l.name} className="text-center">
<Img image={l.photo} ratio={p.template === "bold" ? "aspect-[3/4]" : "aspect-square"}
className={cx(p.template === "heritage" || p.template === "community" ? "rounded-full" : "", big ? "mx-auto max-w-xs" : "mx-auto max-w-[12rem]")} />
<figcaption className="mt-4">
<span className={cx("block font-heading font-semibold", big ? "text-2xl" : "text-lg")}>{l.name}</span>
{l.role && <span className="cc-muted block">{l.role}</span>}
</figcaption>
</figure>
);
if (p.section.variant === "list") {
return (
<Section>
<div className="cc-wrap">
{head}
<ul className="mx-auto max-w-2xl divide-y divide-gray-200">
{people.map((l) => <li key={l.name} className="flex justify-between gap-4 py-4"><span className="font-semibold">{l.name}</span><span className="cc-muted">{l.role}</span></li>)}
</ul>
</div>
</Section>
);
}
if (p.section.variant === "featured") {
const [lead, ...rest] = people;
return (
<Section>
<div className="cc-wrap">
{head}
{face(lead!, true)}
{rest.length > 0 && <div className="mt-12 grid grid-cols-2 gap-8 sm:grid-cols-3">{rest.map((l) => face(l))}</div>}
</div>
</Section>
);
}
return <Section><div className="cc-wrap">{head}<div className="grid grid-cols-2 gap-8 sm:grid-cols-4">{people.map((l) => face(l))}</div></div></Section>;
}
// ─── Upcoming events: Cards · List · Calendar strip ─────────────────────────────
export function EventLine({ e, timeZone }: { e: SiteEvent; timeZone: string }) {
const when = e.allDay ? fmtDate(e.startsAt, timeZone, { weekday: "long", day: "numeric", month: "long" }) : `${fmtDate(e.startsAt, timeZone, { weekday: "long", day: "numeric", month: "long" })}, ${fmtTime(e.startsAt, timeZone)}`;
return (
<>
<time dateTime={e.startsAt} className="cc-muted block text-sm">{when}</time>
{e.location && <span className="cc-muted block text-sm">{e.location}</span>}
{e.registration && e.registration.status === "open" && <span className="cc-eyebrow mt-1 block text-xs">Register on our Events site</span>}
</>
);
}
function Events(p: SectionProps) {
const d = p.section.data as { heading: string | null; count: number };
const list = p.site.events.slice(0, d.count ?? 3);
const zone = tz(p);
const page = p.site.snapshot.pages.find((x) => x.kind === "events");
const head = <SectionHeading heading={d.heading ?? "Coming up"} centred={p.template === "heritage"} />;
const more = page && <p className={cx("mt-8", p.template === "heritage" && "text-center")}><a href={page.path} className="cc-link font-semibold">All events</a></p>;
if (!list.length) {
return <Section><div className="cc-wrap">{head}<p className="cc-muted">Nothing on the calendar just now. Check back soon.</p></div></Section>;
}
if (p.section.variant === "cards") {
return (
<Section>
<div className="cc-wrap">
{head}
<ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{list.map((e) => (
<li key={e.url + e.startsAt} className="cc-card flex flex-col">
<div className="relative">
<Img image={e.image} ratio="aspect-[16/10]" className="rounded-none" />
<DateBadge iso={e.startsAt} timeZone={zone} className="absolute left-4 top-4 shadow" />
</div>
<div className="flex flex-1 flex-col p-5">
<h3 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h3>
<div className="mt-2"><EventLine e={e} timeZone={zone} /></div>
</div>
</li>
))}
</ul>
{more}
</div>
</Section>
);
}
if (p.section.variant === "calendar") {
return (
<Section>
<div className="cc-wrap">
{head}
<ol className="flex snap-x gap-4 overflow-x-auto pb-4">
{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 text-brand-text">{fmtDate(e.startsAt, zone, { day: "numeric" })}</p>
<p className="cc-eyebrow">{fmtDate(e.startsAt, zone, { month: "long", weekday: "short" })}</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>
))}
</ol>
{more}
</div>
</Section>
);
}
return (
<Section>
<div className="cc-wrap">
{head}
<ul className={cx("divide-y divide-gray-200", p.template === "heritage" && "mx-auto max-w-2xl")}>
{list.map((e) => (
<li key={e.url + e.startsAt} className="flex gap-5 py-5">
<DateBadge iso={e.startsAt} timeZone={zone} />
<div><h3 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h3><EventLine e={e} timeZone={zone} /></div>
</li>
))}
</ul>
{more}
</div>
</Section>
);
}
// ─── Latest message: Large video · Card · Compact ───────────────────────────────
function LatestMessage(p: SectionProps) {
const d = p.section.data as { heading: string | null };
const m = p.site.messages[0];
if (!m) return null;
const zone = tz(p);
const page = p.site.snapshot.pages.find((x) => x.kind === "messages");
const meta = [m.speaker, m.passage, fmtDate(m.date, zone, { day: "numeric", month: "long", year: "numeric" })].filter(Boolean).join(" · ");
const head = <SectionHeading eyebrow={d.heading ?? "Latest message"} heading={null} centred={p.template === "heritage"} />;
const words = (
<div>
{m.series && <p className="cc-eyebrow mb-2">{m.series}</p>}
<h3 className="cc-h2">{m.title}</h3>
<p className="cc-muted mt-3">{meta}</p>
{page && <a href={page.path} className="cc-link mt-5 inline-block font-semibold">All messages</a>}
</div>
);
if (p.section.variant === "compact") {
return (
<Section>
<div className="cc-wrap">
<div className="flex flex-col gap-4 border-y border-gray-200 py-6 sm:flex-row sm:items-center sm:justify-between">
<div><p className="cc-eyebrow">{d.heading ?? "Latest message"}</p><p className="font-heading text-xl font-semibold">{m.title}</p><p className="cc-muted text-sm">{meta}</p></div>
<a href={m.url} rel="noopener" className="cc-btn">{m.source === "spotify" ? "Listen" : "Watch"}</a>
</div>
</div>
</Section>
);
}
if (p.section.variant === "video") {
return (
<Section className={cx(p.template === "bold" && "cc-own-bg cc-dark bg-gray-950 text-white")}>
<div className="cc-wrap">
{head}
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} />
<div className={cx("mt-8", p.template === "heritage" && "text-center")}>{words}</div>
</div>
</Section>
);
}
return (
<Section>
<div className="cc-wrap">
{head}
<div className="cc-card grid items-center gap-0 md:grid-cols-2">
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} className="rounded-none" />
<div className="p-8">{words}</div>
</div>
</div>
</Section>
);
}
// ─── Invitation: Banner · Centred · Image background ────────────────────────────
function Invitation(p: SectionProps) {
const d = p.section.data as { heading: string; text: string | null; button: ButtonData; imageId: string | null };
if (p.section.variant === "image") {
const img = media(p.site, d.imageId);
return (
<section className="cc-section cc-own-bg cc-dark relative isolate overflow-hidden bg-gray-900 text-white">
{img && <img src={img.url} alt="" className="cc-img absolute inset-0 -z-10" loading="lazy" />}
<div className="absolute inset-0 -z-10 bg-black/60" aria-hidden="true" />
<div className="cc-wrap py-10 text-center">
<h2 className="cc-h2">{d.heading}</h2>
{d.text && <p className="mx-auto mt-4 max-w-2xl text-lg text-white/90">{d.text}</p>}
<div className="cc-on-dark mt-8"><Button button={d.button} /></div>
</div>
</section>
);
}
if (p.section.variant === "banner") {
return (
<section className="cc-section cc-own-bg cc-dark bg-brand text-brand-on">
<div className="cc-wrap flex flex-col items-start gap-6 md:flex-row md:items-center md:justify-between">
<div><h2 className="cc-h2">{d.heading}</h2>{d.text && <p className="mt-3 max-w-2xl text-lg opacity-90">{d.text}</p>}</div>
<div className="cc-on-dark shrink-0"><Button button={d.button} /></div>
</div>
</section>
);
}
return (
<Section>
<div className="cc-wrap text-center">
<h2 className="cc-h2">{d.heading}</h2>
{d.text && <p className="cc-muted mx-auto mt-4 max-w-2xl text-lg">{d.text}</p>}
<div className="mt-8"><Button button={d.button} /></div>
</div>
</Section>
);
}
// ─── Blocks on the other pages ──────────────────────────────────────────────────
function TextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string };
return <Section><div className="cc-wrap"><div className="cc-text">{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /></div></div></Section>;
}
function ImageTextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData };
return (
<Section>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-2">
<Img image={media(p.site, d.imageId)} className={cx(p.template === "community" && "rounded-[2rem]")} />
<div>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /><div className="mt-6"><Button button={d.button} /></div></div>
</div>
</Section>
);
}
function QuoteBlock(p: SectionProps) {
const d = p.section.data as { quote: string; by: string | null };
return (
<Section>
<figure className="cc-wrap text-center">
<blockquote className="font-heading mx-auto max-w-3xl text-2xl leading-snug sm:text-3xl">“{d.quote}”</blockquote>
{str(d.by) && <figcaption className="cc-muted mt-4">{d.by}</figcaption>}
</figure>
</Section>
);
}
function CtaBlock(p: SectionProps) {
return <Invitation {...p} section={{ ...p.section, variant: "centred", data: { ...p.section.data, imageId: null } }} />;
}
const SECTIONS: Record<string, (p: SectionProps) => React.ReactNode> = {
hero: Hero, serviceTimes: ServiceTimes, welcome: Welcome, ministries: Ministries, team: Team, events: Events, latestMessage: LatestMessage, invitation: Invitation,
text: TextBlock, "image-text": ImageTextBlock, quote: QuoteBlock, cta: CtaBlock,
};
export function Sections({ site, sections }: { site: SectionProps["site"]; sections: SectionProps["section"][] }) {
const template = site.snapshot.design.template;
return (
<>
{sections.map((section, i) => {
const S = SECTIONS[section.type];
return S ? <S key={`${section.type}-${i}`} section={section} site={site} template={template} first={i === 0} /> : null;
})}
</>
);
}
+86
View File
@@ -0,0 +1,86 @@
/**
* What the backend's `/api/v1/site/content` answers (backend src/site/content.ts and snapshot.ts).
* Kept by hand: the frontend never imports the backend.
*/
import type { Church } from "@crosscode/contracts";
export type Template = "heritage" | "bold" | "community" | "clean";
export type Image = { url: string; alt: string; width: number | null; height: number | null };
export type Section = { type: string; variant: string | null; data: Record<string, unknown> };
export type Page = {
kind: string;
slug: string;
path: string;
title: string;
seoTitle: string | null;
description: string | null;
navLabel: string;
inNav: boolean;
image: Image | null;
sections: Section[];
};
export type Design = {
template: Template;
variants: Record<string, string>;
home: { section: string; hidden: boolean }[];
style: { sectionColour: "light" | "tinted" | "mixed"; spacing: "airy" | "compact"; buttons: "solid" | "outline" | "pill"; images: "natural" | "mono" | "duotone"; header: string };
};
export type Snapshot = {
v: 1;
design: Design;
pages: Page[];
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
media: Record<string, Image>;
};
export type Palette = { brand: string; brandDark: string; onBrand: string; brandText: string; brandTint: string; accent: string; onAccent: string; notes: string[] };
export type SiteEvent = {
title: string;
summary: string | null;
startsAt: string;
endsAt: string | null;
allDay: boolean;
location: string | null;
image: Image | null;
url: string;
from: "website" | "events" | "app";
registration: { status: string; priceFromCents: number | null } | null;
};
export type SiteMessage = {
slug: string;
title: string;
date: string;
speaker: string | null;
series: string | null;
passage: string | null;
source: "youtube" | "spotify";
embedUrl: string | null;
url: string;
thumbnail: string | null;
};
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string } };
export type ComingSoon = Common & { mode: "coming-soon"; template: Template; comingSoonText: string };
export type Published = Common & {
mode: "published";
version: number;
snapshot: Snapshot;
transparentHeader: Record<string, boolean>;
messages: SiteMessage[];
events: SiteEvent[];
};
export type SiteContent = ComingSoon | Published;
/** What every section component gets. */
export type SectionProps = { section: Section; site: Published; template: Template; first: boolean };
+9 -2
View File
@@ -1,12 +1,19 @@
/** @type {import('tailwindcss').Config} */
// The church's colours are CSS variables set per request in layout.tsx (from the church profile).
// The church's colours are CSS variables set per request in layout.tsx (from its profile, made
// safe by the backend's palette, WEBSITE-1.0-PLAN §3). Each is an "r g b" triple.
const v = (name) => `rgb(var(--${name}) / <alpha-value>)`;
module.exports = {
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
brand: { DEFAULT: v("brand"), dark: v("brand-dark"), text: v("brand-text"), tint: v("brand-tint"), on: v("on-brand") },
accent: { DEFAULT: v("accent"), on: v("on-accent") },
ink: "#111827",
},
borderRadius: { cc: "var(--cc-radius, 0.5rem)", "cc-sm": "var(--cc-radius-sm, 0.25rem)" },
fontFamily: { heading: "var(--cc-font-heading, inherit)" },
},
},
plugins: [],
+34
View File
@@ -0,0 +1,34 @@
import { defineConfig, devices } from "@playwright/test";
// The Website end to end (docs/WEBSITE-1.0-PLAN.md §13): the real backend on an in-memory database
// with the demo church (e2e/server.ts), and the Next.js pages. Run with `npx playwright test` in
// apps/website. Nothing needs a database.
export default defineConfig({
testDir: "./e2e",
testMatch: "**/*.spec.ts",
workers: 1,
fullyParallel: false,
timeout: 120_000,
expect: { timeout: 20_000 },
reporter: "list",
outputDir: "e2e/test-results",
use: { baseURL: "http://localhost:3310", trace: "retain-on-failure", navigationTimeout: 90_000 },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: [
{
command: "npx tsx e2e/server.ts",
url: "http://127.0.0.1:5310/api/health",
timeout: 120_000,
reuseExistingServer: false,
stdout: "pipe",
},
{
command: "npx next dev -p 3310",
cwd: "frontend",
url: "http://localhost:3310/robots.txt",
timeout: 180_000,
reuseExistingServer: false,
env: { WEBSITE_API_URL: "http://127.0.0.1:5310" },
},
],
});
+4 -2
View File
@@ -2,7 +2,7 @@
Phase **5** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§6, §9, §10, §11; decisions 19, 20, 40–47).
Written 2026-11-21. **All decisions confirmed by Joshua on 2026-11-21** (12 changed: a full
storage stops uploads). **Being built:** the skeleton is in `apps/website` (2026-11-25).
storage stops uploads). **Being built:** the skeleton, signing in, `website.sh`, and the four templates with the public site are in `apps/website` (2026-11-25).
**Updated 2026-11-24:** the Hub release is **2.21.0**, not 2.13.0 (the Hub reached 2.20.0 on
2026-11-23 with other work). The 8 font pairings in §3 ("Font pairings") were **confirmed by Joshua
@@ -456,7 +456,7 @@ preview and SEO warnings where they apply (ROADMAP §11).
Admin roles can require 2FA through Accounts (`acr_values=mfa`, ACCOUNTS-1.0-PLAN decision 8): on by
default for Owner and Admin.
**The first Owner** (built 2026-11-25, to confirm): whoever signs in through Accounts with the
**The first Owner** (confirmed by Joshua 2026-11-25, decision 17): whoever signs in through Accounts with the
church's admin email from the Hub (`HUB_ADMIN_EMAIL`, as Accounts' setup uses it), with that email
verified in Accounts, while the site has no Owner. Everyone else is added by an Owner or Admin. If
the last Owner's account is deleted, the same rule finds the next one.
@@ -586,6 +586,8 @@ Confirmed on 2026-11-25:
homepage order (Bold hides Team, Clean hides Ministries and Team) and style defaults; picking a
template only suggests the shared fonts and corners; a template switch moves untouched sections
and settings to the new defaults and keeps the church's own choices.
17. **The first Owner** (§10): whoever signs in through Accounts with the Hub's admin email
(`HUB_ADMIN_EMAIL`), verified in Accounts, while the site has no Owner.
## Still open
+1
View File
@@ -387,6 +387,7 @@
"version": "0.1.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"next": "^16.4.6",
"react": "^19.3.1",
+3 -3
View File
@@ -17,10 +17,10 @@ website_expected_version() {
node -p 'require(process.argv[1]).version' "$(website_app "$1")/backend/package.json"
}
# The shared packages the Website is built with (contracts, auth-client for signing in, ui for its pages).
# The shared packages the Website is built with (contracts, auth-client for signing in, ui and seo for its pages).
website_shared_packages() {
local p
for p in packages/contracts packages/ui packages/auth-client; do
for p in packages/contracts packages/ui packages/auth-client packages/seo; do
[ -f "$1/$p/package.json" ] && printf '%s\n' "$p"
done
}
@@ -54,7 +54,7 @@ website_migrate() {
website_build() {
local p
for p in packages/contracts packages/auth-client; do
for p in packages/contracts packages/auth-client packages/seo; do
[ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1
done
run_as "$2" "$(website_app "$1")/backend" npm run build &&
+4 -4
View File
@@ -19,7 +19,7 @@ setup() {
checkout() {
local dir="$TMP/$1" p
for p in contracts ui auth-client; do
for p in contracts ui auth-client seo; do
mkdir -p "$dir/packages/$p"
echo "{\"name\":\"@crosscode/$p\"}" > "$dir/packages/$p/package.json"
done
@@ -39,13 +39,13 @@ checkout() {
is_supported_product website
}
@test "contracts, ui and auth-client are installed; contracts and auth-client built before the Website" {
@test "contracts, ui, auth-client and seo are installed; contracts, auth-client and seo built before the Website" {
checkout new
website_install_deps "$TMP/new" hope
grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund --include-workspace-root -w packages/contracts -w packages/ui -w packages/auth-client -w apps/website/backend -w apps/website/frontend' "$CALLS"
grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund --include-workspace-root -w packages/contracts -w packages/ui -w packages/auth-client -w packages/seo -w apps/website/backend -w apps/website/frontend' "$CALLS"
: > "$CALLS"
website_build "$TMP/new" hope
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/auth-client new/apps/website/backend new/apps/website/frontend " ]
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/auth-client new/packages/seo new/apps/website/backend new/apps/website/frontend " ]
}
@test "ports default to 5300 / 3300, else church.env's" {