Merge branch 'fix/church-from-accounts'

This commit is contained in:
2026-12-01 00:54:27 +02:00
42 changed files with 949 additions and 127 deletions
+17
View File
@@ -2,6 +2,23 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@3.9.0 + website@1.9.0 + accounts@1.10.0 - 2026-12-01
The church's details from Accounts on every site, section backgrounds, one colour picker (Joshua,
2026-12-01). No migrations; no contracts change.
- **Events 3.9.0:** the Accounts profile's name, logo, icon, colours and contact details win over
Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs), and Settings
shows them read-only with a link to Accounts. The logo from Accounts is copied for PDFs, and SVG logos
are drawn in PDFs (`svg-to-pdfkit`, new dependency). Fixes Events keeping its old church after a demo scenario load.
- **Website 1.9.0:** a background for each homepage section in the church's colours; "More info"
instead of "Register" for events without registration; the shared colour field in Church
details.
- **Accounts 1.10.0:** the shared colour field in Church profile.
- **`@crosscode/ui` 0.4.0:** `ColourField` and `isHexColour`.
- Checked: Events backend tests (828), Website backend tests (149), typecheck and lint of every
changed app.
## contracts@1.24.0 - 2026-11-30 ## contracts@1.24.0 - 2026-11-30
Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive. Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive.
+12
View File
@@ -1,5 +1,17 @@
# Changelog — Accounts # Changelog — Accounts
## [1.10.0] - 2026-12-01
No migration, no new .env variables, no backend change. Needs `@crosscode/ui` 0.4.0 (built with
Accounts).
### Changed
- **Admin → Church profile:** the main and accent colours use the shared colour field
(`ColourField`, `@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, a preview, and a
message when the code isn't a colour, as Cross Events' Branding settings. Cross Events 3.9.0
now takes the church's name, logo, colours and contact details from this profile too.
## [1.9.0] - 2026-11-30 ## [1.9.0] - 2026-11-30
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
+7
View File
@@ -3,6 +3,13 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged). WHATS-NEW.md; a section shows once its version is tagged).
## 1.10.0
- **An easier colour picker** in **Church profile**: pick your main and accent colours, or type or
paste their codes (like #1f4e79), and see them straight away.
- Your Events site (from version 3.9.0) now uses the name, logo, colours and contact details in
your church profile here, as your website does, so you change them in one place.
## 1.9.0 ## 1.9.0
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no - **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.9.0", "version": "1.10.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true, "private": true,
"type": "module", "type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.9.0", "version": "1.10.0",
"private": true, "private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": { "scripts": {
@@ -6,7 +6,7 @@ import {
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play, AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users, RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
} from "lucide-react"; } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; import { Button, Checkbox, ColourField, Field, Notice } from "@crosscode/ui";
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell"; import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText"; import { NoticeText } from "@/components/NoticeText";
import { Card, Heading } from "@/components/Panel"; import { Card, Heading } from "@/components/Panel";
@@ -325,6 +325,8 @@ type ChurchData = { name: string; shortName: string | null; branding: { logoUrl:
function Church({ flash }: { flash: Flash }) { function Church({ flash }: { flash: Flash }) {
const [c, setC] = useState<ChurchData | null>(null); const [c, setC] = useState<ChurchData | null>(null);
const [fields, setFields] = useState<Record<string, string>>({}); const [fields, setFields] = useState<Record<string, string>>({});
// The two colours as typed (ColourField is controlled); the saved ones until changed.
const [colours, setColours] = useState<{ primary?: string; accent?: string }>({});
useExternalEffect(() => { useExternalEffect(() => {
let alive = true; let alive = true;
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); }); call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
@@ -344,14 +346,16 @@ function Church({ flash }: { flash: Flash }) {
branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } }, branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } },
contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) }, contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) },
}); });
if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); } if (r.ok) { setC(r.data); setFields({}); setColours({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
}}> }}>
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} /> <Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} /> <Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} /> <Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
<div className="grid grid-cols-2 gap-4"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} /> <ColourField label="Main colour" name="primary" value={colours.primary ?? c.branding.colours.primary} onChange={(primary) => setColours((x) => ({ ...x, primary }))}
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} /> hint="Buttons, links and headings on every site." error={fields["branding.colours.primary"]} />
<ColourField label="Accent colour" name="accent" value={colours.accent ?? c.branding.colours.accent ?? "#f2a900"} onChange={(accent) => setColours((x) => ({ ...x, accent }))}
hint="Highlights and touches beside the main colour." error={fields["branding.colours.accent"]} />
</div> </div>
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} /> <Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} /> <Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
+35
View File
@@ -5,6 +5,41 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/). and this project follows [Semantic Versioning](https://semver.org/).
## [3.9.0] - 2026-12-01
No migration, no new settings or environment variables. One new dependency: `svg-to-pdfkit`
0.1.8 (MIT, pure JavaScript; draws SVG logos in PDFs). Works with any Accounts; nothing changes on
a site without Accounts.
### Fixed
- **The church's details come from Accounts.** The church profile set only the fonts, corners and
footer, so after a change in Accounts (or a demo scenario loaded on a new church) Events kept its
own old name, logo and colours while the Website showed the new ones. Now, while Accounts is
connected, the profile's name, logo, icon, main and accent colours, email, phone and address win
over `org_name`, `logo_url`, `favicon_url`, `primary_color`, `accent_color`, `org_email`,
`org_phone` and `org_address` everywhere: the public settings (`GET /api/v2/settings`), and
everything that reads the settings cache (emails, WhatsApp, PDFs, 2FA labels). Only what the
profile has: no icon or accent there keeps this site's own. `org_tagline` and `secondary_color`
stay this site's (`src/accounts/church.ts` `churchSettings`, `utils/settingsCache.js`
`setAccountsOverrides`). `church.changed` fetches the profile straight away; disconnecting
Accounts brings the site's own back. The look sent to Accounts on a move stays this site's own
(`getStoredSetting`).
- **PDFs with the church's logo from Accounts.** Tickets, invoices, receipts, certificates and
privacy exports could only draw a logo uploaded here. The logo from Accounts is copied into
`uploads/accounts` (once per address, when the profile arrives or the first PDF needs it; old
copies removed; 2 MB at most; `utils/logoCopy.js`). PNG and JPEG are drawn as pictures and SVG
(the demo churches' logos, and an SVG uploaded here) as shapes with `svg-to-pdfkit`
(`drawLogo`); an SVG never opens a file or address it names. WebP and GIF show the name only.
- A logo address on another `localhost` port (Accounts in development) is no longer rewritten to
the API's address; only this site's own uploads are (`resolveToApiOrigin`).
### Changed
- **Settings → Organisation and Branding** show the fields Accounts sets read-only, with a link to
the church profile in Accounts, and never send them back (`GET /api/v2/settings/all` adds
`accounts_managed`, the keys Accounts sets, with Accounts' values).
## [3.8.0] - 2026-11-30 ## [3.8.0] - 2026-11-30
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
+12
View File
@@ -12,6 +12,18 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
--> -->
## 3.9.0
- **Your church's name, logo, colours and contact details now come from your church profile in
Accounts**, as they do on your website. Change them once in Accounts and your Events site shows
the change within moments, in its pages, emails and WhatsApp messages too. Before, Events kept
the details it had been given when it was set up.
- In **Site settings → Organisation and Branding**, those details are shown but can't be changed
there any more; a link takes you to your church profile in Accounts. Your tagline and secondary
colour are still set in Events.
- **Tickets, invoices and certificates show your church's logo from Accounts** (PNG, JPEG or
SVG).
## 3.8.0 ## 3.8.0
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number - **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/events-backend", "name": "@crosscode/events-backend",
"version": "3.8.0", "version": "3.9.0",
"description": "Event Management System Backend", "description": "Event Management System Backend",
"main": "src/index.js", "main": "src/index.js",
"scripts": { "scripts": {
@@ -45,6 +45,7 @@
"pg-boss": "^11.1.2", "pg-boss": "^11.1.2",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"raw-body": "^3.0.0", "raw-body": "^3.0.0",
"svg-to-pdfkit": "0.1.8",
"swagger-ui-dist": "^5.34.0", "swagger-ui-dist": "^5.34.0",
"tsx": "^4.23.15", "tsx": "^4.23.15",
"typescript": "^5.9.3", "typescript": "^5.9.3",
+55 -6
View File
@@ -1,8 +1,11 @@
/** /**
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand * The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9). Accounts owns
* style (fonts and corners) and what the shared footer shows (service times, address, contact, * it and serves it publicly at `GET /api/church/v1`; this keeps a copy in memory for the public
* social, the church's other sites). Accounts owns it and serves it publicly at * pages (`GET /api/v2/church`: the brand style and the shared footer).
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`). *
* The church's own details in it (name, logo, icon, colours, contact details) also win over
* this site's settings of the same name (`churchSettings`, through utils/settingsCache), so a change
* in Accounts (or a new demo church) shows here as it does on the church's Website.
* *
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed` * Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last * (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
@@ -12,6 +15,11 @@
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts'; import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import { accountsLink } from './client'; import { accountsLink } from './client';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { setAccountsOverrides } = require('../utils/settingsCache') as { setAccountsOverrides(map: Record<string, string>): void };
const { pdfLogoPath } = require('../utils/logoCopy') as { pdfLogoPath(url: string): Promise<string | null> };
/* eslint-enable @typescript-eslint/no-require-imports */
const FRESH_MS = 10 * 60e3; const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3; const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000; const TIMEOUT_MS = 5000;
@@ -20,6 +28,28 @@ type Cached = { url: string; church: Church | null; at: number; ok: boolean };
let cached: Cached | null = null; let cached: Cached | null = null;
let pending: Promise<Church | null> | null = null; let pending: Promise<Church | null> | null = null;
/**
* This site's settings that the church profile sets, with its values. Only what the profile has:
* a church without an icon keeps this site's favicon, without an accent its accent colour.
* `secondary_color` and `org_tagline` aren't in the profile, so they stay this site's own.
*/
export function churchSettings(church: Church | null): Record<string, string> {
if (!church) return {};
const a = church.contact.address;
const address = a ? [a.line1, a.line2, a.suburb, a.city, a.province, a.postalCode].filter((x) => x && x.trim()).join(', ') : null;
const out: Record<string, string | null> = {
org_name: church.name,
logo_url: church.branding.logoUrl,
favicon_url: church.branding.iconUrl,
primary_color: church.branding.colours.primary,
accent_color: church.branding.colours.accent,
org_email: church.contact.email,
org_phone: church.contact.phone,
org_address: address,
};
return Object.fromEntries(Object.entries(out).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1] !== ''));
}
async function fetchProfile(accountsUrl: string): Promise<Church> { 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) }); 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}`); if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
@@ -36,7 +66,12 @@ export async function churchProfile(): Promise<Church | null> {
} catch { } catch {
return cached?.church ?? null; return cached?.church ?? null;
} }
if (!link) return null; if (!link) {
// Disconnected from Accounts: this site's own settings again.
if (cached) cached = null;
setAccountsOverrides({});
return null;
}
const url = link.url; const url = link.url;
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church; if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
if (!pending) { if (!pending) {
@@ -44,10 +79,14 @@ export async function churchProfile(): Promise<Church | null> {
pending = fetchProfile(url) pending = fetchProfile(url)
.then((church) => { .then((church) => {
cached = { url, church, at: Date.now(), ok: true }; cached = { url, church, at: Date.now(), ok: true };
setAccountsOverrides(churchSettings(church));
// A copy of the logo for PDFs, made now rather than while a ticket is being sent.
if (church.branding.logoUrl) pdfLogoPath(church.branding.logoUrl).catch(() => {});
return church; return church;
}, (e: Error) => { }, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message); console.warn('[church] profile not fetched from Accounts:', e.message);
cached = { url, church: last, at: Date.now(), ok: false }; cached = { url, church: last, at: Date.now(), ok: false };
setAccountsOverrides(churchSettings(last));
return last; return last;
}) })
.finally(() => { pending = null; }); .finally(() => { pending = null; });
@@ -55,13 +94,23 @@ export async function churchProfile(): Promise<Church | null> {
return pending; return pending;
} }
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */ /** This site's settings the church profile sets right now (fetching it when it's due). Never throws. */
export async function churchSettingsNow(): Promise<Record<string, string>> {
return churchSettings(await churchProfile());
}
/**
* `church.changed`: fetched again straight away, so emails and pages that read the settings
* without waiting get the new details within moments (the last copy is used meanwhile).
*/
export function churchChanged(): void { export function churchChanged(): void {
if (cached) cached = { ...cached, at: 0 }; if (cached) cached = { ...cached, at: 0 };
churchProfile().catch(() => {});
} }
/** Tests: start with nothing. */ /** Tests: start with nothing. */
export function resetChurchProfile(): void { export function resetChurchProfile(): void {
cached = null; cached = null;
pending = null; pending = null;
setAccountsOverrides({});
} }
+2 -1
View File
@@ -7,7 +7,8 @@ import type { ChurchLook } from '@crosscode/contracts';
import { siteUrl } from '../feed/context'; import { siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ /* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> }; // This site's own values: they fill what Accounts doesn't have, so never Accounts' own (settingsCache).
const { getStoredSetting: getSetting } = require('../utils/settingsCache') as { getStoredSetting(k: string, f?: string): Promise<string> };
/* eslint-enable @typescript-eslint/no-require-imports */ /* eslint-enable @typescript-eslint/no-require-imports */
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null); const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
@@ -41,11 +41,22 @@ const PUBLIC_KEYS = [
// @desc Get public app settings // @desc Get public app settings
// @route GET /api/settings // @route GET /api/settings
// @access Public // @access Public
// The church's own details from its Accounts profile (name, logo, colours, contact): they win over
// this site's settings of the same name while Accounts is connected (src/accounts/church.ts).
async function fromAccounts() {
try {
return await require('../accounts/church').churchSettingsNow();
} catch {
return {};
}
}
const getSettings = async (req, res) => { const getSettings = async (req, res) => {
try { try {
const rows = await prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }); const [rows, accounts] = await Promise.all([prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }), fromAccounts()]);
const settings = {}; const settings = {};
for (const r of rows) settings[r.key] = r.value; for (const r of rows) settings[r.key] = r.value;
for (const [k, v] of Object.entries(accounts)) if (PUBLIC_KEYS.includes(k)) settings[k] = v;
res.json(settings); res.json(settings);
} catch (e) { } catch (e) {
res.status(500).json({ message: safeErrorMessage(e) }); res.status(500).json({ message: safeErrorMessage(e) });
@@ -79,6 +90,11 @@ const getAllSettings = async (req, res) => {
settings[r.key] = r.value; settings[r.key] = r.value;
} }
} }
// What the site uses for the keys Accounts sets, and which they are, so Settings shows them
// read-only with a link to change them in Accounts.
const accounts = await fromAccounts();
Object.assign(settings, accounts);
settings.accounts_managed = Object.keys(accounts).join(',');
res.json(settings); res.json(settings);
} catch (e) { } catch (e) {
res.status(500).json({ message: safeErrorMessage(e) }); res.status(500).json({ message: safeErrorMessage(e) });
@@ -96,7 +112,7 @@ const updateSettings = async (req, res) => {
} }
const ops = Object.entries(updates) const ops = Object.entries(updates)
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k)) .filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k) && k !== 'accounts_managed')
.map(([key, value]) => { .map(([key, value]) => {
let storedValue = String(value); let storedValue = String(value);
@@ -16,6 +16,7 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const PDFDocument = require('pdfkit'); const PDFDocument = require('pdfkit');
const QRCode = require('qrcode'); const QRCode = require('qrcode');
const { drawLogo } = require('./logoCopy');
const prisma = require('../config/db'); const prisma = require('../config/db');
const { activeSessions, completionMet, normalizeCertificateConfig, attendanceBySession, groupTickets, TIMEZONE } = require('./sessions'); const { activeSessions, completionMet, normalizeCertificateConfig, attendanceBySession, groupTickets, TIMEZONE } = require('./sessions');
@@ -189,7 +190,7 @@ function drawTemplate(doc, template, ctx) {
doc.rect(0, 0, 28, H).fill(color); doc.rect(0, 0, 28, H).fill(color);
doc.rect(28, 0, 6, H).fill(lighten(color, 0.6)); doc.rect(28, 0, 6, H).fill(lighten(color, 0.6));
const x = 90; const x = 90;
safeImage(doc, logo, x, 70, { fit: [120, 50] }); drawLogo(doc, logo, x, 70, { fit: [120, 50] });
doc.font('Helvetica').fontSize(11).fillColor(color).text(branding.name.toUpperCase(), x, 150, { characterSpacing: 2 }); doc.font('Helvetica').fontSize(11).fillColor(color).text(branding.name.toUpperCase(), x, 150, { characterSpacing: 2 });
doc.font('Helvetica-Bold').fontSize(36).fillColor('#0f172a').text(title, x, 175, { width: W - x - 80 }); doc.font('Helvetica-Bold').fontSize(36).fillColor('#0f172a').text(title, x, 175, { width: W - x - 80 });
doc.font('Helvetica').fontSize(13).fillColor('#64748b').text('Presented to', x, 260); doc.font('Helvetica').fontSize(13).fillColor('#64748b').text('Presented to', x, 260);
@@ -202,7 +203,7 @@ function drawTemplate(doc, template, ctx) {
if (template === 'church') { if (template === 'church') {
doc.rect(0, 0, W, H).fill(lighten(color, 0.94)); doc.rect(0, 0, W, H).fill(lighten(color, 0.94));
doc.rect(30, 30, W - 60, H - 60).lineWidth(1).strokeColor(lighten(color, 0.4)).stroke(); doc.rect(30, 30, W - 60, H - 60).lineWidth(1).strokeColor(lighten(color, 0.4)).stroke();
const hasLogo = safeImage(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' }); const hasLogo = drawLogo(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' });
const top = hasLogo ? 150 : 115; const top = hasLogo ? 150 : 115;
doc.font('Times-Italic').fontSize(14).fillColor(color).text(branding.name, 0, top, { width: W, align: 'center' }); doc.font('Times-Italic').fontSize(14).fillColor(color).text(branding.name, 0, top, { width: W, align: 'center' });
doc.font('Times-Bold').fontSize(34).fillColor('#1e293b').text(title, 60, top + 26, { width: W - 120, align: 'center' }); doc.font('Times-Bold').fontSize(34).fillColor('#1e293b').text(title, 60, top + 26, { width: W - 120, align: 'center' });
@@ -228,7 +229,7 @@ function drawTemplate(doc, template, ctx) {
const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260); const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260);
doc.circle(x, y, 3 + rnd() * 5).fill(bright[i % bright.length]); doc.circle(x, y, 3 + rnd() * 5).fill(bright[i % bright.length]);
} }
safeImage(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' }); drawLogo(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' });
doc.font('Helvetica-Bold').fontSize(38).fillColor(color).text(title, 100, 165, { width: W - 200, align: 'center' }); doc.font('Helvetica-Bold').fontSize(38).fillColor(color).text(title, 100, 165, { width: W - 200, align: 'center' });
doc.font('Helvetica-Bold').fontSize(15).fillColor('#f59e0b').text('Well done,', 0, 230, { width: W, align: 'center' }); doc.font('Helvetica-Bold').fontSize(15).fillColor('#f59e0b').text('Well done,', 0, 230, { width: W, align: 'center' });
doc.font('Helvetica-Bold').fontSize(36).fillColor('#1e293b').text(cert.name, 100, 250, { width: W - 200, align: 'center' }); doc.font('Helvetica-Bold').fontSize(36).fillColor('#1e293b').text(cert.name, 100, 250, { width: W - 200, align: 'center' });
@@ -244,7 +245,7 @@ function drawTemplate(doc, template, ctx) {
for (const [cx, cy] of [[34, 34], [W - 34, 34], [34, H - 34], [W - 34, H - 34]]) { for (const [cx, cy] of [[34, 34], [W - 34, 34], [34, H - 34], [W - 34, H - 34]]) {
doc.circle(cx, cy, 6).fill(color); doc.circle(cx, cy, 6).fill(color);
} }
safeImage(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' }); drawLogo(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' });
doc.font('Times-Bold').fontSize(38).fillColor('#1e293b').text(title.toUpperCase(), 60, 150, { width: W - 120, align: 'center', characterSpacing: 1.5 }); doc.font('Times-Bold').fontSize(38).fillColor('#1e293b').text(title.toUpperCase(), 60, 150, { width: W - 120, align: 'center', characterSpacing: 1.5 });
doc.font('Times-Italic').fontSize(14).fillColor('#64748b').text('This certificate is proudly presented to', 0, 212, { width: W, align: 'center' }); doc.font('Times-Italic').fontSize(14).fillColor('#64748b').text('This certificate is proudly presented to', 0, 212, { width: W, align: 'center' });
doc.font('Times-BoldItalic').fontSize(34).fillColor(color).text(cert.name, 60, 236, { width: W - 120, align: 'center' }); doc.font('Times-BoldItalic').fontSize(34).fillColor(color).text(cert.name, 60, 236, { width: W - 120, align: 'center' });
+137
View File
@@ -0,0 +1,137 @@
// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file
// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an
// address on another site, so a copy is kept in uploads/accounts (one per address, made when the
// profile arrives or the first PDF needs it; older copies are removed).
//
// PNG and JPEG are drawn as pictures; SVG (the demo churches' logos, and many churches') is drawn
// as shapes with svg-to-pdfkit (`drawLogo`). Anything else (WebP, GIF) isn't copied, and the PDFs
// show the church's name without a logo.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SVGtoPDF = require('svg-to-pdfkit');
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
const MAX_BYTES = 2 * 1024 * 1024;
const TIMEOUT_MS = 5000;
const EXT = { png: 'png', jpeg: 'jpg', svg: 'svg' };
/** PNG, JPEG or SVG by the file's own bytes (never by what a server says it is), else null. */
function logoKind(buf) {
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
const head = buf.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();
if (head.startsWith('<') && /<svg[\s>]/i.test(head)) return 'svg';
return null;
}
const nameFor = (url) => `logo-${crypto.createHash('sha256').update(url).digest('hex').slice(0, 16)}`;
/** An outside address the site may fetch the logo from: https, or http while developing. */
function fetchable(url) {
try {
const u = new URL(url);
return u.protocol === 'https:' || (u.protocol === 'http:' && process.env.NODE_ENV !== 'production');
} catch {
return false;
}
}
function existingCopy(url) {
const base = nameFor(url);
for (const ext of Object.values(EXT)) {
const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`);
if (fs.existsSync(p)) return p;
}
return null;
}
// Addresses tried lately that gave no usable logo: not fetched again for 10 minutes.
const misses = new Map();
const MISS_MS = 10 * 60e3;
const pending = new Map();
async function download(url) {
const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' });
if (!res.ok) throw new Error(`answered ${res.status}`);
if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB');
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB');
const kind = logoKind(buf);
if (!kind) return null; // WebP, GIF…: not drawable in a PDF
const dir = uploadsDir('accounts');
const base = nameFor(url);
const file = path.join(dir, `${base}.${EXT[kind]}`);
fs.writeFileSync(file, buf);
// The church changed its logo: the copies of the old ones go.
for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true });
return file;
}
/**
* The logo as a file a PDF can draw (`drawLogo`), or null. `logoUrl` is the logo_url setting: a
* path on this site (/uploads/…) or the church's logo address from Accounts. Never throws.
*/
async function pdfLogoPath(logoUrl) {
const url = String(logoUrl || '').trim();
if (!url) return null;
if (!/^https?:\/\//i.test(url)) {
const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, ''));
try {
return fs.existsSync(p) && logoKind(fs.readFileSync(p)) ? p : null;
} catch {
return null;
}
}
if (!fetchable(url)) return null;
const have = existingCopy(url);
if (have) return have;
const missed = misses.get(url);
if (missed && Date.now() - missed < MISS_MS) return null;
if (!pending.has(url)) {
pending.set(url, download(url)
.catch((e) => {
console.warn(`[logo] the church's logo couldn't be copied for PDFs: ${url} ${e.message}`);
return null;
})
.then((file) => {
if (!file) misses.set(url, Date.now());
return file;
})
.finally(() => pending.delete(url)));
}
return pending.get(url);
}
/**
* Draws the logo `file` (from pdfLogoPath) at x, y within `fit` [w, h], as doc.image does; centred
* in that box with `align: 'center'`. True when drawn. Never throws.
*/
function drawLogo(doc, file, x, y, { fit, align } = {}) {
if (!file) return false;
try {
if (file.toLowerCase().endsWith('.svg')) {
const [width, height] = fit || [100, 50];
SVGtoPDF(doc, fs.readFileSync(file, 'utf8'), x, y, {
width,
height,
preserveAspectRatio: align === 'center' ? 'xMidYMid meet' : 'xMinYMid meet',
// Only pictures inside the SVG itself: never a file or address it names.
imageCallback: (link) => (/^data:image\/(png|jpe?g);base64,/i.test(String(link).trim()) ? String(link).replace(/\s+/g, '') : ''),
warningCallback: () => {},
});
} else {
doc.image(file, x, y, { fit, ...(align ? { align } : {}) });
}
return true;
} catch {
return false;
}
}
/** Tests: forget the addresses that gave nothing. */
function resetLogoCopies() {
misses.clear();
}
module.exports = { pdfLogoPath, drawLogo, resetLogoCopies, logoKind };
+4 -7
View File
@@ -55,11 +55,8 @@ async function getBranding() {
getSetting('logo_url', ''), getSetting('logo_url', ''),
]); ]);
const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, ''); const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
let logoPath = null; // An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js).
if (logoUrl) { const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl);
const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, ''));
if (fs.existsSync(p)) logoPath = p;
}
return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath }; return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath };
} }
@@ -196,7 +193,7 @@ async function generateReceiptPdf(payment) {
const bannerH = 150; const bannerH = 150;
doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor); doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor);
if (org.logoPath) { if (org.logoPath) {
try { doc.image(org.logoPath, marginX, 28, { fit: [36, 36] }); } catch {} require('./logoCopy').drawLogo(doc, org.logoPath, marginX, 28, { fit: [36, 36] });
} }
doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(13).text(org.name, marginX + (org.logoPath ? 46 : 0), 38, { width: 260 }); doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(13).text(org.name, marginX + (org.logoPath ? 46 : 0), 38, { width: 260 });
doc.font('Helvetica-Bold').fontSize(26).text('Payment Receipt', marginX, 68, { width: 320 }); doc.font('Helvetica-Bold').fontSize(26).text('Payment Receipt', marginX, 68, { width: 320 });
@@ -301,7 +298,7 @@ async function generateInvoicePdf(registration, { paymentUrl = null, totalDue =
doc.rect(0, 0, sidebarW, pageHeight).fill('#111827'); doc.rect(0, 0, sidebarW, pageHeight).fill('#111827');
let sy = 40; let sy = 40;
if (org.logoPath) { if (org.logoPath) {
try { doc.image(org.logoPath, 28, sy, { fit: [32, 32] }); sy += 0; } catch {} require('./logoCopy').drawLogo(doc, org.logoPath, 28, sy, { fit: [32, 32] });
} }
doc.font('Helvetica-Bold').fontSize(12).fillColor('#ffffff').text(org.name, org.logoPath ? 68 : 28, sy + 8, { width: sidebarW - (org.logoPath ? 96 : 56) }); doc.font('Helvetica-Bold').fontSize(12).fillColor('#ffffff').text(org.name, org.logoPath ? 68 : 28, sy + 8, { width: sidebarW - (org.logoPath ? 96 : 56) });
sy += 60; sy += 60;
+42 -1
View File
@@ -17,9 +17,37 @@ let _cache = {};
let _lastFetch = 0; let _lastFetch = 0;
const TTL_MS = 60 * 1000; const TTL_MS = 60 * 1000;
/**
* The church's own details from its Accounts profile (src/accounts/church.ts): name, logo, icon,
* colours and contact details. Accounts owns them, so while it's connected they win over this
* site's own settings everywhere (pages, emails, PDFs). Empty without Accounts.
*/
let _fromAccounts = {};
/** Set by src/accounts/church.ts whenever it has (or loses) the church profile. */
function setAccountsOverrides(map) {
_fromAccounts = { ...(map || {}) };
}
/** The keys Accounts sets right now, with their values. */
function accountsOverrides() {
return { ..._fromAccounts };
}
/** The church profile is kept fresh as the settings are (it caches itself for 10 minutes). */
function refreshChurchProfile() {
try {
const p = require('../accounts/church').churchProfile();
if (p && typeof p.catch === 'function') p.catch(() => {});
} catch {
// No Accounts code in this context (some tests): the site's own settings stand.
}
}
async function refreshIfStale() { async function refreshIfStale() {
const now = Date.now(); const now = Date.now();
if (now - _lastFetch < TTL_MS && _lastFetch > 0) return; if (now - _lastFetch < TTL_MS && _lastFetch > 0) return;
refreshChurchProfile();
try { try {
const rows = await prisma.appSetting.findMany(); const rows = await prisma.appSetting.findMany();
const fresh = {}; const fresh = {};
@@ -38,6 +66,13 @@ async function refreshIfStale() {
* @returns {string} * @returns {string}
*/ */
function _getSync(key, envFallback = '') { function _getSync(key, envFallback = '') {
const a = _fromAccounts[key];
if (typeof a === 'string' && a !== '') return a;
return _getStoredSync(key, envFallback);
}
/** This site's own value, ignoring Accounts (for sending this site's look to Accounts, src/accounts/look.ts). */
function _getStoredSync(key, envFallback = '') {
const v = _cache[key]; const v = _cache[key];
const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || ''); const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || '');
if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) { if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) {
@@ -76,4 +111,10 @@ function invalidate() {
refreshIfStale().catch(() => {}); refreshIfStale().catch(() => {});
} }
module.exports = { getSetting, getSettingSync, warmCache, invalidate, ENCRYPTED_KEYS }; /** As getSetting, but this site's own value even when Accounts sets the key. */
async function getStoredSetting(key, envFallback = '') {
await refreshIfStale();
return _getStoredSync(key, envFallback);
}
module.exports = { getSetting, getSettingSync, getStoredSetting, warmCache, invalidate, setAccountsOverrides, accountsOverrides, ENCRYPTED_KEYS };
@@ -37,8 +37,9 @@ const realFetch = global.fetch;
beforeAll(() => { beforeAll(() => {
global.fetch = (async (url: string) => { global.fetch = (async (url: string) => {
// The logo, copied for PDFs (utils/logoCopy.js): not part of these tests.
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 });
fetches++; fetches++;
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
const next = answers.shift() ?? 200; const next = answers.shift() ?? 200;
if (next === 'down') throw new Error('connect ECONNREFUSED'); if (next === 'down') throw new Error('connect ECONNREFUSED');
return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } }); return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } });
@@ -0,0 +1,128 @@
// The church's own details from Accounts (name, logo, icon, colours, contact) win over this site's
// settings of the same name: on the public settings, in Settings (read-only), and for everything
// that reads them through the settings cache (emails, PDFs). Without Accounts, the site's own stand.
import fs from 'fs';
import path from 'path';
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
const mockLinks: Link[] = [];
const mockRows: { key: string; value: string }[] = [];
jest.mock('../src/config/db', () => ({
productLink: {
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
},
appSetting: {
findMany: async (q?: { where?: { key?: { in?: string[] } } }) => mockRows.filter((r) => !q?.where?.key?.in || q.where.key.in.includes(r.key)),
},
}));
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
import { CHURCH_PATHS } from '@crosscode/contracts';
import { churchProfile, churchSettings, resetChurchProfile } from '../src/accounts/church';
import { churchLook } from '../src/accounts/look';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const settingsCache = require('../src/utils/settingsCache');
const { getSettings, getAllSettings } = require('../src/controllers/settingsController');
/* eslint-enable @typescript-eslint/no-require-imports */
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const sample = () => JSON.parse(fs.readFileSync(path.join(SAMPLES, 'church.json'), 'utf8'));
let profile = sample();
const realFetch = global.fetch;
beforeAll(() => {
global.fetch = (async (url: string) => {
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 }); // the logo (logoCopy tests)
return new Response(JSON.stringify(profile), { status: 200, headers: { 'content-type': 'application/json' } });
}) as typeof fetch;
});
afterAll(() => { global.fetch = realFetch; });
beforeEach(() => {
resetChurchProfile();
mockLinks.length = 0;
mockRows.length = 0;
mockRows.push(
{ key: 'org_name', value: 'Old Demo Church' },
{ key: 'org_tagline', value: 'Our own tagline' },
{ key: 'primary_color', value: '#111111' },
{ key: 'secondary_color', value: '#222222' },
{ key: 'logo_url', value: '/uploads/old-logo.png' },
);
settingsCache.invalidate();
profile = sample();
});
const connectAccounts = () => mockLinks.push({ installId: 'acc', product: 'accounts', url: 'https://accounts.hope.test/', secret: 'x', updatedAt: new Date() });
async function call(handler: (req: unknown, res: unknown) => Promise<void>): Promise<Record<string, string>> {
let body: Record<string, string> = {};
await handler({}, { json: (b: Record<string, string>) => { body = b; }, status() { return this; } });
return body;
}
describe("the church's details from Accounts", () => {
test('only what the profile has', () => {
profile.branding.iconUrl = null;
profile.branding.colours.accent = null;
const s = churchSettings(profile);
expect(s.org_name).toBe(profile.name);
expect(s.primary_color).toBe(profile.branding.colours.primary);
expect('favicon_url' in s).toBe(false);
expect('accent_color' in s).toBe(false);
expect(churchSettings(null)).toEqual({});
});
test('without Accounts, the site keeps its own', async () => {
const s = await call(getSettings);
expect(s.org_name).toBe('Old Demo Church');
expect((await call(getAllSettings)).accounts_managed).toBe('');
});
test("with Accounts, the public settings show the church's, and keep what the profile doesn't set", async () => {
connectAccounts();
const s = await call(getSettings);
expect(s.org_name).toBe(profile.name);
expect(s.primary_color).toBe(profile.branding.colours.primary);
expect(s.logo_url).toBe(profile.branding.logoUrl);
expect(s.org_tagline).toBe('Our own tagline');
expect(s.secondary_color).toBe('#222222');
});
test('Settings marks the ones Accounts sets', async () => {
connectAccounts();
const all = await call(getAllSettings);
expect(all.org_name).toBe(profile.name);
expect(all.accounts_managed.split(',')).toEqual(expect.arrayContaining(['org_name', 'primary_color', 'logo_url']));
expect(all.accounts_managed.split(',')).not.toContain('secondary_color');
});
test('the settings cache (emails, PDFs) uses them once the profile is in, and the look sent to Accounts stays the site\'s own', async () => {
connectAccounts();
await settingsCache.warmCache();
await churchProfile();
expect(settingsCache.getSettingSync('org_name', 'Cross Code')).toBe(profile.name);
expect(await settingsCache.getStoredSetting('org_name')).toBe('Old Demo Church');
expect((await churchLook()).name).toBe('Old Demo Church');
});
test('a church that changes its name in Accounts (a new demo church) is shown after church.changed', async () => {
connectAccounts();
await churchProfile();
profile.name = 'Grace Fellowship';
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('../src/accounts/church').churchChanged();
await churchProfile();
expect(settingsCache.getSettingSync('org_name')).toBe('Grace Fellowship');
expect((await call(getSettings)).org_name).toBe('Grace Fellowship');
});
test('disconnected from Accounts: back to the site\'s own', async () => {
connectAccounts();
await churchProfile();
mockLinks.length = 0;
await churchProfile();
expect(settingsCache.getSettingSync('org_name')).toBe('Old Demo Church');
});
});
+126
View File
@@ -0,0 +1,126 @@
// The logo for PDFs: an uploaded one is used as it is; the church's logo from Accounts (an address
// on another site) is copied into uploads/accounts once, when it's a PNG, JPEG or SVG; drawLogo
// draws either kind into a PDF.
import fs from 'fs';
import path from 'path';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { pdfLogoPath, drawLogo, resetLogoCopies } = require('../src/utils/logoCopy') as {
pdfLogoPath(u: string): Promise<string | null>;
drawLogo(doc: unknown, file: string | null, x: number, y: number, o?: { fit?: [number, number]; align?: string }): boolean;
resetLogoCopies(): void;
};
const PDFDocument = require('pdfkit');
const { UPLOADS_DIR } = require('../src/utils/uploads') as { UPLOADS_DIR: string };
/* eslint-enable @typescript-eslint/no-require-imports */
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
const SVG = Buffer.from('<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#1f4e79"/><path d="M232 96h48v320h-48z" fill="#fff"/></svg>');
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]);
const COPIES = path.join(UPLOADS_DIR, 'accounts');
const realFetch = global.fetch;
let served: Record<string, Buffer | number> = {};
let fetched: string[] = [];
beforeAll(() => {
global.fetch = (async (url: string) => {
fetched.push(url);
const body = served[url];
if (body === undefined || typeof body === 'number') return new Response('', { status: typeof body === 'number' ? body : 404 });
return new Response(new Uint8Array(body), { status: 200 });
}) as typeof fetch;
});
afterAll(() => {
global.fetch = realFetch;
fs.rmSync(COPIES, { recursive: true, force: true });
});
beforeEach(() => {
fs.rmSync(COPIES, { recursive: true, force: true });
resetLogoCopies();
served = {};
fetched = [];
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => { jest.restoreAllMocks(); });
function pdfOf(draw: (doc: unknown) => void): Promise<string> {
return new Promise((resolve) => {
const doc = new PDFDocument({ compress: false });
const parts: Buffer[] = [];
doc.on('data', (b: Buffer) => parts.push(b));
doc.on('end', () => resolve(Buffer.concat(parts).toString('latin1')));
draw(doc);
doc.end();
});
}
test("the church's PNG logo from Accounts is copied once, and used from the copy after", async () => {
served['https://accounts.hope.test/logo.png'] = PNG;
const p = await pdfLogoPath('https://accounts.hope.test/logo.png');
expect(p && path.dirname(p)).toBe(COPIES);
expect(fs.readFileSync(p!)).toEqual(PNG);
expect(await pdfLogoPath('https://accounts.hope.test/logo.png')).toBe(p);
expect(fetched).toHaveLength(1);
});
test('a new logo replaces the copy of the old one', async () => {
served['https://accounts.hope.test/old.png'] = PNG;
served['https://accounts.hope.test/new.png'] = PNG;
const old = await pdfLogoPath('https://accounts.hope.test/old.png');
const next = await pdfLogoPath('https://accounts.hope.test/new.png');
expect(next).not.toBe(old);
expect(fs.existsSync(old!)).toBe(false);
expect(fs.readdirSync(COPIES)).toHaveLength(1);
});
test("an SVG logo (the demo churches') is copied too", async () => {
served['https://accounts.hope.test/logo.svg'] = SVG;
const p = await pdfLogoPath('https://accounts.hope.test/logo.svg');
expect(p?.endsWith('.svg')).toBe(true);
});
test("a logo a PDF can't draw, or one that can't be fetched, gives none (the PDF shows the name), and isn't fetched again at once", async () => {
served['https://accounts.hope.test/logo.webp'] = WEBP;
served['https://accounts.hope.test/gone.png'] = 404;
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
expect(await pdfLogoPath('https://accounts.hope.test/gone.png')).toBeNull();
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
expect(fetched).toHaveLength(2);
});
test('drawLogo draws an SVG logo as shapes in its colours, and never opens a file the SVG names', async () => {
fs.mkdirSync(COPIES, { recursive: true });
const file = path.join(COPIES, 'logo-test.svg');
fs.writeFileSync(file, SVG);
let drawn = false;
const pdf = await pdfOf((doc) => { drawn = drawLogo(doc, file, 40, 40, { fit: [60, 60], align: 'center' }); });
expect(drawn).toBe(true);
expect(pdf).toMatch(/0\.12156\d* 0\.30588\d* 0\.47450\d* scn/); // #1f4e79
const picture = path.join(COPIES, 'logo-test.png');
fs.writeFileSync(picture, PNG);
const sneaky = path.join(COPIES, 'logo-sneaky.svg');
const href = picture.split(path.sep).join('/');
fs.writeFileSync(sneaky, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><image href="${href}" width="10" height="10"/></svg>`);
const out = await pdfOf((doc) => { drawLogo(doc, sneaky, 0, 0, { fit: [10, 10] }); });
expect(out).not.toContain('/Subtype /Image');
});
test("drawLogo gives false, without throwing, for a file it can't draw", async () => {
fs.mkdirSync(COPIES, { recursive: true });
const bad = path.join(COPIES, 'logo-bad.png');
fs.writeFileSync(bad, 'not a picture');
let drawn = true;
await pdfOf((doc) => { drawn = drawLogo(doc, bad, 0, 0, { fit: [10, 10] }); });
expect(drawn).toBe(false);
expect(drawLogo({}, null, 0, 0)).toBe(false);
});
test('a logo uploaded here is used as it is; nothing for no logo', async () => {
fs.mkdirSync(COPIES, { recursive: true });
fs.writeFileSync(path.join(COPIES, 'own.png'), PNG);
expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(COPIES, 'own.png'));
expect(await pdfLogoPath('')).toBeNull();
expect(await pdfLogoPath('/uploads/accounts/missing.png')).toBeNull();
expect(fetched).toHaveLength(0);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/events-frontend", "name": "@crosscode/events-frontend",
"version": "3.8.0", "version": "3.9.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@@ -26,6 +26,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink"; import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup"; import { uploadImage } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks"; import { useExternalEffect } from "@/lib/hooks";
import { useChurch } from "@/contexts/ChurchContext";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai"; type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai";
@@ -48,7 +49,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
]; ];
const inputCls = const inputCls =
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500";
/** The code from Search Console's verification meta tag; accepts the whole tag or just the code. */ /** The code from Search Console's verification meta tag; accepts the whole tag or just the code. */
function googleVerificationCode(input: string): string { function googleVerificationCode(input: string): string {
@@ -56,6 +57,20 @@ function googleVerificationCode(input: string): string {
return (m ? m[1] : input).trim(); return (m ? m[1] : input).trim();
} }
/**
* Shown above Organisation and Branding while the church's Accounts sets some of their fields:
* those come from the church profile (on all the church's sites) and are changed there.
*/
function FromAccountsNotice({ what, href }: { what: string; href: string | null }) {
return (
<div className="rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900">
Your church&apos;s {what} come from its church profile in Accounts, so every one of its sites shows the same.
They can&apos;t be changed here.{" "}
{href ? <a href={href} className="font-medium underline">Change them in Accounts ↗</a> : "Change them in Accounts, under Church profile."}
</div>
);
}
function Field({ function Field({
label, hint, required, children, label, hint, required, children,
}: { }: {
@@ -146,6 +161,14 @@ function SiteSettingsPageInner() {
const [faviconPreview, setFaviconPreview] = useState<string | null>(null); const [faviconPreview, setFaviconPreview] = useState<string | null>(null);
const faviconRef = useRef<HTMLInputElement>(null); const faviconRef = useRef<HTMLInputElement>(null);
// ── From Accounts ── the settings the church profile sets (name, logo, colours, contact): shown,
// not editable, and never sent back. The church profile's own page in Accounts changes them.
const [managed, setManaged] = useState<Set<string>>(new Set());
const church = useChurch();
const accountsChurchUrl = church ? `${church.links.accounts.replace(/\/+$/, "")}/admin/church` : null;
const fromAccounts = (key: string) => managed.has(key);
const ownOnly = (updates: Record<string, string>) => Object.fromEntries(Object.entries(updates).filter(([k]) => !managed.has(k)));
// ── Notifications ── // ── Notifications ──
const [notifEmails, setNotifEmails] = useState(""); const [notifEmails, setNotifEmails] = useState("");
@@ -206,6 +229,7 @@ function SiteSettingsPageInner() {
setLegalEffectiveDate(s.legal_effective_date || ""); setLegalEffectiveDate(s.legal_effective_date || "");
setConsentRetentionDays(s.consent_medical_retention_days || "30"); setConsentRetentionDays(s.consent_medical_retention_days || "30");
setNotifyOnImpersonation(s.notify_user_on_impersonation === "true"); setNotifyOnImpersonation(s.notify_user_on_impersonation === "true");
setManaged(new Set((s.accounts_managed || "").split(",").filter(Boolean)));
}) })
.catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" })) .catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" }))
.finally(() => setLoadingInitial(false)); .finally(() => setLoadingInitial(false));
@@ -220,7 +244,7 @@ function SiteSettingsPageInner() {
setSaving(true); setSaving(true);
setResult(null); setResult(null);
try { try {
await apiV2Data("put", "/settings", { authToken: token, body: updates }); await apiV2Data("put", "/settings", { authToken: token, body: ownOnly(updates) });
setResult({ ok: true, message: "Saved." }); setResult({ ok: true, message: "Saved." });
reloadSettings(); reloadSettings();
} catch (e) { } catch (e) {
@@ -271,13 +295,13 @@ function SiteSettingsPageInner() {
await apiV2Data("put", "/settings", { await apiV2Data("put", "/settings", {
authToken: token, authToken: token,
body: { body: ownOnly({
primary_color: primaryColor, primary_color: primaryColor,
secondary_color: secondaryColor, secondary_color: secondaryColor,
accent_color: accentColor, accent_color: accentColor,
logo_url: finalLogoUrl, logo_url: finalLogoUrl,
favicon_url: finalFaviconUrl, favicon_url: finalFaviconUrl,
}, }),
}); });
setLogoUrl(finalLogoUrl); setLogoUrl(finalLogoUrl);
setLogoFile(null); setLogoFile(null);
@@ -303,13 +327,13 @@ function SiteSettingsPageInner() {
try { try {
await apiV2Data("put", "/settings", { await apiV2Data("put", "/settings", {
authToken: token, authToken: token,
body: { primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }, body: ownOnly({ primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }),
}); });
setPrimaryColor("#4F46E5"); if (!fromAccounts("primary_color")) setPrimaryColor("#4F46E5");
setSecondaryColor("#8B5CF6"); setSecondaryColor("#8B5CF6");
setAccentColor("#EC4899"); if (!fromAccounts("accent_color")) setAccentColor("#EC4899");
setLogoUrl(""); setLogoFile(null); setLogoPreview(null); if (!fromAccounts("logo_url")) { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); }
setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (!fromAccounts("favicon_url")) { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); }
setSuggestedColors([]); setSuggestedColors([]);
setResult({ ok: true, message: "Reset to defaults." }); setResult({ ok: true, message: "Reset to defaults." });
reloadSettings(); reloadSettings();
@@ -433,9 +457,10 @@ function SiteSettingsPageInner() {
{activeTab === "organisation" && ( {activeTab === "organisation" && (
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-lg font-semibold text-gray-900">Organisation details</h2> <h2 className="text-lg font-semibold text-gray-900">Organisation details</h2>
{["org_name", "org_email", "org_phone", "org_address"].some(fromAccounts) && <FromAccountsNotice what="name and contact details" href={accountsChurchUrl} />}
<Field label="Organisation name" required> <Field label="Organisation name" required>
<input className={inputCls} placeholder="Your Organisation" <input className={inputCls} placeholder="Your Organisation"
value={orgName} onChange={e => setOrgName(e.target.value)} /> value={orgName} disabled={fromAccounts("org_name")} onChange={e => setOrgName(e.target.value)} />
</Field> </Field>
<Field label="Tagline"> <Field label="Tagline">
<input className={inputCls} placeholder="Connecting community through events" <input className={inputCls} placeholder="Connecting community through events"
@@ -444,16 +469,16 @@ function SiteSettingsPageInner() {
<div className="grid sm:grid-cols-2 gap-4"> <div className="grid sm:grid-cols-2 gap-4">
<Field label="Contact email"> <Field label="Contact email">
<input type="email" className={inputCls} placeholder="admin@yourchurch.org" <input type="email" className={inputCls} placeholder="admin@yourchurch.org"
value={orgEmail} onChange={e => setOrgEmail(e.target.value)} /> value={orgEmail} disabled={fromAccounts("org_email")} onChange={e => setOrgEmail(e.target.value)} />
</Field> </Field>
<Field label="Phone"> <Field label="Phone">
<input className={inputCls} placeholder="+27 12 345 6789" <input className={inputCls} placeholder="+27 12 345 6789"
value={orgPhone} onChange={e => setOrgPhone(e.target.value)} /> value={orgPhone} disabled={fromAccounts("org_phone")} onChange={e => setOrgPhone(e.target.value)} />
</Field> </Field>
</div> </div>
<Field label="Address" hint="Used as the default location for new events."> <Field label="Address" hint="Used as the default location for new events.">
<input className={inputCls} placeholder="123 Church St, City" <input className={inputCls} placeholder="123 Church St, City"
value={orgAddress} onChange={e => setOrgAddress(e.target.value)} /> value={orgAddress} disabled={fromAccounts("org_address")} onChange={e => setOrgAddress(e.target.value)} />
{orgAddress.trim() && ( {orgAddress.trim() && (
<a href={mapsSearchUrl(orgAddress.trim())} target="_blank" rel="noopener noreferrer" <a href={mapsSearchUrl(orgAddress.trim())} target="_blank" rel="noopener noreferrer"
className="inline-block text-xs text-brand-600 hover:underline mt-1"> className="inline-block text-xs text-brand-600 hover:underline mt-1">
@@ -477,14 +502,15 @@ function SiteSettingsPageInner() {
{activeTab === "branding" && ( {activeTab === "branding" && (
<div className="space-y-5"> <div className="space-y-5">
<h2 className="text-lg font-semibold text-gray-900">Branding</h2> <h2 className="text-lg font-semibold text-gray-900">Branding</h2>
{["primary_color", "accent_color", "logo_url", "favicon_url"].some(fromAccounts) && <FromAccountsNotice what="logo and colours" href={accountsChurchUrl} />}
<div className="grid sm:grid-cols-3 gap-4"> <div className="grid sm:grid-cols-3 gap-4">
<ColorPickerField label="Primary" hint="Buttons, links, nav highlights, and the email header/CTA." <ColorPickerField label="Primary" hint="Buttons, links, nav highlights, and the email header/CTA."
value={primaryColor} onChange={setPrimaryColor} /> value={primaryColor} onChange={setPrimaryColor} disabled={fromAccounts("primary_color")} />
<ColorPickerField label="Secondary" hint="Subtle backgrounds and outline-button borders/text." <ColorPickerField label="Secondary" hint="Subtle backgrounds and outline-button borders/text."
value={secondaryColor} onChange={setSecondaryColor} /> value={secondaryColor} onChange={setSecondaryColor} />
<ColorPickerField label="Accent" hint="Hover states and highlight chips/badges." <ColorPickerField label="Accent" hint="Hover states and highlight chips/badges."
value={accentColor} onChange={setAccentColor} /> value={accentColor} onChange={setAccentColor} disabled={fromAccounts("accent_color")} />
</div> </div>
<Field label="Site logo" hint="PNG, JPG, SVG or WebP, max 2 MB. Displayed in the navigation bar."> <Field label="Site logo" hint="PNG, JPG, SVG or WebP, max 2 MB. Displayed in the navigation bar.">
@@ -492,16 +518,16 @@ function SiteSettingsPageInner() {
<div className="mb-3 flex items-center gap-3"> <div className="mb-3 flex items-center gap-3">
{/* eslint-disable-next-line @next/next/no-img-element */} {/* eslint-disable-next-line @next/next/no-img-element */}
<img src={currentLogoSrc} alt="Current logo" className="h-16 object-contain border rounded p-1 bg-gray-50" /> <img src={currentLogoSrc} alt="Current logo" className="h-16 object-contain border rounded p-1 bg-gray-50" />
<button {!fromAccounts("logo_url") && <button
type="button" type="button"
className="text-xs text-red-500 hover:text-red-700" className="text-xs text-red-500 hover:text-red-700"
onClick={() => { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); setSuggestedColors([]); if (fileRef.current) fileRef.current.value = ""; }} onClick={() => { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); setSuggestedColors([]); if (fileRef.current) fileRef.current.value = ""; }}
> >
Remove Remove
</button> </button>}
</div> </div>
)} )}
<input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" /> {!fromAccounts("logo_url") && <input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" />}
{suggestedColors.length > 0 && ( {suggestedColors.length > 0 && (
<div className="mt-3 border rounded-lg p-3 bg-gray-50"> <div className="mt-3 border rounded-lg p-3 bg-gray-50">
<p className="text-xs font-medium text-gray-600 mb-2">Suggested from your logo — click a swatch to apply it</p> <p className="text-xs font-medium text-gray-600 mb-2">Suggested from your logo — click a swatch to apply it</p>
@@ -524,21 +550,21 @@ function SiteSettingsPageInner() {
<div className="mb-3 flex items-center gap-3"> <div className="mb-3 flex items-center gap-3">
{/* eslint-disable-next-line @next/next/no-img-element */} {/* eslint-disable-next-line @next/next/no-img-element */}
<img src={currentFaviconSrc} alt="Current favicon" className="h-8 w-8 object-contain border rounded p-1 bg-gray-50" /> <img src={currentFaviconSrc} alt="Current favicon" className="h-8 w-8 object-contain border rounded p-1 bg-gray-50" />
<button {!fromAccounts("favicon_url") && <button
type="button" type="button"
className="text-xs text-red-500 hover:text-red-700" className="text-xs text-red-500 hover:text-red-700"
onClick={() => { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (faviconRef.current) faviconRef.current.value = ""; }} onClick={() => { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (faviconRef.current) faviconRef.current.value = ""; }}
> >
Remove Remove
</button> </button>}
</div> </div>
)} )}
<input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => { {!fromAccounts("favicon_url") && <input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
setFaviconFile(file); setFaviconFile(file);
setFaviconPreview(URL.createObjectURL(file)); setFaviconPreview(URL.createObjectURL(file));
}} className="text-sm" /> }} className="text-sm" />}
</Field> </Field>
<div className="flex items-center justify-between pt-4 border-t mt-6 flex-wrap gap-3"> <div className="flex items-center justify-between pt-4 border-t mt-6 flex-wrap gap-3">
@@ -5,12 +5,14 @@ import { isValidHex } from "@/lib/colorScale";
/** A native color swatch + hex text input, shared by the admin Branding tab and the setup wizard's Branding step. */ /** A native color swatch + hex text input, shared by the admin Branding tab and the setup wizard's Branding step. */
export function ColorPickerField({ export function ColorPickerField({
label, hint, value, onChange, label, hint, value, onChange, disabled,
}: { }: {
label: string; label: string;
hint?: string; hint?: string;
value: string; value: string;
onChange: (hex: string) => void; onChange: (hex: string) => void;
/** Set elsewhere (the church profile in Accounts): shown, not changed here. */
disabled?: boolean;
}) { }) {
const valid = isValidHex(value); const valid = isValidHex(value);
return ( return (
@@ -19,13 +21,15 @@ export function ColorPickerField({
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<input <input
type="color" type="color"
className="h-10 w-20 border rounded cursor-pointer shrink-0" disabled={disabled}
className="h-10 w-20 border rounded cursor-pointer shrink-0 disabled:cursor-not-allowed"
value={valid ? value : "#000000"} value={valid ? value : "#000000"}
onChange={e => onChange(e.target.value)} onChange={e => onChange(e.target.value)}
/> />
<input <input
className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 ${valid ? "" : "border-red-300"}`} className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500 ${valid ? "" : "border-red-300"}`}
placeholder="#2563eb" placeholder="#2563eb"
disabled={disabled}
value={value} value={value}
onChange={e => onChange(e.target.value)} onChange={e => onChange(e.target.value)}
/> />
+6 -3
View File
@@ -52,15 +52,18 @@ function computeApiBase(): string {
export const API_BASE = computeApiBase(); export const API_BASE = computeApiBase();
// Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE. // Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE.
// If it's an absolute URL but points to localhost/127.0.0.1/::1, rewrite its origin to API_BASE. // If it's an absolute URL to this site's own uploads on localhost/127.0.0.1/::1, rewrite its
// origin to API_BASE. Another localhost address (the church's Accounts in development, whose logo
// the site now shows) is left as it is.
export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null { export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null {
const raw = (urlOrPath || "").trim(); const raw = (urlOrPath || "").trim();
if (!raw) return null; if (!raw) return null;
try { try {
if (raw.startsWith("http")) { if (raw.startsWith("http")) {
const u = new URL(raw); const u = new URL(raw);
const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname); const isLocal = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
if (isLocal && API_BASE) { const ownUpload = /^\/(api\/)?uploads\//.test(u.pathname);
if (isLocal && ownUpload && API_BASE) {
const api = new URL(API_BASE); const api = new URL(API_BASE);
u.protocol = api.protocol; u.protocol = api.protocol;
u.hostname = api.hostname; u.hostname = api.hostname;
+24
View File
@@ -1,5 +1,29 @@
# Changelog — Church Website # Changelog — Church Website
## [1.9.0] — 2026-12-01
No migration, no new environment settings. Needs `@crosscode/ui` 0.4.0 (built with the Website).
### Added
- **A background for each homepage section** (Template and style → Home page layout), from the
church's colours: as the style sets it (the default), white, soft main colour, soft accent
colour, main colour, or deep main colour. Stored on the design's home entry (`background`,
`SECTION_BACKGROUNDS` in `src/site/variants.ts`), kept through a template switch, checked by
`cleanDesign`, and carried to the snapshot's section. On the main colour, text, links and
buttons use the palette's on-brand colour; on the deep shade, white. A layout with its own
background (`cc-own-bg`: a photo, a band) and the top of the page keep theirs; Section colour's
tinted and mixed patterns skip a section that has its own.
### Changed
- **Events from Cross Events** say "Register on our Events site" only when they take
registrations and are open; contact-only, full or closed ones say "More info on our Events
site". The site's events carry the registration's `mode`.
- **Church details:** the main and accent colours use the shared colour field (`ColourField`,
`@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, and a preview, as Cross Events'
Branding settings.
## [1.8.0] — 2026-11-30 ## [1.8.0] — 2026-11-30
No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by
+12
View File
@@ -3,6 +3,18 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged). WHATS-NEW.md; a section shows once its version is tagged).
## 1.9.0
- **Choose a background for each homepage section.** In **Template and style → Home page layout**,
each section now has a background in your church's colours: white, a soft wash of your main or
accent colour, your main colour, or a deep shade of it. Text and buttons change to stay easy to
read. Leave it as it is and the section follows your style's section colour, as before.
- **Events say "More info" when there's nothing to register for.** An event from your Events site
only says "Register on our Events site" when people can register; events where people just
contact the church say "More info on our Events site".
- **An easier colour picker** in **Church details**: pick a colour, or type or paste its code
(like #1f4e79), and see it straight away.
## 1.8.0 ## 1.8.0
- Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo - Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.8.0", "version": "1.9.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads", "description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true, "private": true,
"type": "module", "type": "module",
+2 -2
View File
@@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js';
import { ApiError } from '../http.js'; import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js'; import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js';
import { cleanDesign } from '../site/snapshot.js'; import { cleanDesign } from '../site/snapshot.js';
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js'; import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
type Who = { id: string; role: string }; type Who = { id: string; role: string };
@@ -55,7 +55,7 @@ export async function getDesign(ctx: Ctx) {
const designPatch = z.object({ const designPatch = z.object({
template: websiteTemplateSchema.optional(), template: websiteTemplateSchema.optional(),
variants: z.record(z.string(), z.string()).optional(), variants: z.record(z.string(), z.string()).optional(),
home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(), home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean(), background: z.enum(SECTION_BACKGROUNDS).optional() })).max(SECTION_TYPES.length).optional(),
style: z.object({ style: z.object({
sectionColour: z.enum(SECTION_COLOURS).optional(), sectionColour: z.enum(SECTION_COLOURS).optional(),
spacing: z.enum(SPACINGS).optional(), spacing: z.enum(SPACINGS).optional(),
+3 -2
View File
@@ -26,7 +26,8 @@ export type SiteEvent = {
/** An outside link for more information or signing up (the Website's own events). */ /** An outside link for more information or signing up (the Website's own events). */
link: string | null; link: string | null;
from: 'website' | 'events' | 'app'; from: 'website' | 'events' | 'app';
registration: { status: string; priceFromCents: number | null } | null; /** From Cross Events: how it's joined (`origin`: register there; `contact`: ask the church; `none`: just come), whether it's open, and from what price. */
registration: { mode: string; status: string; priceFromCents: number | null } | null;
}; };
export type SiteMessage = { export type SiteMessage = {
@@ -147,7 +148,7 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
return [{ return [{
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null, 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, slug: null, link: null, from: e.origin.product, image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, slug: null, link: null, from: e.origin.product,
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null, registration: e.registration ? { mode: e.registration.mode, status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
} satisfies SiteEvent]; } satisfies SiteEvent];
}); });
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt)); return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
+9 -4
View File
@@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js'; import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js'; import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js'; import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js'; import { defaultDesign, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1; export const SNAPSHOT_VERSION = 1;
@@ -34,7 +34,8 @@ export const framed = (img: Image | null, f: unknown): Image | null => {
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown }; type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> }; /** `background`: a homepage section's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown>; background?: SectionBackground };
export type SnapshotPage = { export type SnapshotPage = {
kind: string; kind: string;
@@ -87,7 +88,11 @@ export function cleanDesign(saved: { template: string; variants: unknown; home:
const v = (saved.variants ?? {}) as Record<string, unknown>; 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; 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) 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 })) ? (saved.home as { section?: unknown; hidden?: unknown; background?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({
section: e.section as SectionType,
hidden: !!e.hidden,
...((SECTION_BACKGROUNDS as readonly unknown[]).includes(e.background) ? { background: e.background as SectionBackground } : {}),
}))
: base.home; : base.home;
// Every section listed once: any missing one is added at the end, hidden. // 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 }); for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
@@ -176,7 +181,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
const data = parseSectionData(entry.section, byType.get(entry.section)?.data); const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
if (!data) continue; if (!data) continue;
collect(data); collect(data);
sections.push({ type: entry.section, variant: d.variants[entry.section], data }); sections.push({ type: entry.section, variant: d.variants[entry.section], data, ...(entry.background ? { background: entry.background } : {}) });
} }
} else { } else {
for (const x of p.sections) { for (const x of p.sections) {
+18 -3
View File
@@ -104,8 +104,18 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant); return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
} }
/** A homepage entry: the section and whether it shows. */ /**
export type HomeEntry = { section: SectionType; hidden: boolean }; * A homepage section's own background: always from the church's colours, so it stays on brand.
* Left out, the section follows the site's Section colour (style). `light` is plain white; `tint`
* and `accent` are soft washes of the main and accent colours; `brand` is the main colour itself and
* `dark` a deep shade of it, both with light text. A layout with its own background (a photo, a
* band) keeps it.
*/
export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const;
export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number];
/** A homepage entry: the section, whether it shows, and its own background when it has one. */
export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground };
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [ const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
...shown.map((section) => ({ section, hidden: false })), ...shown.map((section) => ({ section, hidden: false })),
@@ -184,7 +194,12 @@ export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { desi
} }
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]); const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e })); // The order may move to the new template's; each section keeps the background it was given.
const backgrounds = new Map(current.home.flatMap((e) => (e.background ? [[e.section, e.background] as const] : [])));
const home = (homeUntouched ? target.home : current.home).map(({ background: _b, ...e }) => {
const background = backgrounds.get(e.section);
return background ? { ...e, background } : e;
});
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` }); if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
const style = { ...current.style }; const style = { ...current.style };
+1 -1
View File
@@ -114,7 +114,7 @@ describe('showing events from Cross Events (Show events from)', () => {
if (c.mode === 'published') { if (c.mode === 'published') {
assert.equal(c.events[0]!.title, 'Youth camp'); assert.equal(c.events[0]!.title, 'Youth camp');
assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d'); assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d');
assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 }); assert.deepEqual(c.events[0]!.registration, { mode: 'origin', status: 'open', priceFromCents: 45000 });
} }
assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/); assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/);
}); });
@@ -5,6 +5,7 @@ import {
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS, SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate, defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
} from '../src/site/variants.js'; } from '../src/site/variants.js';
import { cleanDesign } from '../src/site/snapshot.js';
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => { describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
it('has the 26 confirmed variant ids', () => { it('has the 26 confirmed variant ids', () => {
@@ -101,3 +102,20 @@ describe('switching template', () => {
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage')); assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
}); });
}); });
describe("a section's own background", () => {
it('stays with its section through a template switch, whether the order moves or not', () => {
const start = defaultDesign('heritage');
start.home = start.home.map((e) => (e.section === 'events' ? { ...e, background: 'brand' as const } : e));
const moved = switchTemplate(start, 'bold').design;
assert.equal(moved.home.find((e) => e.section === 'events')?.background, 'brand');
assert.deepEqual(moved.home.map((e) => e.section), defaultDesign('bold').home.map((e) => e.section));
assert.equal(moved.home.filter((e) => e.background).length, 1);
});
it('is kept by cleanDesign only when it is one of the church-colour choices', () => {
const d = cleanDesign({ template: 'clean', variants: {}, home: [{ section: 'welcome', hidden: false, background: 'tint' }, { section: 'events', hidden: false, background: 'hot-pink' }], style: {} });
assert.equal(d.home.find((e) => e.section === 'welcome')?.background, 'tint');
assert.equal('background' in d.home.find((e) => e.section === 'events')!, false);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.8.0", "version": "1.9.0",
"private": true, "private": true,
"description": "Church Website: the church's public site in its template, and the admin", "description": "Church Website: the church's public site in its template, and the admin",
"scripts": { "scripts": {
@@ -7,6 +7,7 @@
*/ */
import { useState } from "react"; import { useState } from "react";
import type { Church } from "@crosscode/contracts"; import type { Church } from "@crosscode/contracts";
import { ColourField } from "@crosscode/ui";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media"; import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
@@ -55,8 +56,10 @@ export default function ChurchDetails() {
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field> <Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field>
<Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field> <Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field>
<Field label="Main colour" error={err("branding.colours.primary")}><input type="color" className="h-10 w-20" value={c.branding.colours.primary} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, primary: e.target.value } } })} /></Field> <ColourField label="Main colour" hint="Buttons, links and headings on every site." error={err("branding.colours.primary")} disabled={!editor}
<Field label="Accent colour"><input type="color" className="h-10 w-20" value={c.branding.colours.accent ?? "#999999"} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, accent: e.target.value } } })} /></Field> value={c.branding.colours.primary} onChange={(primary) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, primary } } })} />
<ColourField label="Accent colour" hint="Highlights and touches beside the main colour." error={err("branding.colours.accent")} disabled={!editor}
value={c.branding.colours.accent ?? "#999999"} onChange={(accent) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, accent } } })} />
<Field label="Fonts" hint="Shared by all your sites. Your template suggests some."> <Field label="Fonts" hint="Shared by all your sites. Your template suggests some.">
<select className={inputClass} value={c.branding.style?.fontPairing ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: (e.target.value || null) as never, corners: c.branding.style?.corners ?? null } } })}> <select className={inputClass} value={c.branding.style?.fontPairing ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: (e.target.value || null) as never, corners: c.branding.style?.corners ?? null } } })}>
{PAIRINGS.map(([v, l]) => <option key={v} value={v}>{l}</option>)} {PAIRINGS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
@@ -12,7 +12,18 @@ import { api } from "@/admin/api";
import { WithPreview } from "@/admin/LivePreview"; import { WithPreview } from "@/admin/LivePreview";
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> }; type HomeEntry = { section: string; hidden: boolean; background?: string };
type Design = { template: string; variants: Record<string, string>; home: HomeEntry[]; style: Record<string, string> };
/** A section's own background (backend variants.ts SECTION_BACKGROUNDS), each from the church's colours; "" follows Style → Section colour. */
const BACKGROUNDS: { id: string; name: string; swatch: string }[] = [
{ id: "", name: "As the style sets it", swatch: "repeating-linear-gradient(45deg, #fff 0 4px, rgb(var(--brand-tint)) 4px 8px)" },
{ id: "light", name: "White", swatch: "#fff" },
{ id: "tint", name: "Soft main colour", swatch: "rgb(var(--brand-tint))" },
{ id: "accent", name: "Soft accent colour", swatch: "linear-gradient(rgb(var(--accent) / 0.12), rgb(var(--accent) / 0.12)), #fff" },
{ id: "brand", name: "Main colour", swatch: "rgb(var(--brand))" },
{ id: "dark", name: "Deep main colour", swatch: "linear-gradient(rgb(0 0 0 / 0.35), rgb(0 0 0 / 0.35)), rgb(var(--brand-dark))" },
];
type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> }; type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
const TEMPLATES = [ const TEMPLATES = [
@@ -94,7 +105,7 @@ export default function TemplatePage() {
)} )}
{tab === "home" && ( {tab === "home" && (
<Panel title="Home page: sections and layouts" icon={ListOrdered} sub={<>Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best. What each section says is on the home page, under Pages.</>}> <Panel title="Home page: sections and layouts" icon={ListOrdered} sub={<>Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best. Each section can have its own background in your church&apos;s colours (a layout with a photo or band keeps its own). What each section says is on the home page, under Pages.</>}>
<ul className="divide-y divide-gray-100"> <ul className="divide-y divide-gray-100">
{design.home.map((e, i) => { {design.home.map((e, i) => {
const recommended = options.variants[design.template]?.[e.section] ?? []; const recommended = options.variants[design.template]?.[e.section] ?? [];
@@ -107,6 +118,16 @@ export default function TemplatePage() {
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}> onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}>
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)} {ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
</select> </select>
{/* The top of the page draws its own background (photo, colour or plain). */}
{e.section !== "hero" && (
<span className="flex items-center gap-2">
<span className="h-6 w-6 shrink-0 rounded border border-gray-300" style={{ background: BACKGROUNDS.find((b) => b.id === (e.background ?? ""))?.swatch }} aria-hidden />
<select aria-label={`${SECTIONS[e.section]} background`} title="Background" className={`${inputClass} w-48`} value={e.background ?? ""} disabled={busy}
onChange={(ev) => save({ home: design.home.map(({ background: _b, ...x }) => (x.section === e.section ? (ev.target.value ? { ...x, background: ev.target.value } : x) : { ...x, ...(_b ? { background: _b } : {}) })) })}>
{BACKGROUNDS.map((b) => <option key={b.id} value={b.id}>{b.id ? b.name : `Background: ${b.name.toLowerCase()}`}</option>)}
</select>
</span>
)}
<label className="flex items-center gap-2 text-sm"> <label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={!e.hidden} disabled={busy} onChange={(ev) => save({ home: design.home.map((x) => (x.section === e.section ? { ...x, hidden: !ev.target.checked } : x)) })} /> <input type="checkbox" checked={!e.hidden} disabled={busy} onChange={(ev) => save({ home: design.home.map((x) => (x.section === e.section ? { ...x, hidden: !ev.target.checked } : x)) })} />
Show Show
+30 -8
View File
@@ -59,18 +59,18 @@ h1, h2, h3 {
* Section colour: tinted alternates the church colour as a soft background; mixed adds dark bands. * 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). * 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="tinted"] .cc-section:not(.cc-own-bg):not([data-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):not([data-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; } [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):not([data-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. */ /* 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, .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); } [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):not([data-bg]):nth-of-type(3n) .cc-muted { color: rgb(255 255 255 / 0.8); }
.cc-dark .cc-link, .cc-dark .cc-eyebrow, .cc-dark .cc-brand-text, .cc-dark .cc-link, .cc-dark .cc-eyebrow, .cc-dark .cc-brand-text,
[data-template="bold"] .cc-card .cc-link, [data-template="bold"] .cc-card .cc-eyebrow, [data-template="bold"] .cc-card .cc-brand-text, [data-template="bold"] .cc-card .cc-link, [data-template="bold"] .cc-card .cc-eyebrow, [data-template="bold"] .cc-card .cc-brand-text,
[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):not([data-bg]):nth-of-type(3n) .cc-link,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-eyebrow, [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):not([data-bg]):nth-of-type(3n) .cc-eyebrow,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-brand-text { color: rgb(255 255 255); } [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):not([data-bg]):nth-of-type(3n) .cc-brand-text { color: rgb(255 255 255); }
.cc-muted { color: rgb(75 85 99); } .cc-muted { color: rgb(75 85 99); }
/* The church's colour as text (made AA on light by the palette): here, not a utility, so the dark rules above win. */ /* The church's colour as text (made AA on light by the palette): here, not a utility, so the dark rules above win. */
@@ -108,10 +108,32 @@ h1, h2, h3 {
[data-buttons="pill"] .cc-btn { border-radius: 9999px; } [data-buttons="pill"] .cc-btn { border-radius: 9999px; }
[data-template="bold"] .cc-btn { @apply uppercase tracking-wider; } [data-template="bold"] .cc-btn { @apply uppercase tracking-wider; }
/* A button on a photo or a dark band: always light on dark. */ /* 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 { .cc-on-dark .cc-btn, .cc-dark .cc-btn, [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):not([data-bg]):nth-of-type(3n) .cc-btn {
background: rgb(255 255 255); color: rgb(17 24 39); border-color: rgb(255 255 255); background: rgb(255 255 255); color: rgb(17 24 39); border-color: rgb(255 255 255);
} }
/*
* A homepage section's own background (Template → Home page), always from the church's colours.
* It replaces the Section colour's pattern for that section; a layout with its own background
* (cc-own-bg: a photo, a band) keeps it. On the main colour, text is the palette's on-brand
* colour (AA); on the deep shade, white.
*/
.cc-section[data-bg="light"]:not(.cc-own-bg) { background: rgb(255 255 255); }
.cc-section[data-bg="tint"]:not(.cc-own-bg) { background: rgb(var(--brand-tint)); }
.cc-section[data-bg="accent"]:not(.cc-own-bg) { background: rgb(var(--accent) / 0.12); }
.cc-section[data-bg="brand"]:not(.cc-own-bg) { background: rgb(var(--brand)); color: rgb(var(--on-brand)); }
.cc-section[data-bg="dark"]:not(.cc-own-bg) { background: linear-gradient(rgb(0 0 0 / 0.35), rgb(0 0 0 / 0.35)), rgb(var(--brand-dark)); color: rgb(255 255 255); }
.cc-section[data-bg="brand"]:not(.cc-own-bg) .cc-card,
.cc-section[data-bg="dark"]:not(.cc-own-bg) .cc-card { background: rgb(255 255 255 / 0.08); border-color: rgb(255 255 255 / 0.25); color: inherit; box-shadow: none; }
.cc-section[data-bg="brand"]:not(.cc-own-bg) .cc-muted { color: rgb(var(--on-brand) / 0.85); }
.cc-section[data-bg="brand"]:not(.cc-own-bg) :is(.cc-link, .cc-eyebrow, .cc-brand-text) { color: rgb(var(--on-brand)); }
.cc-section[data-bg="dark"]:not(.cc-own-bg) .cc-muted { color: rgb(255 255 255 / 0.8); }
.cc-section[data-bg="dark"]:not(.cc-own-bg) :is(.cc-link, .cc-eyebrow, .cc-brand-text) { color: rgb(255 255 255); }
.cc-section[data-bg="brand"]:not(.cc-own-bg) .cc-btn { background: rgb(var(--on-brand)); color: rgb(var(--brand)); border-color: rgb(var(--on-brand)); }
.cc-section[data-bg="dark"]:not(.cc-own-bg) .cc-btn { background: rgb(255 255 255); color: rgb(17 24 39); border-color: rgb(255 255 255); }
.cc-section[data-bg="brand"]:not(.cc-own-bg) .cc-btn:hover,
.cc-section[data-bg="dark"]:not(.cc-own-bg) .cc-btn:hover { opacity: 0.9; }
/* Cards. */ /* Cards. */
.cc-card { @apply overflow-hidden bg-white; border-radius: var(--cc-radius, 0.5rem); } .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="heritage"] .cc-card { border: 1px solid rgb(var(--brand-text) / 0.2); }
@@ -9,8 +9,9 @@ import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, Pict
import type { SectionProps, SiteEvent } from "../types"; import type { SectionProps, SiteEvent } from "../types";
import { Hero } from "./Hero"; import { Hero } from "./Hero";
const Section = ({ children, className, id }: { children: React.ReactNode; className?: string; id?: string }) => ( /** `data-bg`: the section's own background, when the church gave it one (globals.css). */
<section id={id} className={cx("cc-section", className)}>{children}</section> const Section = ({ p, children, className, id }: { p: SectionProps; children: React.ReactNode; className?: string; id?: string }) => (
<section id={id} data-bg={p.section.background} className={cx("cc-section", className)}>{children}</section>
); );
const tz = (p: SectionProps) => p.site.church?.timezone ?? "Africa/Johannesburg"; const tz = (p: SectionProps) => p.site.church?.timezone ?? "Africa/Johannesburg";
@@ -79,7 +80,7 @@ function ServiceTimes(p: SectionProps) {
if (p.section.variant === "map") { if (p.section.variant === "map") {
const geo = p.site.church?.contact.address?.geo; const geo = p.site.church?.contact.address?.geo;
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap grid items-stretch gap-8 md:grid-cols-2"> <div className="cc-wrap grid items-stretch gap-8 md:grid-cols-2">
{panel} {panel}
{geo ? ( {geo ? (
@@ -90,7 +91,7 @@ function ServiceTimes(p: SectionProps) {
</Section> </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>; return <Section p={p}><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 ──────────────── // ─── Welcome: Text · Image and text · With pastor's photo and quote ────────────────
@@ -108,7 +109,7 @@ function Welcome(p: SectionProps) {
if (p.section.variant === "pastor" && d.pastor) { if (p.section.variant === "pastor" && d.pastor) {
const photo = media(p.site, d.pastor.photoId, p.section.data); const photo = media(p.site, d.pastor.photoId, p.section.data);
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]"> <div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]">
<figure className={cx(centred && "text-center")}> <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")} /> <Img image={photo} ratio="aspect-[4/5]" className={cx(p.template === "community" && "rounded-[2rem]", centred && "mx-auto max-w-xs")} />
@@ -122,7 +123,7 @@ function Welcome(p: SectionProps) {
} }
if (p.section.variant === "image-text") { if (p.section.variant === "image-text") {
return ( return (
<Section> <Section p={p}>
<div className={cx("grid items-center gap-10 md:grid-cols-2", p.template === "bold" ? "px-0 md:gap-0" : "cc-wrap")}> <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, p.section.data)} 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")} /> <Img image={media(p.site, d.imageId, p.section.data)} 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 className={cx(p.template === "bold" && "px-6 py-10 sm:px-12")}>{words}</div>
@@ -130,7 +131,7 @@ function Welcome(p: SectionProps) {
</Section> </Section>
); );
} }
return <Section><div className="cc-wrap"><div className="cc-text">{words}</div></div></Section>; return <Section p={p}><div className="cc-wrap"><div className="cc-text">{words}</div></div></Section>;
} }
// ─── Ministries: Cards · List · Alternating bands ─────────────────────────────── // ─── Ministries: Cards · List · Alternating bands ───────────────────────────────
@@ -145,7 +146,7 @@ function Ministries(p: SectionProps) {
if (p.section.variant === "bands") { if (p.section.variant === "bands") {
return ( return (
<Section className="!pb-0"> <Section p={p} className="!pb-0">
<div className="cc-wrap">{head}</div> <div className="cc-wrap">{head}</div>
<div className={cx(p.template === "bold" ? "" : "cc-wrap space-y-10")}> <div className={cx(p.template === "bold" ? "" : "cc-wrap space-y-10")}>
{list.map((m, i) => ( {list.map((m, i) => (
@@ -165,7 +166,7 @@ function Ministries(p: SectionProps) {
} }
if (p.section.variant === "list") { if (p.section.variant === "list") {
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ul className={cx("divide-y", p.template === "heritage" ? "mx-auto max-w-2xl divide-brand-text/20" : "divide-gray-200")}> <ul className={cx("divide-y", p.template === "heritage" ? "mx-auto max-w-2xl divide-brand-text/20" : "divide-gray-200")}>
@@ -181,7 +182,7 @@ function Ministries(p: SectionProps) {
); );
} }
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ul className={cx("grid gap-6", list.length > 3 ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-3")}> <ul className={cx("grid gap-6", list.length > 3 ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-3")}>
@@ -220,7 +221,7 @@ function Team(p: SectionProps) {
); );
if (p.section.variant === "list") { if (p.section.variant === "list") {
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ul className="mx-auto max-w-2xl divide-y divide-gray-200"> <ul className="mx-auto max-w-2xl divide-y divide-gray-200">
@@ -233,7 +234,7 @@ function Team(p: SectionProps) {
if (p.section.variant === "featured") { if (p.section.variant === "featured") {
const [lead, ...rest] = people; const [lead, ...rest] = people;
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
{face(lead!, true)} {face(lead!, true)}
@@ -242,7 +243,7 @@ function Team(p: SectionProps) {
</Section> </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>; return <Section p={p}><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 ───────────────────────────── // ─── Upcoming events: Cards · List · Calendar strip ─────────────────────────────
@@ -253,7 +254,12 @@ export function EventLine({ e, timeZone }: { e: SiteEvent; timeZone: string }) {
<> <>
<time dateTime={e.startsAt} className="cc-muted block text-sm">{when}</time> <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.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>} {e.registration && e.from === "events" && (
<span className="cc-eyebrow mt-1 block text-xs">
{/* Only an event that takes registrations says "Register"; a contact-only one (or a full or closed one) has its details there. */}
{(e.registration.mode ?? "origin") === "origin" && e.registration.status === "open" ? "Register on our Events site" : "More info on our Events site"}
</span>
)}
</> </>
); );
} }
@@ -266,11 +272,11 @@ function Events(p: SectionProps) {
const head = <SectionHeading heading={d.heading ?? "Coming up"} centred={p.template === "heritage"} />; 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>; 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) { 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>; return <Section p={p}><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") { if (p.section.variant === "cards") {
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3"> <ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
@@ -294,7 +300,7 @@ function Events(p: SectionProps) {
} }
if (p.section.variant === "calendar") { if (p.section.variant === "calendar") {
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ol className="flex snap-x gap-4 overflow-x-auto pb-4"> <ol className="flex snap-x gap-4 overflow-x-auto pb-4">
@@ -314,7 +320,7 @@ function Events(p: SectionProps) {
); );
} }
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<ul className={cx("divide-y divide-gray-200", p.template === "heritage" && "mx-auto max-w-2xl")}> <ul className={cx("divide-y divide-gray-200", p.template === "heritage" && "mx-auto max-w-2xl")}>
@@ -351,7 +357,7 @@ function LatestMessage(p: SectionProps) {
); );
if (p.section.variant === "compact") { if (p.section.variant === "compact") {
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <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 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> <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>
@@ -363,7 +369,7 @@ function LatestMessage(p: SectionProps) {
} }
if (p.section.variant === "video") { if (p.section.variant === "video") {
return ( return (
<Section className={cx(p.template === "bold" && "cc-own-bg cc-dark bg-gray-950 text-white")}> <Section p={p} className={cx(p.template === "bold" && "cc-own-bg cc-dark bg-gray-950 text-white")}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} /> <MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} />
@@ -373,7 +379,7 @@ function LatestMessage(p: SectionProps) {
); );
} }
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap"> <div className="cc-wrap">
{head} {head}
<div className="cc-card grid items-center gap-0 md:grid-cols-2"> <div className="cc-card grid items-center gap-0 md:grid-cols-2">
@@ -414,7 +420,7 @@ function Invitation(p: SectionProps) {
); );
} }
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap text-center"> <div className="cc-wrap text-center">
<h2 className="cc-h2">{d.heading}</h2> <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>} {d.text && <p className="cc-muted mx-auto mt-4 max-w-2xl text-lg">{d.text}</p>}
@@ -428,13 +434,13 @@ function Invitation(p: SectionProps) {
function TextBlock(p: SectionProps) { function TextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string }; 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>; return <Section p={p}><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) { function ImageTextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData }; const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData };
return ( return (
<Section> <Section p={p}>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-2"> <div className="cc-wrap grid items-center gap-10 md:grid-cols-2">
<Img image={media(p.site, d.imageId, p.section.data)} className={cx(p.template === "community" && "rounded-[2rem]")} /> <Img image={media(p.site, d.imageId, p.section.data)} 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>{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>
@@ -446,7 +452,7 @@ function ImageTextBlock(p: SectionProps) {
function QuoteBlock(p: SectionProps) { function QuoteBlock(p: SectionProps) {
const d = p.section.data as { quote: string; by: string | null }; const d = p.section.data as { quote: string; by: string | null };
return ( return (
<Section> <Section p={p}>
<figure className="cc-wrap text-center"> <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> <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>} {str(d.by) && <figcaption className="cc-muted mt-4">{d.by}</figcaption>}
+3 -2
View File
@@ -12,7 +12,8 @@ export type Focus = { x: number; y: number; zoom: number };
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string }; focus?: Focus }; export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string }; focus?: Focus };
export type Section = { type: string; variant: string | null; data: Record<string, unknown> }; /** `background`: a homepage section's own background (light | tint | accent | brand | dark), when it has one. */
export type Section = { type: string; variant: string | null; data: Record<string, unknown>; background?: "light" | "tint" | "accent" | "brand" | "dark" };
export type Page = { export type Page = {
kind: string; kind: string;
@@ -59,7 +60,7 @@ export type SiteEvent = {
slug: string | null; slug: string | null;
link: string | null; link: string | null;
from: "website" | "events" | "app"; from: "website" | "events" | "app";
registration: { status: string; priceFromCents: number | null } | null; registration: { mode: string; status: string; priceFromCents: number | null } | null;
}; };
export type SiteMessage = { export type SiteMessage = {
+16 -6
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything # Versions — the latest release of everything
Last updated: 2026-11-30. Taken from the git tags, which is what a release is here (branch → merge → Last updated: 2026-12-01. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.** tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded "Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -10,9 +10,9 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released | | What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------| |------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.8.0** | `events@3.8.0` | 2026-11-30 | | Cross Events | `crosscode-platform` (`apps/events`) | **3.9.0** | `events@3.9.0` | 2026-12-01 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.8.0** | `website@1.8.0` | 2026-11-30 | | Church Website | `crosscode-platform` (`apps/website`) | **1.9.0** | `website@1.9.0` | 2026-12-01 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.0` | 2026-11-30 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.10.0** | `accounts@1.10.0` | 2026-12-01 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.7.0** | `agent@1.7.0` | 2026-11-30 | | Server agent | `crosscode-platform` (`apps/agent`) | **1.7.0** | `agent@1.7.0` | 2026-11-30 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.24.0** | `contracts@1.24.0` | 2026-11-30 | | Contracts | `crosscode-platform` (`packages/contracts`) | **1.24.0** | `contracts@1.24.0` | 2026-11-30 |
| Cross Code Hub | `events-hub` | **2.26.1** | `v2.26.1` | 2026-11-30 | | Cross Code Hub | `events-hub` | **2.26.1** | `v2.26.1` | 2026-11-30 |
@@ -30,8 +30,8 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) | | `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0, Events 3.8.0 and Website 1.8.0) | | `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0, Events 3.8.0 and Website 1.8.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) | | `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) | | `@crosscode/ui` | `packages/ui` | 0.4.0 (fonts, `ChurchFooter`, `ColourField`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0, 0.4.0 with Accounts 1.10.0 and Website 1.9.0) |
| Website | `apps/website` | 1.8.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28, 1.8.0 on 2026-11-30; tagged as `website@…`; see "Deployed / rolled out" for where it runs) | | Website | `apps/website` | 1.9.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28, 1.8.0 on 2026-11-30, 1.9.0 on 2026-12-01; tagged as `website@…`; see "Deployed / rolled out" for where it runs) |
| App | `apps/app` | 0.0.0 on main (a placeholder); 0.1.0 on the branch `feat/app-scaffold`, being built from 2026-12-01 (phase 6; not released, merged and tagged `app@1.0.0` when the plan is built) | | App | `apps/app` | 0.0.0 on main (a placeholder); 0.1.0 on the branch `feat/app-scaffold`, being built from 2026-12-01 (phase 6; not released, merged and tagged `app@1.0.0` when the plan is built) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -39,6 +39,16 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for ## What each latest release was for
- **Events 3.9.0 + Website 1.9.0 + Accounts 1.10.0 + `@crosscode/ui` 0.4.0 (2026-12-01):** Events
takes the church's name, logo, icon, colours and contact details from the Accounts profile
(pages, emails, WhatsApp, PDFs; Settings shows them read-only), so a change in Accounts or a
demo scenario load shows on Events as on the Website; the Accounts logo is copied for PDFs, and SVG
logos are drawn in them (`svg-to-pdfkit`). The Website gets a background per homepage section in the church's colours, and
"More info" instead of "Register" for events without registration. Accounts' Church profile and
the Website's Church details use one colour field (`ColourField`, like Events' picker). No
migrations, no contracts change, works with any Accounts. Checked: Events backend tests (828),
Website backend tests (149), typecheck and lint of every changed app. Not deployed.
- **Hub 2.26.1 + contracts 1.24.0 (2026-11-30):** Cross Code's devotionals can be scheduled up to - **Hub 2.26.1 + contracts 1.24.0 (2026-11-30):** Cross Code's devotionals can be scheduled up to
**two years ahead** (was 3 months; `CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS`), and a CSV holds two **two years ahead** (was 3 months; `CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS`), and a CSV holds two
years in one file (800 rows, 8 MB). `GET /api/v2/devotionals` answers **2 weeks, today included** years in one file (800 rows, 8 MB). `GET /api/v2/devotionals` answers **2 weeks, today included**
+18 -8
View File
@@ -51,7 +51,7 @@
}, },
"apps/accounts/backend": { "apps/accounts/backend": {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.9.0", "version": "1.10.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
@@ -89,7 +89,7 @@
}, },
"apps/accounts/frontend": { "apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.9.0", "version": "1.10.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/ui": "*", "@crosscode/ui": "*",
@@ -134,7 +134,7 @@
}, },
"apps/events/backend": { "apps/events/backend": {
"name": "@crosscode/events-backend", "name": "@crosscode/events-backend",
"version": "3.8.0", "version": "3.9.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@cj-tech-master/excelts": "^10.2.0", "@cj-tech-master/excelts": "^10.2.0",
@@ -160,6 +160,7 @@
"pg-boss": "^11.1.2", "pg-boss": "^11.1.2",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"raw-body": "^3.0.0", "raw-body": "^3.0.0",
"svg-to-pdfkit": "0.1.8",
"swagger-ui-dist": "^5.34.0", "swagger-ui-dist": "^5.34.0",
"tsx": "^4.23.15", "tsx": "^4.23.15",
"typescript": "^5.9.3", "typescript": "^5.9.3",
@@ -185,7 +186,7 @@
}, },
"apps/events/frontend": { "apps/events/frontend": {
"name": "@crosscode/events-frontend", "name": "@crosscode/events-frontend",
"version": "3.8.0", "version": "3.9.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/seo": "*", "@crosscode/seo": "*",
@@ -362,7 +363,7 @@
}, },
"apps/website/backend": { "apps/website/backend": {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.8.0", "version": "1.9.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/auth-client": "*", "@crosscode/auth-client": "*",
@@ -392,7 +393,7 @@
}, },
"apps/website/frontend": { "apps/website/frontend": {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.8.0", "version": "1.9.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/seo": "*", "@crosscode/seo": "*",
@@ -21285,6 +21286,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/svg-to-pdfkit": {
"version": "0.1.8",
"resolved": "https://registry.npmjs.org/svg-to-pdfkit/-/svg-to-pdfkit-0.1.8.tgz",
"integrity": "sha512-QItiGZBy5TstGy+q8mjQTMGRlDDOARXLxH+sgVm1n/LYeo0zFcQlcCh8m4zi8QxctrxB9Kue/lStc/RD5iLadQ==",
"license": "MIT",
"dependencies": {
"pdfkit": ">=0.8.1"
}
},
"node_modules/swagger-ui-dist": { "node_modules/swagger-ui-dist": {
"version": "5.34.0", "version": "5.34.0",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.34.0.tgz", "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.34.0.tgz",
@@ -23192,7 +23202,7 @@
}, },
"packages/contracts": { "packages/contracts": {
"name": "@crosscode/contracts", "name": "@crosscode/contracts",
"version": "1.23.0", "version": "1.24.0",
"license": "UNLICENSED", "license": "UNLICENSED",
"dependencies": { "dependencies": {
"zod": "^4.6.7" "zod": "^4.6.7"
@@ -23244,7 +23254,7 @@
}, },
"packages/ui": { "packages/ui": {
"name": "@crosscode/ui", "name": "@crosscode/ui",
"version": "0.3.0", "version": "0.4.0",
"dependencies": { "dependencies": {
"@fontsource-variable/dm-sans": "5.3.0", "@fontsource-variable/dm-sans": "5.3.0",
"@fontsource-variable/eb-garamond": "5.3.0", "@fontsource-variable/eb-garamond": "5.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/ui", "name": "@crosscode/ui",
"version": "0.3.0", "version": "0.4.0",
"private": true, "private": true,
"description": "Shared UI for the church's sign-in pages, Website and App: the branded shell, forms and buttons, the church's fonts and footer (Tailwind; apps compile the source with transpilePackages)", "description": "Shared UI for the church's sign-in pages, Website and App: the branded shell, forms and buttons, the church's fonts and footer (Tailwind; apps compile the source with transpilePackages)",
"main": "src/index.tsx", "main": "src/index.tsx",
+56
View File
@@ -97,6 +97,62 @@ export function Field({ label, error, hint, id, className, ...rest }: FieldProps
); );
} }
export const isHexColour = (v: string) => /^#[0-9a-fA-F]{6}$/.test(v.trim());
type ColourFieldProps = {
label: string;
value: string;
onChange: (hex: string) => void;
hint?: React.ReactNode;
error?: string | null;
/** For a form read with FormData: the hex is sent under this name. */
name?: string;
id?: string;
disabled?: boolean;
};
/**
* A colour: the swatch to pick it, the hex code to type or paste it, and a bar showing it, as Cross
* Events' Branding settings. Controlled: `value` is what's typed, so it can be half-typed; it's a
* colour once it reads `#rrggbb` (`isHexColour`), and says so when it doesn't.
*/
export function ColourField({ label, value, onChange, hint, error, name, id, disabled }: ColourFieldProps) {
const fieldId = id ?? `f-${label.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
const valid = isHexColour(value);
const problem = error || (valid ? null : "Enter a colour code like #1f4e79.");
return (
<div className="mb-4">
<label htmlFor={fieldId} className="mb-1 block text-sm font-medium text-gray-800">{label}</label>
<div className="flex items-center gap-3">
<input
type="color"
aria-label={`${label}: pick`}
disabled={disabled}
className="h-10 w-20 shrink-0 cursor-pointer rounded-[var(--cc-radius-sm,0.5rem)] border border-gray-300 bg-white p-1 disabled:cursor-not-allowed"
value={valid ? value.trim().toLowerCase() : "#000000"}
onChange={(e) => onChange(e.target.value)}
/>
<input
id={fieldId}
name={name}
disabled={disabled}
spellCheck={false}
autoComplete="off"
placeholder="#1f4e79"
aria-invalid={!!problem}
aria-describedby={problem ? `${fieldId}-error` : undefined}
className={cx("w-full rounded-[var(--cc-radius-sm,0.5rem)] border px-3 py-2.5 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-brand/50", problem ? "border-red-500" : "border-gray-300")}
value={value}
onChange={(e) => onChange(e.target.value)}
/>
</div>
<div className="mt-2 h-6 rounded-[var(--cc-radius-sm,0.5rem)] border border-gray-200 transition-colors" style={{ background: valid ? value.trim() : "#f1f5f9" }} aria-hidden />
{hint && !problem && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
{problem && <p id={`${fieldId}-error`} className="mt-1 text-sm text-red-700">{problem}</p>}
</div>
);
}
export function Checkbox({ label, hint, ...rest }: React.InputHTMLAttributes<HTMLInputElement> & { label: React.ReactNode; hint?: React.ReactNode }) { export function Checkbox({ label, hint, ...rest }: React.InputHTMLAttributes<HTMLInputElement> & { label: React.ReactNode; hint?: React.ReactNode }) {
return ( return (
<label className="mb-3 flex items-start gap-3 text-sm"> <label className="mb-3 flex items-start gap-3 text-sm">