Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50bce1928e | ||
|
|
777b045053 | ||
|
|
43187513d7 | ||
|
|
35c4dd6915 | ||
|
|
b9b2cadcd3 | ||
|
|
f5f778f0d7 | ||
|
|
a38468ba47 | ||
|
|
8b1d1da5a9 | ||
|
|
101248195f | ||
|
|
805967a85a | ||
|
|
8055e1ec62 | ||
|
|
799c193fe1 | ||
|
|
f651ae2530 | ||
|
|
74dee881e4 | ||
|
|
969d0110a1 |
@@ -2,6 +2,55 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## website@1.12.0 - 2026-12-01
|
||||
|
||||
Layouts for the pages that list something (Joshua, 2026-12-01). No migration, no contracts change.
|
||||
|
||||
- **Website 1.12.0:** the Ministries, Leadership, Events, Messages and Contact pages each have
|
||||
three layouts (`PAGE_VARIANTS`), kept in the design beside the homepage sections', with a
|
||||
suggestion per template; a site saved before keeps how its pages looked until it picks one.
|
||||
- Checked: the Website backend tests (156, five new), the frontend's typecheck and lint, and the
|
||||
new `page-layouts` e2e suite (60: every layout in every template, axe at phone and desktop).
|
||||
|
||||
## website@1.11.0 - 2026-12-01
|
||||
|
||||
Layouts and backgrounds for the other pages' blocks, and a video for the top of the page
|
||||
(Joshua, 2026-12-01). **Migration** (`Section.background`, nullable). No contracts change.
|
||||
|
||||
- **Website 1.11.0:** each block has its own layout (`BLOCK_VARIANTS`: text, image and text,
|
||||
quote, call to action) and background in the church's colours; MP4 uploads (up to 20 MB, where
|
||||
it was filmed taken out) for the hero's Video layout, with a video field in the admin.
|
||||
- Checked: the Website backend tests (152, three new), the frontend's typecheck and lint, and the
|
||||
admin, variants and templates e2e suites.
|
||||
|
||||
## website@1.10.0 - 2026-12-01
|
||||
|
||||
The home page laid out from its editor, and photos that match the layout (Joshua, 2026-12-01).
|
||||
Frontend only: no migration, no contracts change.
|
||||
|
||||
- **Website 1.10.0:** each homepage section's layout, background, order and showing in Pages →
|
||||
Home (still under Template and style too); a section offers only the photo fields its layout
|
||||
shows, with a slot for each photo (1 for Photo, Video and Split, 3 for Collage, none for Text
|
||||
only), keeping photos for other layouts.
|
||||
- Checked: the Website frontend's typecheck and lint, and the admin e2e suite (13 tests, one new).
|
||||
|
||||
## 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
|
||||
|
||||
Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive.
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# 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
|
||||
|
||||
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.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
|
||||
|
||||
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"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",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
|
||||
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
|
||||
} from "lucide-react";
|
||||
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
|
||||
import { Button, Checkbox, ColourField, Field, Notice } from "@crosscode/ui";
|
||||
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
import { Card, Heading } from "@/components/Panel";
|
||||
@@ -325,6 +325,8 @@ type ChurchData = { name: string; shortName: string | null; branding: { logoUrl:
|
||||
function Church({ flash }: { flash: Flash }) {
|
||||
const [c, setC] = useState<ChurchData | null>(null);
|
||||
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(() => {
|
||||
let alive = true;
|
||||
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")) } },
|
||||
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="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"]} />
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
|
||||
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<ColourField label="Main colour" name="primary" value={colours.primary ?? c.branding.colours.primary} onChange={(primary) => setColours((x) => ({ ...x, primary }))}
|
||||
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>
|
||||
<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"]} />
|
||||
|
||||
@@ -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/),
|
||||
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
|
||||
|
||||
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
|
||||
|
||||
@@ -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".
|
||||
-->
|
||||
|
||||
## 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
|
||||
|
||||
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
@@ -45,6 +45,7 @@
|
||||
"pg-boss": "^11.1.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"raw-body": "^3.0.0",
|
||||
"svg-to-pdfkit": "0.1.8",
|
||||
"swagger-ui-dist": "^5.34.0",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3",
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
|
||||
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
|
||||
* social, the church's other sites). Accounts owns it and serves it publicly at
|
||||
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9). Accounts owns
|
||||
* it and serves it publicly at `GET /api/church/v1`; this keeps a copy in memory for the public
|
||||
* pages (`GET /api/v2/church`: the brand style and the shared footer).
|
||||
*
|
||||
* 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`
|
||||
* (`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 { 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 RETRY_MS = 60e3;
|
||||
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 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> {
|
||||
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}`);
|
||||
@@ -36,7 +66,12 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
} catch {
|
||||
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;
|
||||
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!pending) {
|
||||
@@ -44,10 +79,14 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
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;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
cached = { url, church: last, at: Date.now(), ok: false };
|
||||
setAccountsOverrides(churchSettings(last));
|
||||
return last;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
@@ -55,13 +94,23 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
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 {
|
||||
if (cached) cached = { ...cached, at: 0 };
|
||||
churchProfile().catch(() => {});
|
||||
}
|
||||
|
||||
/** Tests: start with nothing. */
|
||||
export function resetChurchProfile(): void {
|
||||
cached = null;
|
||||
pending = null;
|
||||
setAccountsOverrides({});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ import type { ChurchLook } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
|
||||
/* 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 */
|
||||
|
||||
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
|
||||
// @route GET /api/settings
|
||||
// @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) => {
|
||||
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 = {};
|
||||
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);
|
||||
} catch (e) {
|
||||
res.status(500).json({ message: safeErrorMessage(e) });
|
||||
@@ -79,6 +90,11 @@ const getAllSettings = async (req, res) => {
|
||||
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);
|
||||
} catch (e) {
|
||||
res.status(500).json({ message: safeErrorMessage(e) });
|
||||
@@ -96,7 +112,7 @@ const updateSettings = async (req, res) => {
|
||||
}
|
||||
|
||||
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]) => {
|
||||
let storedValue = String(value);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const PDFDocument = require('pdfkit');
|
||||
const QRCode = require('qrcode');
|
||||
const { drawLogo } = require('./logoCopy');
|
||||
const prisma = require('../config/db');
|
||||
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(28, 0, 6, H).fill(lighten(color, 0.6));
|
||||
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-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);
|
||||
@@ -202,7 +203,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
if (template === 'church') {
|
||||
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();
|
||||
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;
|
||||
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' });
|
||||
@@ -228,7 +229,7 @@ function drawTemplate(doc, template, ctx) {
|
||||
const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260);
|
||||
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(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' });
|
||||
@@ -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]]) {
|
||||
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-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' });
|
||||
|
||||
@@ -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 };
|
||||
@@ -55,11 +55,8 @@ async function getBranding() {
|
||||
getSetting('logo_url', ''),
|
||||
]);
|
||||
const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
||||
let logoPath = null;
|
||||
if (logoUrl) {
|
||||
const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, ''));
|
||||
if (fs.existsSync(p)) logoPath = p;
|
||||
}
|
||||
// An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js).
|
||||
const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl);
|
||||
return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath };
|
||||
}
|
||||
|
||||
@@ -196,7 +193,7 @@ async function generateReceiptPdf(payment) {
|
||||
const bannerH = 150;
|
||||
doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor);
|
||||
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.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');
|
||||
let sy = 40;
|
||||
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) });
|
||||
sy += 60;
|
||||
|
||||
@@ -17,9 +17,37 @@ let _cache = {};
|
||||
let _lastFetch = 0;
|
||||
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() {
|
||||
const now = Date.now();
|
||||
if (now - _lastFetch < TTL_MS && _lastFetch > 0) return;
|
||||
refreshChurchProfile();
|
||||
try {
|
||||
const rows = await prisma.appSetting.findMany();
|
||||
const fresh = {};
|
||||
@@ -38,6 +66,13 @@ async function refreshIfStale() {
|
||||
* @returns {string}
|
||||
*/
|
||||
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 raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || '');
|
||||
if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) {
|
||||
@@ -76,4 +111,10 @@ function invalidate() {
|
||||
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(() => {
|
||||
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++;
|
||||
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
|
||||
const next = answers.shift() ?? 200;
|
||||
if (next === 'down') throw new Error('connect ECONNREFUSED');
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -26,6 +26,7 @@ import { errorMessage } from "@/lib/utils";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
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";
|
||||
|
||||
@@ -48,7 +49,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
];
|
||||
|
||||
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. */
|
||||
function googleVerificationCode(input: string): string {
|
||||
@@ -56,6 +57,20 @@ function googleVerificationCode(input: string): string {
|
||||
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's {what} come from its church profile in Accounts, so every one of its sites shows the same.
|
||||
They can'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({
|
||||
label, hint, required, children,
|
||||
}: {
|
||||
@@ -146,6 +161,14 @@ function SiteSettingsPageInner() {
|
||||
const [faviconPreview, setFaviconPreview] = useState<string | null>(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 ──
|
||||
const [notifEmails, setNotifEmails] = useState("");
|
||||
|
||||
@@ -206,6 +229,7 @@ function SiteSettingsPageInner() {
|
||||
setLegalEffectiveDate(s.legal_effective_date || "");
|
||||
setConsentRetentionDays(s.consent_medical_retention_days || "30");
|
||||
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" }))
|
||||
.finally(() => setLoadingInitial(false));
|
||||
@@ -220,7 +244,7 @@ function SiteSettingsPageInner() {
|
||||
setSaving(true);
|
||||
setResult(null);
|
||||
try {
|
||||
await apiV2Data("put", "/settings", { authToken: token, body: updates });
|
||||
await apiV2Data("put", "/settings", { authToken: token, body: ownOnly(updates) });
|
||||
setResult({ ok: true, message: "Saved." });
|
||||
reloadSettings();
|
||||
} catch (e) {
|
||||
@@ -271,13 +295,13 @@ function SiteSettingsPageInner() {
|
||||
|
||||
await apiV2Data("put", "/settings", {
|
||||
authToken: token,
|
||||
body: {
|
||||
body: ownOnly({
|
||||
primary_color: primaryColor,
|
||||
secondary_color: secondaryColor,
|
||||
accent_color: accentColor,
|
||||
logo_url: finalLogoUrl,
|
||||
favicon_url: finalFaviconUrl,
|
||||
},
|
||||
}),
|
||||
});
|
||||
setLogoUrl(finalLogoUrl);
|
||||
setLogoFile(null);
|
||||
@@ -303,13 +327,13 @@ function SiteSettingsPageInner() {
|
||||
try {
|
||||
await apiV2Data("put", "/settings", {
|
||||
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");
|
||||
setAccentColor("#EC4899");
|
||||
setLogoUrl(""); setLogoFile(null); setLogoPreview(null);
|
||||
setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null);
|
||||
if (!fromAccounts("accent_color")) setAccentColor("#EC4899");
|
||||
if (!fromAccounts("logo_url")) { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); }
|
||||
if (!fromAccounts("favicon_url")) { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); }
|
||||
setSuggestedColors([]);
|
||||
setResult({ ok: true, message: "Reset to defaults." });
|
||||
reloadSettings();
|
||||
@@ -433,9 +457,10 @@ function SiteSettingsPageInner() {
|
||||
{activeTab === "organisation" && (
|
||||
<div className="space-y-4">
|
||||
<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>
|
||||
<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 label="Tagline">
|
||||
<input className={inputCls} placeholder="Connecting community through events"
|
||||
@@ -444,16 +469,16 @@ function SiteSettingsPageInner() {
|
||||
<div className="grid sm:grid-cols-2 gap-4">
|
||||
<Field label="Contact email">
|
||||
<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 label="Phone">
|
||||
<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>
|
||||
</div>
|
||||
<Field label="Address" hint="Used as the default location for new events.">
|
||||
<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() && (
|
||||
<a href={mapsSearchUrl(orgAddress.trim())} target="_blank" rel="noopener noreferrer"
|
||||
className="inline-block text-xs text-brand-600 hover:underline mt-1">
|
||||
@@ -477,14 +502,15 @@ function SiteSettingsPageInner() {
|
||||
{activeTab === "branding" && (
|
||||
<div className="space-y-5">
|
||||
<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">
|
||||
<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."
|
||||
value={secondaryColor} onChange={setSecondaryColor} />
|
||||
<ColorPickerField label="Accent" hint="Hover states and highlight chips/badges."
|
||||
value={accentColor} onChange={setAccentColor} />
|
||||
value={accentColor} onChange={setAccentColor} disabled={fromAccounts("accent_color")} />
|
||||
</div>
|
||||
|
||||
<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">
|
||||
{/* 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" />
|
||||
<button
|
||||
{!fromAccounts("logo_url") && <button
|
||||
type="button"
|
||||
className="text-xs text-red-500 hover:text-red-700"
|
||||
onClick={() => { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); setSuggestedColors([]); if (fileRef.current) fileRef.current.value = ""; }}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</button>}
|
||||
</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 && (
|
||||
<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>
|
||||
@@ -524,21 +550,21 @@ function SiteSettingsPageInner() {
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
{/* 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" />
|
||||
<button
|
||||
{!fromAccounts("favicon_url") && <button
|
||||
type="button"
|
||||
className="text-xs text-red-500 hover:text-red-700"
|
||||
onClick={() => { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (faviconRef.current) faviconRef.current.value = ""; }}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</button>}
|
||||
</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];
|
||||
if (!file) return;
|
||||
setFaviconFile(file);
|
||||
setFaviconPreview(URL.createObjectURL(file));
|
||||
}} className="text-sm" />
|
||||
}} className="text-sm" />}
|
||||
</Field>
|
||||
|
||||
<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. */
|
||||
export function ColorPickerField({
|
||||
label, hint, value, onChange,
|
||||
label, hint, value, onChange, disabled,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
value: string;
|
||||
onChange: (hex: string) => void;
|
||||
/** Set elsewhere (the church profile in Accounts): shown, not changed here. */
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const valid = isValidHex(value);
|
||||
return (
|
||||
@@ -19,13 +21,15 @@ export function ColorPickerField({
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
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"}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
/>
|
||||
<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"
|
||||
disabled={disabled}
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -52,15 +52,18 @@ function computeApiBase(): string {
|
||||
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.
|
||||
// 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 {
|
||||
const raw = (urlOrPath || "").trim();
|
||||
if (!raw) return null;
|
||||
try {
|
||||
if (raw.startsWith("http")) {
|
||||
const u = new URL(raw);
|
||||
const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname);
|
||||
if (isLocal && API_BASE) {
|
||||
const isLocal = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
|
||||
const ownUpload = /^\/(api\/)?uploads\//.test(u.pathname);
|
||||
if (isLocal && ownUpload && API_BASE) {
|
||||
const api = new URL(API_BASE);
|
||||
u.protocol = api.protocol;
|
||||
u.hostname = api.hostname;
|
||||
|
||||
@@ -1,5 +1,106 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [1.12.0] — 2026-12-01
|
||||
|
||||
No migration (the layouts live in `SiteDesign.variants`). No new environment settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **Listing page layouts** (`PAGE_VARIANTS` in `src/site/variants.ts`), three per page:
|
||||
`ministriesPage` `alternating` · `cards` · `list`; `leadershipPage` `grid` · `featured` · `list`;
|
||||
`eventsPage` `list` · `cards` · `months`; `messagesPage` `grid` · `featured` · `list`;
|
||||
`contactPage` `columns` · `map` · `cards`. They sit beside the homepage sections' in the design
|
||||
(`PUT /design { variants: { eventsPage: "months" } }`), so each template recommends some, starts
|
||||
a new site on the first (its suggestion), and a template switch moves an untouched one to the
|
||||
new template's suggestion. A design saved before them has none: `cleanDesign` gives it
|
||||
`LEGACY_PAGE_LAYOUTS` (how the pages looked until now), so nothing changes until a church picks
|
||||
one; a snapshot without them is drawn the same way. `contactPage` `map` without a place on the
|
||||
map draws as `columns`.
|
||||
- **Admin:** a listing page's editor (Pages) has its Layout, the template's suggestion marked; and
|
||||
Template and style has an **Other pages** tab with all five.
|
||||
- `e2e/page-layouts.spec.ts`: every page layout in every template answers and passes axe at phone
|
||||
and desktop width (`PAGE_SHOTS=<folder>` saves screenshots).
|
||||
|
||||
## [1.11.0] — 2026-12-01
|
||||
|
||||
**Migration** `20261201000000_block_background` (adds the nullable `Section.background`; nothing
|
||||
to fill in). No new environment settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **Block layouts** (`BLOCK_VARIANTS` in `src/site/variants.ts`): text `standard` · `centred`;
|
||||
image and text `image-left` · `image-right` · `image-above`; quote `centred` · `line`; call to
|
||||
action `centred` · `banner`. Stored on the block (`Section.variant`, which blocks had but never
|
||||
used); `PUT /pages/:id/blocks/:sid` refuses an id that isn't the type's. The snapshot draws an
|
||||
unknown or missing one as the type's default (`blockVariant`), which is how every block looked
|
||||
before, so nothing changes until a church picks one. The demo's image-and-text block had the id
|
||||
`image-text`; it's now `image-left`.
|
||||
- **A block's own background** (`Section.background`, one of `SECTION_BACKGROUNDS` or null), set
|
||||
with the same endpoint and carried to the snapshot's section, where the site draws it as the
|
||||
homepage's (`data-bg`). The published source lists it only when set, so earlier versions compare
|
||||
equal; Discard and Restore put it back.
|
||||
- **Videos in the media library:** `POST /media` takes an MP4 (sniffed by its `ftyp` box) up to
|
||||
20 MB (`MAX_VIDEO_BYTES`, under the installers' nginx `client_max_body_size 25m`) and keeps it
|
||||
as uploaded, with no other sizes, counted towards storage. QuickTime (`.mov`) is refused with a
|
||||
message to export MP4. Its metadata boxes (`udta`, `meta`, `uuid` in the file and its tracks)
|
||||
are turned into `free` boxes of the same size, zeroed (`cleanVideo`), so where it was filmed is
|
||||
gone and the offsets to the frames hold. Width and height come from the first track's `tkhd`.
|
||||
`GET /media` lists each item's `mime`.
|
||||
- **Admin:** a block, when open, has its Layout and Background (saved straight away); the hero has
|
||||
a Video field for the Video layout, which only offers videos (photo fields only offer photos);
|
||||
the media library shows videos and takes them.
|
||||
|
||||
### Changed
|
||||
|
||||
- A request larger than the upload limit says so ("photos can be up to 15 MB and videos up to 20
|
||||
MB") instead of "That request isn't valid."
|
||||
|
||||
## [1.10.0] — 2026-12-01
|
||||
|
||||
No migration, no new environment settings, no backend change.
|
||||
|
||||
### Added
|
||||
|
||||
- **The home page's layouts in its editor** (Pages → Home): each section's layout and background
|
||||
when it's open, and move up, move down and show or hide on its header. They save straight to
|
||||
the design (`PUT /design`), as under Template and style → Home page layout, which keeps them too;
|
||||
the preview reloads on either a page or a design change. The layout and background lists are
|
||||
shared in `frontend/src/admin/layouts.ts`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A section's photo fields follow its layout.** `DataForm` takes the section's `layout`; a
|
||||
field's `layouts` limits it to some (Welcome's photo: Image and text; its pastor: With pastor;
|
||||
the Invitation's photo: Image background), and a photo list's `count` gives a slot for each photo
|
||||
the layout shows, chosen or not (the hero: 1 for Photo, Video and Split, 3 for Collage, none for
|
||||
Text only). Photos past the slots stay saved for a layout that shows more.
|
||||
- The e2e test opens the hero with `/^Top of the page/` (the new buttons' names contain it), and a
|
||||
new test covers the layout, background, order and showing from the editor.
|
||||
|
||||
## [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
|
||||
|
||||
No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by
|
||||
|
||||
@@ -3,6 +3,51 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.12.0
|
||||
|
||||
- **Choose how your Ministries, Leadership, Events, Messages and Contact pages look.** Each has
|
||||
three layouts: ministries as alternating photo and text, cards, or a list with small photos;
|
||||
your team as a grid of faces, with the lead pastor first, or a list; events as a list, cards
|
||||
with photos, or grouped by month; messages as a grid of videos, the latest first then a list,
|
||||
or a list; contact details in two columns, with a map, or as cards. Your template suggests one
|
||||
for each page. Choose it at the top of the page in **Pages**, or all five together under
|
||||
**Template and style → Other pages**. Your pages look the same as before until you choose.
|
||||
|
||||
## 1.11.0
|
||||
|
||||
- **Layouts and backgrounds for the blocks on your other pages.** Open a block in **Pages** to
|
||||
choose how it looks: text standard or centred; a photo on the left, on the right or above the
|
||||
text; a quote centred or with a line beside it; a call to action centred or as a banner in your
|
||||
colour. Each block can also have its own background in your church's colours, like the home
|
||||
page's sections.
|
||||
- **A video for the top of your home page.** Choose the **Video** layout and upload a short MP4
|
||||
clip (up to 20 MB; 10 to 20 seconds is plenty). It plays muted, on a loop, over your still
|
||||
photo; phones and visitors who prefer less motion see the still photo. Like photos, the place a
|
||||
video was filmed is taken out of it when you upload it.
|
||||
|
||||
## 1.10.0
|
||||
|
||||
- **Lay out your home page while you edit it.** In **Pages → Home**, open a section to choose its
|
||||
layout and background right there. Use the arrows to move a section up or down, and the eye to
|
||||
show or hide it. No more switching back and forth to **Template and style** (it still has the
|
||||
same settings, if you prefer it there).
|
||||
- **The photos match the layout.** A section now asks for exactly the photos its layout shows: one
|
||||
for Photo and Split, three for Collage, none for Text only. The Welcome's photo and the pastor's
|
||||
photo and quote, and the Invitation's background photo, only appear for the layouts that use
|
||||
them. Photos you added for another layout are kept, so switching back brings them back.
|
||||
|
||||
## 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
|
||||
|
||||
- Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.12.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- A block's own background, in the church's colours (Website 1.11.0).
|
||||
ALTER TABLE "Section" ADD COLUMN "background" TEXT;
|
||||
@@ -81,7 +81,8 @@ model Page {
|
||||
}
|
||||
|
||||
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
|
||||
/// is one of that type's ids. Content is never tied to a template (§2).
|
||||
/// is one of that type's ids (a homepage section's is on the design; a block's, BLOCK_VARIANTS, here).
|
||||
/// Content is never tied to a template (§2).
|
||||
model Section {
|
||||
id String @id @default(uuid())
|
||||
pageId String
|
||||
@@ -90,6 +91,9 @@ model Section {
|
||||
variant String?
|
||||
position Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
/// A block's own background (variants.ts SECTION_BACKGROUNDS), or null to follow the style.
|
||||
/// Homepage sections keep theirs on the design's home entries instead.
|
||||
background String?
|
||||
data Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.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 { BLOCK_VARIANTS, BUTTONS, IMAGE_TREATMENTS, isLayoutKey, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
@@ -55,7 +55,7 @@ export async function getDesign(ctx: Ctx) {
|
||||
const designPatch = z.object({
|
||||
template: websiteTemplateSchema.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({
|
||||
sectionColour: z.enum(SECTION_COLOURS).optional(),
|
||||
spacing: z.enum(SPACINGS).optional(),
|
||||
@@ -76,7 +76,7 @@ export async function saveDesign(ctx: Ctx, body: unknown, by: Who) {
|
||||
let moved: { what: string; from: string; to: string }[] = [];
|
||||
if (patch.template && patch.template !== design.template) ({ design, changes: moved } = switchTemplate(design, patch.template));
|
||||
for (const [section, variant] of Object.entries(patch.variants ?? {})) {
|
||||
if (!SECTION_TYPES.includes(section as SectionType) || !isVariant(section as SectionType, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
|
||||
if (!isLayoutKey(section) || !isVariant(section, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
|
||||
(design.variants as Record<string, string>)[section] = variant;
|
||||
}
|
||||
if (patch.home) {
|
||||
@@ -182,7 +182,8 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
|
||||
/** A block's change: its data, its layout (one of its type's BLOCK_VARIANTS), whether it shows, its own background (null follows the style). */
|
||||
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional(), background: z.enum(SECTION_BACKGROUNDS).nullable().optional() });
|
||||
|
||||
/** The blocks of any other page: add, change, move, remove. */
|
||||
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
|
||||
@@ -203,7 +204,20 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod
|
||||
const patch = check(blockPatch, body);
|
||||
await notChangedSince(ctx, s, body, by);
|
||||
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
|
||||
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
|
||||
const layouts = (BLOCK_VARIANTS as Record<string, readonly string[]>)[s.type] ?? [];
|
||||
if (patch.variant && !layouts.includes(patch.variant)) {
|
||||
throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` });
|
||||
}
|
||||
await ctx.db.section.update({
|
||||
where: { id: sectionId },
|
||||
data: {
|
||||
...(data !== undefined ? { data: data as never } : {}),
|
||||
...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}),
|
||||
...(patch.variant !== undefined ? { variant: patch.variant } : {}),
|
||||
...(patch.background !== undefined ? { background: patch.background } : {}),
|
||||
updatedBy: by.id,
|
||||
},
|
||||
});
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
@@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js';
|
||||
import { mediaUrl } from '../site/snapshot.js';
|
||||
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
/**
|
||||
* A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it
|
||||
* stays under the installers' nginx `client_max_body_size 25m`.
|
||||
*/
|
||||
export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
|
||||
/** The most the upload route reads, photo or video. */
|
||||
export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES);
|
||||
|
||||
type Kind = { ext: string; mime: string };
|
||||
|
||||
/** What the bytes are, whatever the name says. */
|
||||
export function sniff(b: Buffer): Kind | null {
|
||||
// An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out:
|
||||
// browsers other than Safari often can't play it.
|
||||
if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' };
|
||||
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
|
||||
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
|
||||
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
|
||||
@@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa
|
||||
|
||||
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
|
||||
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
|
||||
const kind = sniff(body);
|
||||
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
|
||||
if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by);
|
||||
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
|
||||
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.');
|
||||
const s = await storage(ctx);
|
||||
if (s.usedBytes + body.length > s.limitBytes) {
|
||||
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
|
||||
@@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
return { ...row, url: mediaUrl(row.filename) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the
|
||||
* site plays it as it is. Counted towards storage like a photo.
|
||||
*/
|
||||
async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) {
|
||||
if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.');
|
||||
if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.');
|
||||
const clean = cleanVideo(body);
|
||||
if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.');
|
||||
const s = await storage(ctx);
|
||||
if (s.usedBytes + clean.bytes.length > s.limitBytes) {
|
||||
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
|
||||
}
|
||||
const now = ctx.now();
|
||||
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`;
|
||||
const dir = uploadDir(ctx);
|
||||
await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true });
|
||||
await fs.writeFile(path.join(dir, filename), clean.bytes);
|
||||
const row = await ctx.db.mediaAsset.create({
|
||||
data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by },
|
||||
});
|
||||
return { ...row, url: mediaUrl(row.filename) };
|
||||
}
|
||||
|
||||
/** Boxes that hold a video's own boxes, which are searched for metadata. */
|
||||
const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']);
|
||||
/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */
|
||||
const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']);
|
||||
|
||||
/**
|
||||
* An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was
|
||||
* filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so
|
||||
* nothing moves and the offsets to the frames stay right. Also reads the picture's size from the
|
||||
* first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video).
|
||||
*/
|
||||
export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null {
|
||||
const b = Buffer.from(input);
|
||||
let moov = false;
|
||||
let width: number | null = null;
|
||||
let height: number | null = null;
|
||||
const walk = (start: number, end: number, depth: number): boolean => {
|
||||
let i = start;
|
||||
while (i < end) {
|
||||
if (end - i < 8) return false;
|
||||
let size = b.readUInt32BE(i);
|
||||
const type = b.toString('latin1', i + 4, i + 8);
|
||||
let header = 8;
|
||||
if (size === 1) {
|
||||
if (end - i < 16) return false;
|
||||
const big = b.readBigUInt64BE(i + 8);
|
||||
if (big > BigInt(end - i)) return false;
|
||||
size = Number(big);
|
||||
header = 16;
|
||||
} else if (size === 0) size = end - i;
|
||||
if (size < header || i + size > end) return false;
|
||||
if (depth === 0 && type === 'moov') moov = true;
|
||||
if (VIDEO_METADATA.has(type)) {
|
||||
b.write('free', i + 4, 'latin1');
|
||||
b.fill(0, i + header, i + size);
|
||||
} else if (VIDEO_CONTAINERS.has(type)) {
|
||||
if (!walk(i + header, i + size, depth + 1)) return false;
|
||||
} else if (type === 'tkhd' && width === null) {
|
||||
const v1 = b[i + header] === 1;
|
||||
const at = i + header + (v1 ? 88 : 76);
|
||||
if (at + 8 <= i + size) {
|
||||
const w = b.readUInt32BE(at) >>> 16;
|
||||
const h = b.readUInt32BE(at + 4) >>> 16;
|
||||
if (w > 0 && h > 0) [width, height] = [w, h];
|
||||
}
|
||||
}
|
||||
i += size;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!walk(0, b.length, 0) || !moov) return null;
|
||||
return { bytes: b, width, height };
|
||||
}
|
||||
|
||||
export const MAX_WIDTH = 2400;
|
||||
export const WIDTHS = [480, 960, 1600] as const;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
|
||||
import { publishOn, syncLink } from '../feed/feed.js';
|
||||
import { connectTo, disconnectFrom } from '../links/connect.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
|
||||
import { deleteMedia, MAX_BODY_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
|
||||
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
|
||||
import { maintenanceRouter } from './maintenance.js';
|
||||
|
||||
@@ -97,10 +97,10 @@ export function adminRouter(ctx: Ctx) {
|
||||
// ─── Media library and storage ───
|
||||
r.get('/media', handle(async () => {
|
||||
const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]);
|
||||
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
|
||||
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), mime: m.mime, alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
|
||||
}));
|
||||
r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
|
||||
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_BODY_BYTES + 1 }), handle((req) =>
|
||||
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
|
||||
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
|
||||
r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req))));
|
||||
|
||||
@@ -108,6 +108,8 @@ export function createApp(ctx: Ctx) {
|
||||
if (err instanceof ApiError) return sendError(res, err);
|
||||
const e = err as { type?: string; status?: number };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
// Only an upload is ever this large (express.raw's limit on POST /media).
|
||||
if (e?.type === 'entity.too.large') return sendError(res, new ApiError(413, 'TOO_LARGE', 'That file is too large: photos can be up to 15 MB and videos up to 20 MB. Make it smaller and try again.'));
|
||||
// A missing upload (express.static), or another known client error.
|
||||
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
|
||||
return sendError(res, err);
|
||||
|
||||
@@ -26,7 +26,7 @@ import { demoChurch, demoParts, demoPeople } from '@crosscode/demo';
|
||||
import { markRemoved, notifyLinks, syncLink, type SyncResult } from '../feed/feed.js';
|
||||
import type { SectionData } from '../site/sections.js';
|
||||
import { publish } from '../site/snapshot.js';
|
||||
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js';
|
||||
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, LAYOUT_KEYS, defaultDesign, type SiteDesign } from '../site/variants.js';
|
||||
import { MAX_WIDTH, WIDTHS, processImage, type Sizes } from '../admin/media.js';
|
||||
import { DEMO_SEEDS, type DemoPhotos, type DemoSeed, type ProfileSeed } from './seeds.js';
|
||||
|
||||
@@ -250,7 +250,7 @@ const CLASSIC: Omit<DemoSeed, 'template'> & { pastorName: string; ctaText: strin
|
||||
export function seedDesign(template: WebsiteTemplate, alternate: boolean): SiteDesign {
|
||||
const design = defaultDesign(template);
|
||||
if (!alternate) return design;
|
||||
const variants = Object.fromEntries(SECTION_TYPES.map((s) => {
|
||||
const variants = Object.fromEntries(LAYOUT_KEYS.map((s) => {
|
||||
const options = TEMPLATE_VARIANTS[template][s] as readonly string[];
|
||||
return [s, options[1] ?? options[0]!];
|
||||
})) as SiteDesign['variants'];
|
||||
@@ -333,7 +333,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
|
||||
{
|
||||
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
|
||||
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
|
||||
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } },
|
||||
{ type: 'image-text', variant: 'image-left', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } },
|
||||
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -26,7 +26,8 @@ export type SiteEvent = {
|
||||
/** An outside link for more information or signing up (the Website's own events). */
|
||||
link: string | null;
|
||||
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 = {
|
||||
@@ -147,7 +148,7 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
return [{
|
||||
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
|
||||
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, 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];
|
||||
});
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
|
||||
@@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { parseSectionData } from './sections.js';
|
||||
import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js';
|
||||
import { blockVariant, defaultDesign, isSectionBackground, isVariant, LAYOUT_KEYS, LEGACY_PAGE_LAYOUTS, PAGE_LAYOUT_KEYS, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type LayoutKey, type SectionBackground, type SectionType, type SiteDesign } from './variants.js';
|
||||
|
||||
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 };
|
||||
|
||||
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
|
||||
/** `background`: a homepage section's or block'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 = {
|
||||
kind: string;
|
||||
@@ -83,11 +84,17 @@ export function cleanDesign(saved: { template: string; variants: unknown; home:
|
||||
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
|
||||
const base = defaultDesign(template);
|
||||
if (!saved) return base;
|
||||
const variants = { ...base.variants } as Record<SectionType, string>;
|
||||
const variants = { ...base.variants } as Record<LayoutKey, string>;
|
||||
const v = (saved.variants ?? {}) as Record<string, unknown>;
|
||||
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
|
||||
// A design from before the listing pages had layouts keeps how they looked (LEGACY_PAGE_LAYOUTS).
|
||||
if (!PAGE_LAYOUT_KEYS.some((k) => k in v)) Object.assign(variants, LEGACY_PAGE_LAYOUTS);
|
||||
for (const s of LAYOUT_KEYS) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
|
||||
const home = Array.isArray(saved.home)
|
||||
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
|
||||
? (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;
|
||||
// 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 });
|
||||
@@ -101,7 +108,8 @@ export type Source = {
|
||||
pages: {
|
||||
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
|
||||
inNav: boolean; position: number; imageId: string | null;
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
|
||||
/** `background` only when a block has one, so versions published before it compare equal. */
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; background?: string; data: unknown }[];
|
||||
}[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[];
|
||||
@@ -128,7 +136,7 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
|
||||
pages: w.pages.map((p) => ({
|
||||
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
|
||||
position: p.position, imageId: p.imageId,
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })),
|
||||
})),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })),
|
||||
@@ -176,7 +184,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data, ...(entry.background ? { background: entry.background } : {}) });
|
||||
}
|
||||
} else {
|
||||
for (const x of p.sections) {
|
||||
@@ -184,7 +192,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
|
||||
const data = parseSectionData(x.type, x.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: x.type, variant: x.variant, data });
|
||||
sections.push({ type: x.type, variant: blockVariant(x.type, x.variant), data, ...(isSectionBackground(x.background) ? { background: x.background } : {}) });
|
||||
}
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -25,17 +25,50 @@ export const SECTION_VARIANTS = {
|
||||
} as const;
|
||||
|
||||
export type SectionType = keyof typeof SECTION_VARIANTS;
|
||||
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
|
||||
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
|
||||
export const sectionTypeSchema = z.enum(SECTION_TYPES);
|
||||
|
||||
/** Whether `variant` is one of `section`'s ids. */
|
||||
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
|
||||
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
|
||||
/**
|
||||
* The layouts of what a fixed page lists (WEBSITE-1.0-PLAN §6: ministries, leaders, events,
|
||||
* messages, contact details), keyed `<page kind>Page` so they sit beside the homepage sections' in
|
||||
* the design (`variants.ministriesPage = "cards"`). Like those, every template draws every one, a
|
||||
* template recommends some and starts with the first, and **an id never changes or goes away**.
|
||||
*/
|
||||
export const PAGE_VARIANTS = {
|
||||
ministriesPage: ['alternating', 'cards', 'list'],
|
||||
leadershipPage: ['grid', 'featured', 'list'],
|
||||
eventsPage: ['list', 'cards', 'months'],
|
||||
messagesPage: ['grid', 'featured', 'list'],
|
||||
contactPage: ['columns', 'map', 'cards'],
|
||||
} as const;
|
||||
|
||||
export type PageLayoutKey = keyof typeof PAGE_VARIANTS;
|
||||
export const PAGE_LAYOUT_KEYS = Object.keys(PAGE_VARIANTS) as [PageLayoutKey, ...PageLayoutKey[]];
|
||||
|
||||
/**
|
||||
* What each listing page looked like before it had layouts (Website 1.11 and earlier). A design
|
||||
* saved then has no page layouts; it keeps this look rather than taking the template's suggestion
|
||||
* on its next publish, so nothing changes until the church picks one.
|
||||
*/
|
||||
export const LEGACY_PAGE_LAYOUTS: { [K in PageLayoutKey]: (typeof PAGE_VARIANTS)[K][number] } = {
|
||||
ministriesPage: 'alternating', leadershipPage: 'grid', eventsPage: 'list', messagesPage: 'grid', contactPage: 'columns',
|
||||
};
|
||||
|
||||
/** Everything with a layout in the design: the homepage sections and the listing pages. */
|
||||
const LAYOUTS = { ...SECTION_VARIANTS, ...PAGE_VARIANTS };
|
||||
export type LayoutKey = keyof typeof LAYOUTS;
|
||||
export const LAYOUT_KEYS = [...SECTION_TYPES, ...PAGE_LAYOUT_KEYS] as [LayoutKey, ...LayoutKey[]];
|
||||
export type Variant<S extends LayoutKey = LayoutKey> = (typeof LAYOUTS)[S][number];
|
||||
|
||||
export const isLayoutKey = (k: string): k is LayoutKey => (LAYOUT_KEYS as readonly string[]).includes(k);
|
||||
|
||||
/** Whether `variant` is one of `section`'s (or a listing page's) ids. */
|
||||
export function isVariant<S extends LayoutKey>(section: S, variant: string): variant is Variant<S> {
|
||||
return (LAYOUTS[section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** Per section: the default first, then the other recommended variants. */
|
||||
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
|
||||
/** Per section and listing page: the default first, then the other recommended variants. */
|
||||
type Recommendations = { [S in LayoutKey]: readonly [Variant<S>, ...Variant<S>[]] };
|
||||
|
||||
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
heritage: {
|
||||
@@ -47,6 +80,11 @@ export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['centred', 'banner'],
|
||||
ministriesPage: ['list', 'alternating'],
|
||||
leadershipPage: ['featured', 'grid'],
|
||||
eventsPage: ['list', 'months'],
|
||||
messagesPage: ['featured', 'grid'],
|
||||
contactPage: ['columns', 'map'],
|
||||
},
|
||||
bold: {
|
||||
hero: ['video', 'photo', 'split'],
|
||||
@@ -57,6 +95,11 @@ export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['video', 'card'],
|
||||
invitation: ['image', 'banner'],
|
||||
ministriesPage: ['alternating', 'cards'],
|
||||
leadershipPage: ['grid', 'featured'],
|
||||
eventsPage: ['cards', 'list'],
|
||||
messagesPage: ['featured', 'grid'],
|
||||
contactPage: ['map', 'cards'],
|
||||
},
|
||||
community: {
|
||||
hero: ['collage', 'photo', 'split'],
|
||||
@@ -67,6 +110,11 @@ export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['banner', 'image'],
|
||||
ministriesPage: ['cards', 'alternating'],
|
||||
leadershipPage: ['grid', 'featured'],
|
||||
eventsPage: ['cards', 'months'],
|
||||
messagesPage: ['grid', 'featured'],
|
||||
contactPage: ['cards', 'map'],
|
||||
},
|
||||
clean: {
|
||||
hero: ['text', 'split', 'photo'],
|
||||
@@ -77,14 +125,19 @@ export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['compact', 'card'],
|
||||
invitation: ['centred', 'banner'],
|
||||
ministriesPage: ['list', 'cards'],
|
||||
leadershipPage: ['list', 'grid'],
|
||||
eventsPage: ['list', 'months'],
|
||||
messagesPage: ['list', 'grid'],
|
||||
contactPage: ['columns', 'cards'],
|
||||
},
|
||||
};
|
||||
|
||||
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
|
||||
export function defaultVariant<S extends LayoutKey>(template: WebsiteTemplate, section: S): Variant<S> {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
|
||||
}
|
||||
|
||||
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
|
||||
export function isRecommended(template: WebsiteTemplate, section: LayoutKey, variant: string): boolean {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
@@ -104,8 +157,41 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h
|
||||
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];
|
||||
|
||||
export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v);
|
||||
|
||||
/**
|
||||
* The layouts of the other pages' blocks, the default first. Stored on the block's own row
|
||||
* (`Section.variant`); like the homepage's, **an id never changes or goes away** once released,
|
||||
* and one that isn't listed (an older row's) is drawn as the default.
|
||||
*/
|
||||
export const BLOCK_VARIANTS = {
|
||||
text: ['standard', 'centred'],
|
||||
'image-text': ['image-left', 'image-right', 'image-above'],
|
||||
quote: ['centred', 'line'],
|
||||
cta: ['centred', 'banner'],
|
||||
} as const;
|
||||
|
||||
export type BlockVariantType = keyof typeof BLOCK_VARIANTS;
|
||||
|
||||
/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */
|
||||
export function blockVariant(type: string, variant: string | null | undefined): string | null {
|
||||
const list = (BLOCK_VARIANTS as Record<string, readonly string[]>)[type];
|
||||
if (!list) return variant ?? null;
|
||||
return variant && list.includes(variant) ? variant : list[0]!;
|
||||
}
|
||||
|
||||
/** 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[] => [
|
||||
...shown.map((section) => ({ section, hidden: false })),
|
||||
@@ -146,14 +232,15 @@ const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] a
|
||||
/** The site's design: what a template switch changes. Content is never part of it. */
|
||||
export type SiteDesign = {
|
||||
template: WebsiteTemplate;
|
||||
variants: { [S in SectionType]: Variant<S> };
|
||||
/** The homepage sections' layouts and the listing pages' (PAGE_VARIANTS). */
|
||||
variants: { [S in LayoutKey]: Variant<S> };
|
||||
home: HomeEntry[];
|
||||
style: SiteStyle;
|
||||
};
|
||||
|
||||
/** A fresh site on `template`: every default. */
|
||||
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
|
||||
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
|
||||
const variants = Object.fromEntries(LAYOUT_KEYS.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
|
||||
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
|
||||
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
|
||||
}
|
||||
@@ -174,8 +261,8 @@ export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { desi
|
||||
const target = defaultDesign(to);
|
||||
const changes: DesignChange[] = [{ what: 'template', from, to }];
|
||||
|
||||
const variants = { ...current.variants } as Record<SectionType, string>;
|
||||
for (const s of SECTION_TYPES) {
|
||||
const variants = { ...current.variants } as Record<LayoutKey, string>;
|
||||
for (const s of LAYOUT_KEYS) {
|
||||
const next = target.variants[s];
|
||||
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
|
||||
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
|
||||
@@ -184,7 +271,12 @@ export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { desi
|
||||
}
|
||||
|
||||
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` });
|
||||
|
||||
const style = { ...current.style };
|
||||
|
||||
@@ -98,7 +98,7 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
|
||||
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
|
||||
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
await db.section.deleteMany({ where: { pageId: id } });
|
||||
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
|
||||
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, background: x.background ?? null, data: x.data as never, ...stamp } });
|
||||
return;
|
||||
}
|
||||
if (what === 'ministry') {
|
||||
|
||||
@@ -121,6 +121,10 @@ describe('editing, publishing, discarding, restoring (§4)', () => {
|
||||
assert.equal(r.body.design.variants.hero, 'video', 'moved to Bold\'s default');
|
||||
assert.ok(r.body.moved.some((m: { what: string }) => m.what === 'hero.variant'));
|
||||
assert.equal((await as.put('/design', { variants: { hero: 'spinning' } })).status, 400);
|
||||
const pages = await as.put('/design', { variants: { messagesPage: 'list' } });
|
||||
assert.equal(pages.status, 200, 'a listing page has a layout too');
|
||||
assert.equal(pages.body.design.variants.messagesPage, 'list');
|
||||
assert.equal((await as.put('/design', { variants: { messagesPage: 'months' } })).status, 400, "an events layout isn't a messages one");
|
||||
assert.equal((await as.put('/design', { style: { header: 'centred' } })).status, 400, 'a Heritage header on Bold');
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import request from 'supertest';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
import { previewContent, siteContent } from '../src/site/content.js';
|
||||
import { publish } from '../src/site/snapshot.js';
|
||||
import { changes, discard } from '../src/site/workingCopy.js';
|
||||
import { harness, SITE } from './support/harness.js';
|
||||
|
||||
async function site() {
|
||||
@@ -85,3 +86,42 @@ describe('an address that changed (§6)', () => {
|
||||
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
|
||||
});
|
||||
});
|
||||
|
||||
describe("a block's layout and background", () => {
|
||||
it('saves one of its own layouts and a background from the church\'s colours, previews them, and discards them', async () => {
|
||||
const { ctx, db, as } = await site();
|
||||
const page = await db.page.create({ data: { kind: 'custom', slug: 'join', title: 'Join us' } });
|
||||
const block = await db.section.create({ data: { pageId: page.id, type: 'cta', data: { heading: 'Come along', text: null, button: null } } });
|
||||
await db.section.create({ data: { pageId: page.id, type: 'text', variant: 'something-old', data: { heading: null, body: 'Hi' } } });
|
||||
await publish(ctx, { id: 'x', role: 'system' });
|
||||
|
||||
// Drawn with its type's default until it has a layout; an id it doesn't know is drawn so too.
|
||||
const shown = async () => {
|
||||
const c = await previewContent(ctx);
|
||||
assert.ok(c.mode === 'published');
|
||||
return c.snapshot.pages.find((p) => p.slug === 'join')!.sections.map((s) => ({ type: s.type, variant: s.variant, background: s.background }));
|
||||
};
|
||||
assert.deepEqual(await shown(), [{ type: 'cta', variant: 'centred', background: undefined }, { type: 'text', variant: 'standard', background: undefined }]);
|
||||
|
||||
const put = (b: object) => as('ann')('put', `/pages/${page.id}/blocks/${block.id}`, b);
|
||||
assert.equal((await put({ variant: 'banner' })).status, 200);
|
||||
assert.equal((await put({ background: 'dark' })).status, 200);
|
||||
const wrong = await put({ variant: 'image-left' });
|
||||
assert.equal(wrong.status, 400);
|
||||
assert.match(wrong.body.error.message, /isn't a layout of this block/);
|
||||
assert.equal((await put({ background: 'pink' })).status, 400);
|
||||
assert.deepEqual((await shown())[0], { type: 'cta', variant: 'banner', background: 'dark' });
|
||||
|
||||
// A change like any other: listed, and discarded back to what's published.
|
||||
const pending = (await changes(ctx)).find((c) => c.key === `page:${page.id}`);
|
||||
assert.ok(pending);
|
||||
await discard(ctx, `page:${page.id}`, { id: 'x', role: 'editor' });
|
||||
const back = await db.section.findUnique({ where: { id: block.id } });
|
||||
assert.equal(back?.background, null);
|
||||
assert.equal(back?.variant, null);
|
||||
// Back to null follows the style again.
|
||||
assert.equal((await put({ background: 'tint' })).status, 200);
|
||||
assert.equal((await put({ background: null })).status, 200);
|
||||
assert.equal((await shown())[0]!.background, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,7 +114,7 @@ describe('showing events from Cross Events (Show events from)', () => {
|
||||
if (c.mode === 'published') {
|
||||
assert.equal(c.events[0]!.title, 'Youth camp');
|
||||
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/);
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
import { cleanVideo } from '../src/admin/media.js';
|
||||
import { parseSectionData } from '../src/site/sections.js';
|
||||
import { harness, SITE } from './support/harness.js';
|
||||
|
||||
@@ -56,3 +57,71 @@ describe('framing a photo in its frame', () => {
|
||||
assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null);
|
||||
});
|
||||
});
|
||||
|
||||
/** An MP4 box: its size, its type, then what's in it. */
|
||||
const box = (type: string, ...parts: Buffer[]) => {
|
||||
const body = Buffer.concat(parts);
|
||||
const head = Buffer.alloc(8);
|
||||
head.writeUInt32BE(8 + body.length, 0);
|
||||
head.write(type, 4, 'latin1');
|
||||
return Buffer.concat([head, body]);
|
||||
};
|
||||
/** A version 0 track header for a picture `w` by `h` (16.16 fixed point at its end). */
|
||||
const tkhd = (w: number, h: number) => {
|
||||
const b = Buffer.alloc(84);
|
||||
b.writeUInt32BE(w << 16, 76);
|
||||
b.writeUInt32BE(h << 16, 80);
|
||||
return box('tkhd', b);
|
||||
};
|
||||
const PLACE = '+52.3676+004.9041/';
|
||||
/** A small MP4 filmed somewhere: where in `udta` (©xyz) and Apple's `meta`, as phones save them. */
|
||||
function mp4(brand = 'isom') {
|
||||
return Buffer.concat([
|
||||
box('ftyp', Buffer.from(`${brand}\0\0\0\0isommp42`, 'latin1')),
|
||||
box('moov',
|
||||
box('mvhd', Buffer.alloc(100)),
|
||||
box('trak', tkhd(640, 360), box('mdia', box('mdhd', Buffer.alloc(24)))),
|
||||
box('udta', box('©xyz', Buffer.from(PLACE, 'latin1'))),
|
||||
box('meta', Buffer.from(`com.apple.quicktime.location.ISO6709${PLACE}`, 'latin1'))),
|
||||
box('mdat', Buffer.from('frames go here')),
|
||||
]);
|
||||
}
|
||||
|
||||
describe('a video for the top of the page', () => {
|
||||
it('takes away where it was filmed without moving anything, and reads its size', () => {
|
||||
const v = mp4();
|
||||
const clean = cleanVideo(v)!;
|
||||
assert.equal(clean.bytes.length, v.length);
|
||||
assert.equal(clean.bytes.includes(Buffer.from(PLACE)), false);
|
||||
assert.equal(clean.bytes.includes(Buffer.from('com.apple.quicktime.location')), false);
|
||||
assert.ok(clean.bytes.includes(Buffer.from('frames go here')));
|
||||
// The frames sit where they did, so the offsets to them still hold.
|
||||
assert.equal(clean.bytes.indexOf('mdat'), v.indexOf('mdat'));
|
||||
assert.deepEqual([clean.width, clean.height], [640, 360]);
|
||||
// The upload itself isn't changed.
|
||||
assert.ok(v.includes(Buffer.from(PLACE)));
|
||||
// Boxes that don't add up, or no moov: not a video.
|
||||
assert.equal(cleanVideo(Buffer.concat([v.subarray(0, 40), Buffer.from([0, 0, 1, 0])])), null);
|
||||
assert.equal(cleanVideo(box('ftyp', Buffer.from('isom\0\0\0\0', 'latin1'))), null);
|
||||
});
|
||||
|
||||
it('uploads an MP4 to the library, and refuses QuickTime and one too large', async () => {
|
||||
const { app, db, uploads } = await site();
|
||||
const post = (b: Buffer) => request(app).post('/api/v1/admin/media?alt=People%20arriving').set('Cookie', 'ccw_session=ann').set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(b);
|
||||
const ok = await post(mp4());
|
||||
assert.equal(ok.status, 200, JSON.stringify(ok.body));
|
||||
assert.equal(ok.body.mime, 'video/mp4');
|
||||
assert.match(ok.body.url, /\.mp4$/);
|
||||
const row = await db.mediaAsset.findUnique({ where: { id: ok.body.id } });
|
||||
assert.deepEqual([row?.width, row?.height, row?.alt], [640, 360, 'People arriving']);
|
||||
const saved = await fs.readFile(path.join(uploads, String(row!.filename)));
|
||||
assert.equal(saved.includes(Buffer.from(PLACE)), false);
|
||||
|
||||
const mov = await post(mp4('qt '));
|
||||
assert.equal(mov.status, 415);
|
||||
assert.match(mov.body.error.message, /MP4/);
|
||||
const big = await post(Buffer.concat([mp4(), Buffer.alloc(20 * 1024 * 1024)]));
|
||||
assert.equal(big.status, 413);
|
||||
assert.match(big.body.error.message, /20 MB/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
messageSeries: () => ({ summary: null, imageId: null }),
|
||||
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
||||
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
||||
section: () => ({ variant: null, background: null, position: 0, hidden: false, updatedBy: null }),
|
||||
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
||||
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
|
||||
|
||||
@@ -2,9 +2,10 @@ import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import {
|
||||
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
|
||||
LEGACY_PAGE_LAYOUTS, PAGE_LAYOUT_KEYS, PAGE_VARIANTS, SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
|
||||
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
|
||||
} from '../src/site/variants.js';
|
||||
import { cleanDesign } from '../src/site/snapshot.js';
|
||||
|
||||
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
|
||||
it('has the 26 confirmed variant ids', () => {
|
||||
@@ -101,3 +102,58 @@ describe('switching template', () => {
|
||||
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('listing page layouts', () => {
|
||||
it('has at least three layouts for each listing page, and every template suggests real ones', () => {
|
||||
assert.deepEqual(PAGE_LAYOUT_KEYS, ['ministriesPage', 'leadershipPage', 'eventsPage', 'messagesPage', 'contactPage']);
|
||||
for (const k of PAGE_LAYOUT_KEYS) assert.ok(PAGE_VARIANTS[k].length >= 3, k);
|
||||
for (const t of WEBSITE_TEMPLATES) {
|
||||
for (const k of PAGE_LAYOUT_KEYS) {
|
||||
const rec = TEMPLATE_VARIANTS[t][k] as readonly string[];
|
||||
assert.ok(rec.length >= 2, `${t}.${k}`);
|
||||
assert.equal(new Set(rec).size, rec.length, `${t}.${k} repeats`);
|
||||
for (const v of rec) assert.ok(isVariant(k, v), `${t}.${k}: ${v}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("starts a new site on the template's suggestion", () => {
|
||||
assert.equal(defaultDesign('community').variants.ministriesPage, 'cards');
|
||||
assert.equal(defaultDesign('bold').variants.contactPage, 'map');
|
||||
assert.equal(defaultDesign('clean').variants.messagesPage, 'list');
|
||||
});
|
||||
|
||||
it('keeps the look a design had before page layouts, until the church picks one', () => {
|
||||
const before = cleanDesign({ template: 'community', variants: { hero: 'photo' }, home: [], style: {} });
|
||||
assert.deepEqual(PAGE_LAYOUT_KEYS.map((k) => before.variants[k]), PAGE_LAYOUT_KEYS.map((k) => LEGACY_PAGE_LAYOUTS[k]));
|
||||
const picked = cleanDesign({ template: 'community', variants: { eventsPage: 'months' }, home: [], style: {} });
|
||||
assert.equal(picked.variants.eventsPage, 'months');
|
||||
assert.equal(picked.variants.ministriesPage, 'cards', 'the rest take the suggestion');
|
||||
assert.equal(cleanDesign({ template: 'clean', variants: { eventsPage: 'nope' }, home: [], style: {} }).variants.eventsPage, 'list');
|
||||
});
|
||||
|
||||
it('moves with a template switch when untouched, and stays when chosen', () => {
|
||||
const start = defaultDesign('heritage');
|
||||
start.variants.eventsPage = 'cards';
|
||||
const { design } = switchTemplate(start, 'community');
|
||||
assert.equal(design.variants.eventsPage, 'cards');
|
||||
assert.equal(design.variants.ministriesPage, 'cards', "moved from Heritage's list to Community's cards");
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -191,7 +191,7 @@ test("move and zoom a photo in its frame, then delete a photo nothing uses", asy
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: /^Home\b/ }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
await page.getByRole("button", { name: /Top of the page/ }).click();
|
||||
await page.getByRole("button", { name: /^Top of the page/ }).click();
|
||||
await page.getByRole("button", { name: "Move and zoom" }).first().click();
|
||||
const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" });
|
||||
await expect(dialog).toBeVisible();
|
||||
@@ -245,3 +245,123 @@ test("move and zoom a ministry's, a leader's and an event's photo", async ({ pag
|
||||
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test("on the home page: each section's layout, background, place and showing, and only the photos its layout shows", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: /^Home\b/ }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
const preview = page.frameLocator('iframe[title="Live preview of this page"]');
|
||||
|
||||
// The top of the page: a slot for each photo the layout shows (the demo has three photos).
|
||||
await page.getByRole("button", { name: /^Top of the page/ }).click();
|
||||
const layout = page.getByLabel("Top of the page (hero): layout");
|
||||
await layout.selectOption("collage");
|
||||
await expect(page.getByText("Photo 3 of 3")).toBeVisible();
|
||||
await layout.selectOption("photo");
|
||||
await expect(page.getByText("Photo 1 of 3")).toHaveCount(0);
|
||||
await expect(page.getByText("2 more photos are kept for a layout that shows more.")).toBeVisible();
|
||||
await layout.selectOption("text");
|
||||
await expect(page.getByText("This layout shows no photos.")).toBeVisible();
|
||||
await expect(preview.locator(".cc-section-hero img")).toHaveCount(0);
|
||||
|
||||
// The welcome: its photo fields follow its layout, and it takes a background.
|
||||
await page.getByRole("button", { name: /^Welcome/ }).click();
|
||||
const welcome = page.locator("section").filter({ has: page.getByRole("button", { name: /^Welcome/ }) }).last();
|
||||
await page.getByLabel("Welcome: layout").selectOption("text");
|
||||
await expect(welcome.getByText("Pastor's photo and quote")).toHaveCount(0);
|
||||
await page.getByLabel("Welcome: layout").selectOption("pastor");
|
||||
await expect(welcome.getByText("Pastor's photo and quote")).toBeVisible();
|
||||
await page.getByLabel("Welcome: background").selectOption("brand");
|
||||
await expect(page.getByLabel("Welcome: background")).toHaveValue("brand");
|
||||
|
||||
// Hide it, show it, and move it.
|
||||
await page.getByRole("button", { name: "Hide Welcome" }).click();
|
||||
await expect(welcome.getByText("Not shown")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Show Welcome" }).click();
|
||||
await expect(welcome.getByText("Not shown")).toHaveCount(0);
|
||||
const order = async () => page.locator("main section > div > button").evaluateAll((els) => els.map((e) => e.textContent?.split("·")[0]?.trim() ?? ""));
|
||||
const before = await order();
|
||||
const at = before.findIndex((t) => t.startsWith("Welcome"));
|
||||
await page.getByRole("button", { name: "Move Welcome up" }).click();
|
||||
await expect.poll(async () => (await order()).findIndex((t) => t.startsWith("Welcome"))).toBe(at - 1);
|
||||
|
||||
// Template and style shows the same.
|
||||
await page.goto("/admin/template");
|
||||
await page.getByRole("tab", { name: "Home page layout" }).click();
|
||||
await expect(page.getByLabel("Top of the page layout")).toHaveValue("text");
|
||||
await expect(page.getByLabel("Welcome background")).toHaveValue("brand");
|
||||
});
|
||||
|
||||
/** A small MP4 (ftyp, moov with one track, mdat): enough to upload; browsers needn't play it. */
|
||||
function tinyMp4(): Buffer {
|
||||
const box = (type: string, ...parts: Buffer[]) => {
|
||||
const body = Buffer.concat(parts);
|
||||
const head = Buffer.alloc(8);
|
||||
head.writeUInt32BE(8 + body.length, 0);
|
||||
head.write(type, 4, "latin1");
|
||||
return Buffer.concat([head, body]);
|
||||
};
|
||||
const tkhd = Buffer.alloc(84);
|
||||
tkhd.writeUInt32BE(640 << 16, 76);
|
||||
tkhd.writeUInt32BE(360 << 16, 80);
|
||||
return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isommp42", "latin1")), box("moov", box("mvhd", Buffer.alloc(100)), box("trak", box("tkhd", tkhd))), box("mdat", Buffer.from("frames"))]);
|
||||
}
|
||||
|
||||
test("a page's blocks: their layouts and backgrounds", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: /^Plan your visit\b/ }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
const preview = page.frameLocator('iframe[title="Live preview of this page"]');
|
||||
await expect(preview.locator("section[data-bg]")).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: /^Text/ }).first().click();
|
||||
await page.getByLabel("Text block 1: background").selectOption("dark");
|
||||
await expect(preview.locator('section[data-bg="dark"]')).toHaveCount(1);
|
||||
await page.getByLabel("Text block 1: layout").selectOption("centred");
|
||||
await expect(preview.locator("section .cc-text.text-center")).toHaveCount(1);
|
||||
|
||||
await page.getByRole("button", { name: /^Image and text/ }).first().click();
|
||||
await page.getByLabel("Image and text block 2: layout").selectOption("image-right");
|
||||
await expect(preview.locator('.cc-frame[class*="md:order-2"]')).toHaveCount(1);
|
||||
|
||||
await page.getByRole("button", { name: /^Call to action/ }).first().click();
|
||||
await expect(preview.locator("section.cc-own-bg")).toHaveCount(0);
|
||||
await page.getByLabel("Call to action block 3: layout").selectOption("banner");
|
||||
await expect(preview.locator("section.cc-own-bg")).toHaveCount(1);
|
||||
|
||||
// Saved on the blocks: there when the page opens again.
|
||||
await page.reload();
|
||||
await page.getByRole("button", { name: /^Image and text/ }).first().click();
|
||||
await expect(page.getByLabel("Image and text block 2: layout")).toHaveValue("image-right");
|
||||
await expect(page.getByRole("button", { name: /^Call to action/ }).first()).toContainText("Banner in your colour");
|
||||
});
|
||||
|
||||
test("upload a video for the top of the page's Video layout", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: /^Home\b/ }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
await page.getByRole("button", { name: /^Top of the page/ }).click();
|
||||
await page.getByLabel("Top of the page (hero): layout").selectOption("photo");
|
||||
await expect(page.getByText("Video (plays muted, on a loop)")).toHaveCount(0);
|
||||
await page.getByLabel("Top of the page (hero): layout").selectOption("video");
|
||||
await expect(page.getByText("Still photo (shown before the video plays, and on phones)")).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Choose", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Choose a video" });
|
||||
await expect(dialog.getByText("No videos in your library yet")).toBeVisible();
|
||||
await dialog.locator('input[type="file"]').setInputFiles({ name: "welcome.mp4", mimeType: "video/mp4", buffer: tinyMp4() });
|
||||
await dialog.getByLabel("What the video shows").fill("People arriving on a Sunday");
|
||||
await dialog.getByRole("button", { name: "Upload" }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(page.getByText("Saved as a draft.")).toBeVisible();
|
||||
const preview = page.frameLocator('iframe[title="Live preview of this page"]');
|
||||
await expect(preview.locator(".cc-section-hero video")).toHaveAttribute("src", /\.mp4$/);
|
||||
|
||||
// The library lists it with the photos; photo fields never offer it.
|
||||
await page.goto("/admin/media");
|
||||
await expect(page.locator("main li video")).toHaveCount(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Every listing page layout in every template (backend variants.ts PAGE_VARIANTS): the demo
|
||||
* church's Ministries, Leadership, Events, Messages and Contact pages, one layout at a time. Each
|
||||
* page answers, shows what it lists, keeps the anchors the homepage links to, and axe finds no
|
||||
* violations (WCAG 2.2 AA) at phone and desktop width.
|
||||
*
|
||||
* PAGE_SHOTS=<folder> also saves a full-page screenshot of each, to look through by eye.
|
||||
*/
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test } from "@playwright/test";
|
||||
import { PAGE_LAYOUT_KEYS, PAGE_VARIANTS, TEMPLATE_VARIANTS } from "../backend/src/site/variants.js";
|
||||
|
||||
const BACKEND = "http://127.0.0.1:5310";
|
||||
const TEMPLATES = Object.keys(TEMPLATE_VARIANTS) as (keyof typeof TEMPLATE_VARIANTS)[];
|
||||
const WIDTHS = [["phone", { width: 390, height: 844 }], ["desktop", { width: 1366, height: 900 }]] as const;
|
||||
const SHOTS = process.env.PAGE_SHOTS;
|
||||
|
||||
/** The demo's page for each layout key, and something it must show. */
|
||||
const PAGES: Record<(typeof PAGE_LAYOUT_KEYS)[number], { path: string; shows: string }> = {
|
||||
ministriesPage: { path: "/ministries", shows: "main [id] h2" },
|
||||
leadershipPage: { path: "/leadership", shows: "main article h2" },
|
||||
eventsPage: { path: "/events", shows: 'main a[href]:not([href^="#"])' },
|
||||
messagesPage: { path: "/messages", shows: "main [id] h2" },
|
||||
contactPage: { path: "/contact", shows: 'main a[href^="mailto:"]' },
|
||||
};
|
||||
|
||||
for (const template of TEMPLATES) {
|
||||
test.describe(`${template} page layouts`, () => {
|
||||
test.beforeAll(async ({ request }) => {
|
||||
expect((await request.post(`${BACKEND}/test/demo?template=${template}`)).ok()).toBeTruthy();
|
||||
});
|
||||
|
||||
for (const key of PAGE_LAYOUT_KEYS) {
|
||||
for (const layout of PAGE_VARIANTS[key]) {
|
||||
test(`${key}: ${layout}`, async ({ page }) => {
|
||||
const res = await page.request.post(`${BACKEND}/test/design`, { data: { variants: { [key]: layout } } });
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const { path, shows } = PAGES[key];
|
||||
for (const [name, size] of WIDTHS) {
|
||||
await page.setViewportSize(size);
|
||||
expect((await page.goto(path))?.status()).toBe(200);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-template", template);
|
||||
await expect(page.locator(shows).first()).toBeVisible();
|
||||
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(axe.violations.map((v) => `${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`), name).toEqual([]);
|
||||
if (SHOTS) await page.screenshot({ path: `${SHOTS}/${template}-${key}-${layout}-${name}.png`, fullPage: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.12.0",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -9,13 +9,18 @@ import { FramingContext, type Framing } from "./framing";
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass } from "./ui";
|
||||
|
||||
type Spec =
|
||||
/**
|
||||
* One field. `layouts`: the section's layouts that show it (left out, every one does); the form
|
||||
* only offers it when the section is in one of them. A photo list's `count` is how many photos each
|
||||
* layout shows, and `labels` what they're called in it.
|
||||
*/
|
||||
type Spec = { layouts?: string[] } & (
|
||||
| { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number }
|
||||
| { key: string; kind: "number"; label: string; min: number; max: number }
|
||||
| { key: string; kind: "image"; label: string }
|
||||
| { key: string; kind: "images"; label: string; max: number }
|
||||
| { key: string; kind: "image" | "video"; label: string }
|
||||
| { key: string; kind: "images"; label: string; max: number; count?: Record<string, number>; labels?: Record<string, string> }
|
||||
| { key: string; kind: "button"; label: string }
|
||||
| { key: string; kind: "group"; label: string; fields: Spec[] };
|
||||
| { key: string; kind: "group"; label: string; fields: Spec[] });
|
||||
|
||||
const heading: Spec = { key: "heading", kind: "text", label: "Heading", max: 120 };
|
||||
const button: Spec = { key: "button", kind: "button", label: "Button" };
|
||||
@@ -24,7 +29,10 @@ export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> =
|
||||
hero: { name: "Top of the page (hero)", fields: [
|
||||
{ key: "headline", kind: "text", label: "Headline", max: 120 },
|
||||
{ key: "subline", kind: "textarea", label: "Under the headline", max: 300 },
|
||||
{ key: "images", kind: "images", label: "Photos (the first for Photo and Split; up to three for Collage)", max: 3 },
|
||||
{ key: "videoId", kind: "video", label: "Video (plays muted, on a loop)", layouts: ["video"] },
|
||||
// As site/sections/Hero.tsx draws them: Photo, Video (its still) and Split one, Collage three.
|
||||
{ key: "images", kind: "images", label: "Photos", max: 3, count: { photo: 1, video: 1, split: 1, collage: 3, text: 0 },
|
||||
labels: { photo: "Photo", video: "Still photo (shown before the video plays, and on phones)", split: "Photo (beside the headline)", collage: "Photos (three, for the collage)" } },
|
||||
button,
|
||||
] },
|
||||
serviceTimes: { name: "Service times and location", fields: [heading, { key: "note", kind: "textarea", label: "A note for visitors", hint: "The times and address come from your church profile.", max: 300 }] },
|
||||
@@ -32,8 +40,8 @@ export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> =
|
||||
heading,
|
||||
{ key: "mission", kind: "text", label: "Mission (one line)", max: 200 },
|
||||
{ key: "body", kind: "textarea", label: "Introduction", hint: "Leave an empty line between paragraphs.", max: 4000 },
|
||||
{ key: "imageId", kind: "image", label: "Photo (Image and text layout)" },
|
||||
{ key: "pastor", kind: "group", label: "Pastor's photo and quote (With pastor layout)", fields: [
|
||||
{ key: "imageId", kind: "image", label: "Photo", layouts: ["image-text"] },
|
||||
{ key: "pastor", kind: "group", label: "Pastor's photo and quote", layouts: ["pastor"], fields: [
|
||||
{ key: "name", kind: "text", label: "Name", max: 120 }, { key: "role", kind: "text", label: "Role", max: 80 },
|
||||
{ key: "quote", kind: "textarea", label: "Quote", max: 400 }, { key: "photoId", kind: "image", label: "Photo" },
|
||||
] },
|
||||
@@ -42,7 +50,7 @@ export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> =
|
||||
team: { name: "Team", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
|
||||
events: { name: "Upcoming events", fields: [heading, { key: "count", kind: "number", label: "How many to show", min: 2, max: 12 }] },
|
||||
latestMessage: { name: "Latest message", fields: [heading] },
|
||||
invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo (Image background layout)" }] },
|
||||
invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo", layouts: ["image"] }] },
|
||||
};
|
||||
|
||||
export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
@@ -58,11 +66,15 @@ type Data = Record<string, unknown>;
|
||||
* A section's or block's fields. With `frame` (the top-level form of a section), its photos show in
|
||||
* the shape of their frame on the site and can be moved and zoomed (saved in `data.framing`).
|
||||
*/
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "", frame }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string; frame?: Framing["frame"] }) {
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "", frame, layout }: {
|
||||
fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string; frame?: Framing["frame"];
|
||||
/** The section's layout: only the fields it shows are offered (left out, all of them are). */
|
||||
layout?: string;
|
||||
}) {
|
||||
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
|
||||
const form = (
|
||||
<div className="space-y-4">
|
||||
{fields.map((f) => {
|
||||
{fields.filter((f) => !layout || !f.layouts || f.layouts.includes(layout)).map((f) => {
|
||||
const err = errors[`${prefix}${f.key}`];
|
||||
const v = value[f.key];
|
||||
switch (f.kind) {
|
||||
@@ -72,15 +84,28 @@ export function DataForm({ fields, value, onChange, errors, prefix = "", frame }
|
||||
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>;
|
||||
case "number":
|
||||
return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
|
||||
case "video":
|
||||
return <div key={f.key}><ImagePicker kind="video" label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
case "image":
|
||||
return <div key={f.key}><ImagePicker label={f.label} slot={{ key: f.key }} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
case "images": {
|
||||
const list = Array.isArray(v) ? (v as string[]) : [];
|
||||
// A slot for each photo the layout shows, chosen or not. Photos past them (from a layout
|
||||
// that shows more) are kept, so switching back brings them back.
|
||||
const count = layout ? (f.count?.[layout] ?? f.max) : f.max;
|
||||
const label = (layout && f.labels?.[layout]) || f.label;
|
||||
if (count === 0) return <p key={f.key} className="text-sm text-gray-500">This layout shows no photos. Choose another layout above to add some.</p>;
|
||||
const extra = list.length - count;
|
||||
return (
|
||||
<div key={f.key} className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-800">{f.label}</p>
|
||||
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} slot={{ key: f.key, index: i }} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
|
||||
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} slot={{ key: f.key, index: list.length }} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
|
||||
{count > 1 && <p className="text-sm font-medium text-gray-800">{label}</p>}
|
||||
{Array.from({ length: count }, (_, i) => {
|
||||
const id = list[i] ?? null;
|
||||
const name = count > 1 ? `Photo ${i + 1} of ${count}` : label;
|
||||
return <ImagePicker key={i} label={name} slot={{ key: f.key, index: i }} value={id}
|
||||
onChange={(n) => set(f.key, id ? (n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i)) : n ? [...list, n] : list)} />;
|
||||
})}
|
||||
{extra > 0 && <p className="text-xs text-gray-500">{extra === 1 ? "1 more photo is" : `${extra} more photos are`} kept for a layout that shows more.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ export function frameFor(design: Design, type: string, key: string, index = 0):
|
||||
}
|
||||
if (type === "event") return { ratio: 16 / 10, label: "On the event's card (a little taller on its own page)" };
|
||||
if (type === "invitation") return { ratio: 3, label: "Behind the invitation, darkened (the Image background layout)" };
|
||||
// A block's own layout (passed in as the design's variant for its type).
|
||||
if (type === "image-text" && v === "image-above") return { ratio: 16 / 9, label: "Above the text, the page's full width" };
|
||||
return { ratio: 4 / 3, label: "Beside the text" };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* The homepage sections' layouts and backgrounds, shared by Template and style (Home page layout)
|
||||
* and the home page's editor (Pages), which both change them. The ids are the backend's
|
||||
* (src/site/variants.ts SECTION_VARIANTS and SECTION_BACKGROUNDS).
|
||||
*/
|
||||
|
||||
export type HomeEntry = { section: string; hidden: boolean; background?: string };
|
||||
export type Design = { template: string; variants: Record<string, string>; home: HomeEntry[]; style: Record<string, string> };
|
||||
export type DesignOptions = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
|
||||
|
||||
export const TEMPLATE_NAMES: Record<string, string> = { heritage: "Heritage", bold: "Bold", community: "Community", clean: "Clean" };
|
||||
|
||||
export const SECTION_NAMES: Record<string, string> = {
|
||||
hero: "Top of the page", serviceTimes: "Service times", welcome: "Welcome", ministries: "Ministries", team: "Team", events: "Upcoming events", latestMessage: "Latest message", invitation: "Invitation",
|
||||
};
|
||||
|
||||
export const VARIANT_NAMES: Record<string, string> = {
|
||||
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
|
||||
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
|
||||
calendar: "Calendar strip", card: "Card", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
|
||||
};
|
||||
|
||||
export const ALL_VARIANTS: Record<string, string[]> = {
|
||||
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
|
||||
team: ["faces", "list", "featured"], events: ["cards", "list", "calendar"], latestMessage: ["video", "card", "compact"], invitation: ["banner", "centred", "image"],
|
||||
};
|
||||
|
||||
/** A section's layouts, the ones that suit the template first, and which those are. */
|
||||
export function layoutsFor(design: Design, options: DesignOptions | undefined, section: string): { ordered: string[]; recommended: string[] } {
|
||||
const recommended = options?.variants[design.template]?.[section] ?? [];
|
||||
return { ordered: [...recommended, ...(ALL_VARIANTS[section] ?? []).filter((v) => !recommended.includes(v))], recommended };
|
||||
}
|
||||
|
||||
/**
|
||||
* The layouts of what the fixed pages list (backend variants.ts PAGE_VARIANTS), keyed by page kind:
|
||||
* the design's key for each, its name, and each layout's name in the order the backend lists them.
|
||||
* Saved on the design like the homepage's (`variants.ministriesPage`), with the template's
|
||||
* suggestions first.
|
||||
*/
|
||||
export const PAGE_LAYOUTS: Record<string, { key: string; name: string; layouts: Record<string, string> }> = {
|
||||
ministries: { key: "ministriesPage", name: "Ministries", layouts: { alternating: "Alternating photo and text", cards: "Cards", list: "List with small photos" } },
|
||||
leadership: { key: "leadershipPage", name: "Leadership", layouts: { grid: "Grid of faces", featured: "Lead pastor first", list: "List with photos" } },
|
||||
events: { key: "eventsPage", name: "Events", layouts: { list: "List with dates", cards: "Cards with photos", months: "By month" } },
|
||||
messages: { key: "messagesPage", name: "Messages", layouts: { grid: "Grid of videos", featured: "Latest first, then a list", list: "List" } },
|
||||
contact: { key: "contactPage", name: "Contact", layouts: { columns: "Two columns", map: "With map", cards: "Cards" } },
|
||||
};
|
||||
|
||||
/** A listing page's layouts, the ones that suit the template first, and which those are. */
|
||||
export function pageLayoutsFor(design: Design, options: DesignOptions | undefined, kind: string): { key: string; ordered: string[]; recommended: string[]; names: Record<string, string> } | null {
|
||||
const p = PAGE_LAYOUTS[kind];
|
||||
if (!p) return null;
|
||||
const recommended = options?.variants[design.template]?.[p.key] ?? [];
|
||||
const all = Object.keys(p.layouts);
|
||||
return { key: p.key, ordered: [...recommended.filter((v) => all.includes(v)), ...all.filter((v) => !recommended.includes(v))], recommended, names: p.layouts };
|
||||
}
|
||||
|
||||
/** The other pages' blocks' layouts, the default first (backend variants.ts BLOCK_VARIANTS). */
|
||||
export const BLOCK_LAYOUTS: Record<string, { id: string; name: string }[]> = {
|
||||
text: [{ id: "standard", name: "Standard" }, { id: "centred", name: "Centred" }],
|
||||
"image-text": [{ id: "image-left", name: "Photo on the left" }, { id: "image-right", name: "Photo on the right" }, { id: "image-above", name: "Photo above" }],
|
||||
quote: [{ id: "centred", name: "Centred" }, { id: "line", name: "With a line" }],
|
||||
cta: [{ id: "centred", name: "Centred" }, { id: "banner", name: "Banner in your colour" }],
|
||||
};
|
||||
|
||||
/** A block's layout as the site draws it: its own when it's one of its type's, else the default. */
|
||||
export function blockLayout(type: string, variant: string | null): string | undefined {
|
||||
const list = BLOCK_LAYOUTS[type];
|
||||
return list?.some((l) => l.id === variant) ? variant! : list?.[0]?.id;
|
||||
}
|
||||
|
||||
/** A section's own background (backend variants.ts SECTION_BACKGROUNDS), each from the church's colours; "" follows Style → Section colour. */
|
||||
export 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))" },
|
||||
];
|
||||
|
||||
/** The home list with `section`'s background set ("" clears it, so it follows the style). */
|
||||
export const withBackground = (home: HomeEntry[], section: string, background: string): HomeEntry[] =>
|
||||
home.map(({ background: b, ...e }) => {
|
||||
const next = e.section === section ? background : b;
|
||||
return next ? { ...e, background: next } : e;
|
||||
});
|
||||
|
||||
/** The home list with `section` shown or not. */
|
||||
export const withShown = (home: HomeEntry[], section: string, shown: boolean): HomeEntry[] =>
|
||||
home.map((e) => (e.section === section ? { ...e, hidden: !shown } : e));
|
||||
|
||||
/** The home list with the entry at `i` moved one place up (-1) or down (1), or null at an end. */
|
||||
export function moved(home: HomeEntry[], i: number, d: -1 | 1): HomeEntry[] | null {
|
||||
const j = i + d;
|
||||
if (j < 0 || j >= home.length) return null;
|
||||
const next = [...home];
|
||||
[next[i], next[j]] = [next[j]!, next[i]!];
|
||||
return next;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { api } from "./api";
|
||||
import { Framed, FramingDialog, useFraming } from "./framing";
|
||||
import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] };
|
||||
export type MediaItem = { id: string; url: string; mime?: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] };
|
||||
export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number };
|
||||
|
||||
export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
|
||||
@@ -23,15 +23,28 @@ export function StorageMeter({ s }: { s: Storage }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Upload form: a photo and what it shows (alt text is required, §3 "Every image needs alt text"). */
|
||||
export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) => void; disabled?: boolean }) {
|
||||
/** What a picker or upload takes: photos, a video (MP4, for the top of the page's Video layout), or either (the library). */
|
||||
export type MediaKind = "image" | "video" | "any";
|
||||
|
||||
/** Whether a library item is a video (by its type; items listed before videos existed are photos). */
|
||||
export const isVideo = (m: Pick<MediaItem, "mime">) => !!m.mime?.startsWith("video/");
|
||||
|
||||
const UPLOAD = {
|
||||
image: { label: "Photo", accept: "image/jpeg,image/png,image/webp", hint: "JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.", noun: "photo" },
|
||||
video: { label: "Video", accept: "video/mp4", hint: "MP4, up to 20 MB. A short, quiet clip (10 to 20 seconds) works best: it plays muted, on a loop.", noun: "video" },
|
||||
any: { label: "Photo or video", accept: "image/jpeg,image/png,image/webp,video/mp4", hint: "Photos as JPEG, PNG or WebP, up to 15 MB; a video for the top of the page as MP4, up to 20 MB.", noun: "file" },
|
||||
} as const;
|
||||
|
||||
/** Upload form: a photo or video and what it shows (alt text is required, §3 "Every image needs alt text"). */
|
||||
export function Uploader({ onUploaded, disabled, kind = "image" }: { onUploaded: (m: MediaItem) => void; disabled?: boolean; kind?: MediaKind }) {
|
||||
const file = useRef<HTMLInputElement>(null);
|
||||
const [alt, setAlt] = useState("");
|
||||
const { busy, message, run } = useAction();
|
||||
const u = UPLOAD[kind];
|
||||
const go = () => run(async () => {
|
||||
const f = file.current?.files?.[0];
|
||||
if (!f) throw new Error("Choose a photo first.");
|
||||
if (!alt.trim()) throw new Error("Say what the photo shows (for people who can't see it).");
|
||||
if (!f) throw new Error(`Choose a ${u.noun} first.`);
|
||||
if (!alt.trim()) throw new Error(`Say what the ${u.noun === "file" ? "photo or video" : u.noun} shows (for people who can't see it).`);
|
||||
const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f });
|
||||
setAlt("");
|
||||
if (file.current) file.current.value = "";
|
||||
@@ -39,10 +52,10 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
|
||||
}, "Uploaded.");
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Field label="Photo" hint="JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.">
|
||||
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="block text-sm" disabled={disabled} />
|
||||
<Field label={u.label} hint={u.hint}>
|
||||
<input ref={file} type="file" accept={u.accept} className="block text-sm" disabled={disabled} />
|
||||
</Field>
|
||||
<Field label="What the photo shows" hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
|
||||
<Field label={kind === "video" ? "What the video shows" : "What the photo shows"} hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
|
||||
<input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} />
|
||||
</Field>
|
||||
<Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn>
|
||||
@@ -51,17 +64,27 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
|
||||
);
|
||||
}
|
||||
|
||||
/** A library item small: the photo, or the video's first frame (muted, never playing). */
|
||||
export function MediaThumb({ m, className, alt = m.alt }: { m: MediaItem; className?: string; alt?: string }) {
|
||||
return isVideo(m)
|
||||
? <video src={`${m.url}#t=0.1`} muted playsInline preload="metadata" aria-label={alt || undefined} className={className} />
|
||||
: <img src={m.url} alt={alt} className={className} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* One image field: shows the chosen image, with Choose and Remove. In a section (`slot` and a
|
||||
* FramingContext), it's shown in the shape of its frame on the site, with Move and zoom.
|
||||
* One image field (or, with `kind="video"`, a video field): shows the chosen one, with Choose and
|
||||
* Remove, and only offers its kind from the library. In a section (`slot` and a FramingContext), a
|
||||
* photo is shown in the shape of its frame on the site, with Move and zoom.
|
||||
*/
|
||||
export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) {
|
||||
export function ImagePicker({ value, onChange, label, slot, kind = "image" }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number }; kind?: "image" | "video" }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [framingOpen, setFramingOpen] = useState(false);
|
||||
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
|
||||
const chosen = data?.items.find((m) => m.id === value);
|
||||
const framing = useFraming();
|
||||
const frame = framing && slot ? framing.frame(slot.key, slot.index) : null;
|
||||
const frame = framing && slot && kind === "image" ? framing.frame(slot.key, slot.index) : null;
|
||||
const items = data?.items.filter((m) => isVideo(m) === (kind === "video"));
|
||||
const noun = kind === "video" ? "video" : "image";
|
||||
const focus = value ? framing?.get(value) : undefined;
|
||||
return (
|
||||
<div>
|
||||
@@ -74,7 +97,7 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
|
||||
</button>
|
||||
) : (
|
||||
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
|
||||
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
|
||||
{chosen ? <MediaThumb m={chosen} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No {noun}</span>}
|
||||
</div>
|
||||
)}
|
||||
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
|
||||
@@ -87,17 +110,18 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
|
||||
onDone={(f) => { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} />
|
||||
)}
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image">
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label={`Choose ${kind === "video" ? "a video" : "an image"}`}>
|
||||
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Choose an image</h2>
|
||||
<h2 className="text-lg font-semibold">Choose {kind === "video" ? "a video" : "an image"}</h2>
|
||||
<Btn onClick={() => setOpen(false)}>Close</Btn>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
|
||||
{data?.items.map((m) => (
|
||||
{items?.length === 0 && <p className="col-span-full text-sm text-gray-600">No {noun}s in your library yet: upload one below.</p>}
|
||||
{items?.map((m) => (
|
||||
<button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }}
|
||||
className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}>
|
||||
<img src={m.url} alt="" className="aspect-[4/3] w-full object-cover" />
|
||||
<MediaThumb m={m} alt="" className="aspect-[4/3] w-full object-cover" />
|
||||
<span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -105,7 +129,7 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
|
||||
<div className="mt-6 border-t border-gray-200 pt-4">
|
||||
<h3 className="mb-2 font-semibold">Upload a new one</h3>
|
||||
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>}
|
||||
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
|
||||
<Uploader kind={kind} disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import type { Church } from "@crosscode/contracts";
|
||||
import { ColourField } from "@crosscode/ui";
|
||||
import { api, canEdit } from "@/admin/api";
|
||||
import { ImagePicker } from "@/admin/media";
|
||||
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">
|
||||
<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="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>
|
||||
<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>
|
||||
<ColourField label="Main colour" hint="Buttons, links and headings on every site." error={err("branding.colours.primary")} disabled={!editor}
|
||||
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.">
|
||||
<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>)}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { api, canEdit } from "@/admin/api";
|
||||
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
|
||||
import { gb, MediaThumb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
|
||||
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
|
||||
import { Image as ImageIcon, Trash2 } from "lucide-react";
|
||||
|
||||
@@ -19,15 +19,15 @@ export default function Media() {
|
||||
const s = data.storage;
|
||||
return (
|
||||
<>
|
||||
<Title icon={ImageIcon} sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
|
||||
<Title icon={ImageIcon} sub="Photos for your pages, and a short video for the top of your home page. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<Panel>
|
||||
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
{data.items.length === 0 && <p className="text-gray-600">No photos yet.</p>}
|
||||
{data.items.length === 0 && <p className="text-gray-600">No photos or videos yet.</p>}
|
||||
<ul className="grid gap-4 sm:grid-cols-2">
|
||||
{data.items.map((m) => (
|
||||
<li key={m.id} className="space-y-2">
|
||||
<img src={m.url} alt={m.alt} className="aspect-[4/3] w-full rounded object-cover" />
|
||||
<MediaThumb m={m} className="aspect-[4/3] w-full rounded object-cover" />
|
||||
<label className="block text-xs text-gray-600">What it shows
|
||||
<input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} />
|
||||
</label>
|
||||
@@ -70,7 +70,7 @@ export default function Media() {
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel title="Upload a photo">
|
||||
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
|
||||
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader kind="any" onUploaded={() => reload()} />}
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,27 +2,29 @@
|
||||
|
||||
/**
|
||||
* One page (§6), with its live preview on the right. Content: the home page has one of each
|
||||
* homepage section (their layouts, order and whether they show are under Template and style); every
|
||||
* other page is built from blocks, which can be added, moved, hidden and removed. Page details: its
|
||||
* homepage section, each with its layout, background, place and whether it shows (also under
|
||||
* Template and style), and only the photos its layout shows; every other page is built from blocks,
|
||||
* which can be added, moved, hidden and removed, and a page that lists something (ministries,
|
||||
* events...) chooses how it lists them. Page details: its
|
||||
* title, address, menu and search engine details.
|
||||
*/
|
||||
import Link from "next/link";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
ArrowDown, ArrowUp, CalendarDays, ChevronDown, ChevronRight, Clock, EyeOff, Eye, FileText, Heart, Image as ImageIcon, LayoutList, Megaphone, Mic,
|
||||
ArrowDown, ArrowUp, CalendarDays, ChevronDown, ChevronRight, Clock, EyeOff, Eye, FileText, Heart, Image as ImageIcon, LayoutList, LayoutTemplate, Megaphone, Mic,
|
||||
Plus, Quote, Search, Settings2, Sparkles, Trash2, Type, Users, HandHeart, type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { api } from "@/admin/api";
|
||||
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
|
||||
import { frameFor, type Framing } from "@/admin/framing";
|
||||
import { WithPreview } from "@/admin/LivePreview";
|
||||
import { BACKGROUNDS, BLOCK_LAYOUTS, blockLayout, layoutsFor, moved, pageLayoutsFor, TEMPLATE_NAMES, VARIANT_NAMES, withBackground, withShown, type Design, type DesignOptions, type HomeEntry } from "@/admin/layouts";
|
||||
import { ImagePicker } from "@/admin/media";
|
||||
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string };
|
||||
type Section = { id: string; type: string; variant: string | null; hidden: boolean; background: string | null; data: Record<string, unknown>; updatedAt: string };
|
||||
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
|
||||
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[] };
|
||||
|
||||
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
|
||||
const LISTS: Record<string, string> = {
|
||||
@@ -32,6 +34,7 @@ const LISTS: Record<string, string> = {
|
||||
messages: "This page lists your messages; blocks you add show after them.",
|
||||
contact: "This page shows your church's contact details and service times from your church profile.",
|
||||
};
|
||||
const LIST_WHAT: Record<string, string> = { ministries: "your ministries", leadership: "your team", events: "your events", messages: "your messages", contact: "your contact details and service times" };
|
||||
const ICONS: Record<string, LucideIcon> = {
|
||||
hero: Sparkles, serviceTimes: Clock, welcome: Heart, ministries: HandHeart, team: Users, events: CalendarDays, latestMessage: Mic, invitation: Megaphone,
|
||||
text: Type, "image-text": ImageIcon, quote: Quote, cta: Megaphone,
|
||||
@@ -49,9 +52,25 @@ const summary = (data: Record<string, unknown>) => {
|
||||
return null;
|
||||
};
|
||||
|
||||
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame }: {
|
||||
/** A section's or block's own background, from the church's colours ("" follows the style). */
|
||||
function BackgroundField({ name, value, busy, onChange }: { name: string; value: string; busy: boolean; onChange: (background: string) => void }) {
|
||||
return (
|
||||
<Field label="Background" hint="From your church's colours. A layout with a photo or band keeps its own.">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-9 w-9 shrink-0 rounded border border-gray-300" style={{ background: BACKGROUNDS.find((b) => b.id === value)?.swatch }} aria-hidden />
|
||||
<select aria-label={`${name}: background`} className={inputClass} value={value} disabled={busy} onChange={(ev) => onChange(ev.target.value)}>
|
||||
{BACKGROUNDS.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
|
||||
</select>
|
||||
</span>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame, layout, layoutName, settings }: {
|
||||
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; frame?: Framing["frame"];
|
||||
onSave: (data: Record<string, unknown>) => Promise<unknown>; hidden?: React.ReactNode; extra?: React.ReactNode;
|
||||
/** A home page section's layout (only its fields are offered) and its layout and background controls. */
|
||||
layout?: string; layoutName?: string; settings?: React.ReactNode;
|
||||
}) {
|
||||
const [value, setValue] = useState(initial);
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -65,7 +84,7 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, fr
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex flex-wrap items-center gap-2 font-semibold text-gray-900">{title}{hidden}</span>
|
||||
<span className="block truncate text-xs text-gray-500">{line ?? "Nothing written yet"}</span>
|
||||
<span className="block truncate text-xs text-gray-500">{layout && `${layoutName ?? VARIANT_NAMES[layout] ?? layout} · `}{line ?? "Nothing written yet"}</span>
|
||||
</span>
|
||||
{open ? <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" aria-hidden /> : <ChevronRight className="h-4 w-4 shrink-0 text-gray-400" aria-hidden />}
|
||||
<span className="sr-only">{open ? "Close" : "Edit"}</span>
|
||||
@@ -74,7 +93,8 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, fr
|
||||
</div>
|
||||
{open && (
|
||||
<div className="space-y-4 border-t border-gray-100 p-4">
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} frame={frame} />
|
||||
{settings}
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} frame={frame} layout={layout} />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
|
||||
<Btn onClick={() => setOpen(false)}>Close</Btn>
|
||||
@@ -135,18 +155,26 @@ export default function EditPage() {
|
||||
const router = useRouter();
|
||||
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
|
||||
const isHome = page?.kind === "home";
|
||||
const design = useAdmin<{ design: Design }>("/design");
|
||||
const design = useAdmin<{ design: Design; options: DesignOptions }>("/design");
|
||||
const blocks = useAction();
|
||||
const remove = useAction();
|
||||
const layouts = useAction();
|
||||
const [tab, setTab] = useState<"content" | "details">("content");
|
||||
// The saved page: when it changes (any save), the preview reloads.
|
||||
const version = useMemo(() => (page ? JSON.stringify([page.updatedAt, page.slug, page.sections.map((s) => [s.id, s.updatedAt, s.hidden])]) : ""), [page]);
|
||||
// The saved page and the design (layouts, order, backgrounds): when either changes, the preview reloads.
|
||||
const saved = design.data?.design;
|
||||
const version = useMemo(() => (page ? JSON.stringify([page.updatedAt, page.slug, page.sections.map((s) => [s.id, s.updatedAt, s.hidden]), saved]) : ""), [page, saved]);
|
||||
if (!page) return <Loading error={error} />;
|
||||
const path = isHome ? "/" : `/${page.slug}`;
|
||||
const blockCall = (p: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${p}`, { method, body })));
|
||||
|
||||
// The home page's sections in the order the site shows them, and whether each shows.
|
||||
const home = design.data?.design.home ?? HOME_ORDER.map((section) => ({ section, hidden: false }));
|
||||
const home: HomeEntry[] = saved?.home ?? HOME_ORDER.map((section) => ({ section, hidden: false }));
|
||||
// A section's layout, order, background and whether it shows are the site's design (as under
|
||||
// Template and style): they save straight away, apart from the section's words and photos.
|
||||
const saveDesign = (patch: Partial<Design>) => layouts.run(async () => {
|
||||
const r = await api<{ design: Design }>("/design", { method: "PUT", body: patch });
|
||||
if (design.data) design.setData({ ...design.data, design: r.design });
|
||||
});
|
||||
|
||||
return (
|
||||
<WithPreview path={path} version={version}>
|
||||
@@ -167,25 +195,76 @@ export default function EditPage() {
|
||||
<div hidden={tab !== "content"}>
|
||||
{isHome ? (
|
||||
<div className="space-y-3">
|
||||
<Notice>Open a section to change what it says. Its layout, its place on the page and whether it shows are under <Link href="/admin/template" className="font-semibold underline">Template and style</Link>.</Notice>
|
||||
{home.map(({ section: type, hidden }) => {
|
||||
<Notice>Open a section to choose its layout and background and change what it says. Use the arrows to move a section and the eye to show or hide it. The layout, background, order and showing save straight away; the words and photos save with the section's Save button.</Notice>
|
||||
{layouts.message?.tone === "error" && <Notice tone="error">{layouts.message.text}</Notice>}
|
||||
{home.map(({ section: type, hidden }, i) => {
|
||||
const s = page.sections.find((x) => x.type === type);
|
||||
const spec = SECTION_FIELDS[type];
|
||||
if (!spec) return null;
|
||||
return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} frame={(key, i) => frameFor(design.data?.design, type, key, i)}
|
||||
const layout = saved?.variants[type];
|
||||
const background = home[i]?.background ?? "";
|
||||
const { ordered, recommended } = saved ? layoutsFor(saved, design.data?.options, type) : { ordered: [], recommended: [] };
|
||||
const settings = saved && (
|
||||
<div className="grid gap-4 rounded-lg bg-gray-50 p-3 sm:grid-cols-2">
|
||||
<Field label="Layout" hint={`Those marked suit ${TEMPLATE_NAMES[saved.template] ?? "your template"} best; every one works.`}>
|
||||
<select aria-label={`${spec.name}: layout`} className={inputClass} value={layout} disabled={layouts.busy} onChange={(ev) => saveDesign({ variants: { [type]: ev.target.value } })}>
|
||||
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
{/* The top of the page draws its own background (photo, colour or plain). */}
|
||||
{type !== "hero" && <BackgroundField name={spec.name} value={background} busy={layouts.busy} onChange={(b) => saveDesign({ home: withBackground(home, type, b) })} />}
|
||||
</div>
|
||||
);
|
||||
return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} frame={(key, n) => frameFor(saved, type, key, n)}
|
||||
layout={layout} settings={settings}
|
||||
hidden={hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Not shown</span>}
|
||||
extra={saved && <>
|
||||
<Btn kind="icon" onClick={() => { const h = moved(home, i, -1); if (h) void saveDesign({ home: h }); }} disabled={layouts.busy || i === 0} aria-label={`Move ${spec.name} up`} title="Move up"><ArrowUp className="h-4 w-4" aria-hidden /></Btn>
|
||||
<Btn kind="icon" onClick={() => { const h = moved(home, i, 1); if (h) void saveDesign({ home: h }); }} disabled={layouts.busy || i === home.length - 1} aria-label={`Move ${spec.name} down`} title="Move down"><ArrowDown className="h-4 w-4" aria-hidden /></Btn>
|
||||
<Btn kind="icon" onClick={() => saveDesign({ home: withShown(home, type, hidden) })} disabled={layouts.busy} aria-label={hidden ? `Show ${spec.name}` : `Hide ${spec.name}`} title={hidden ? "Show it" : "Hide it"}>{hidden ? <Eye className="h-4 w-4" aria-hidden /> : <EyeOff className="h-4 w-4" aria-hidden />}</Btn>
|
||||
</>}
|
||||
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{(() => {
|
||||
// What this page lists has its own layout, on the design (as under Template and style), saved straight away.
|
||||
const p = saved && pageLayoutsFor(saved, design.data?.options, page.kind);
|
||||
if (!p) return null;
|
||||
return (
|
||||
<Panel title="Layout" icon={LayoutTemplate} sub={`How this page lists ${LIST_WHAT[page.kind] ?? "its content"}. Those marked suit ${TEMPLATE_NAMES[saved.template] ?? "your template"} best; every one works.`}>
|
||||
<select aria-label="Page layout" className={inputClass} value={saved.variants[p.key] ?? p.ordered[0]} disabled={layouts.busy} onChange={(ev) => saveDesign({ variants: { [p.key]: ev.target.value } })}>
|
||||
{p.ordered.map((v) => <option key={v} value={v}>{p.names[v]}{v === p.recommended[0] ? " (suggested for this template)" : p.recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
{layouts.message?.tone === "error" && <div className="mt-3"><Notice tone="error">{layouts.message.text}</Notice></div>}
|
||||
</Panel>
|
||||
);
|
||||
})()}
|
||||
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
|
||||
{page.sections.length === 0 && <p className="rounded-xl border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">Nothing on this page yet: add a block below.</p>}
|
||||
{page.sections.map((s, i) => {
|
||||
const spec = BLOCK_FIELDS[s.type];
|
||||
if (!spec) return null;
|
||||
// A block's layout and background are its own (saved on it straight away, like hiding it).
|
||||
const layout = blockLayout(s.type, s.variant);
|
||||
const options = BLOCK_LAYOUTS[s.type] ?? [];
|
||||
const name = `${spec.name} block ${i + 1}`;
|
||||
const settings = (
|
||||
<div className="grid gap-4 rounded-lg bg-gray-50 p-3 sm:grid-cols-2">
|
||||
{options.length > 1 && (
|
||||
<Field label="Layout">
|
||||
<select aria-label={`${name}: layout`} className={inputClass} value={layout} disabled={blocks.busy} onChange={(ev) => blockCall(`/blocks/${s.id}`, "PUT", { variant: ev.target.value })}>
|
||||
{options.map((l) => <option key={l.id} value={l.id}>{l.name}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<BackgroundField name={name} value={s.background ?? ""} busy={blocks.busy} onChange={(b) => blockCall(`/blocks/${s.id}`, "PUT", { background: b || null })} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data} frame={(key, i) => frameFor(design.data?.design, s.type, key, i)}
|
||||
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data} layout={layout} layoutName={options.find((l) => l.id === layout)?.name} settings={settings}
|
||||
frame={(key, n) => frameFor(design.data?.design && { ...design.data.design, variants: { ...design.data.design.variants, [s.type]: layout ?? "" } }, s.type, key, n)}
|
||||
hidden={s.hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Hidden</span>}
|
||||
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
|
||||
extra={<>
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Template and style (WEBSITE-1.0-PLAN §3): the template, each homepage section's layout
|
||||
* (recommended first), the homepage order, and the style settings. Fonts and corners are the
|
||||
* Template and style (WEBSITE-1.0-PLAN §3): the template, each homepage section's layout and each
|
||||
* listing page's (recommended first), the homepage order, and the style settings. Fonts and corners are the
|
||||
* church's brand style, shared with its other sites, so they're set in its church profile.
|
||||
*/
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { ArrowDown, ArrowUp, Check, Eye, LayoutTemplate, ListOrdered, Palette, SlidersHorizontal } from "lucide-react";
|
||||
import { ArrowDown, ArrowUp, Check, Eye, Files, LayoutTemplate, ListOrdered, Palette, SlidersHorizontal } from "lucide-react";
|
||||
import { api } from "@/admin/api";
|
||||
import { WithPreview } from "@/admin/LivePreview";
|
||||
import { BACKGROUNDS, layoutsFor, moved, PAGE_LAYOUTS, pageLayoutsFor, SECTION_NAMES as SECTIONS, VARIANT_NAMES, withBackground, withShown, type Design, type DesignOptions as Options } from "@/admin/layouts";
|
||||
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> };
|
||||
type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
|
||||
|
||||
const TEMPLATES = [
|
||||
{ id: "heritage", name: "Heritage", text: "Traditional and dignified: centred, framed images, serif headings." },
|
||||
{ id: "bold", name: "Bold", text: "Modern and energetic: full-screen photos, big headlines, bands." },
|
||||
@@ -22,16 +20,6 @@ const TEMPLATES = [
|
||||
{ id: "clean", name: "Clean", text: "Minimal and calm: lots of space, good without photos." },
|
||||
];
|
||||
|
||||
const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes: "Service times", welcome: "Welcome", ministries: "Ministries", team: "Team", events: "Upcoming events", latestMessage: "Latest message", invitation: "Invitation" };
|
||||
const VARIANT_NAMES: Record<string, string> = {
|
||||
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
|
||||
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
|
||||
calendar: "Calendar strip", card: "Card", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
|
||||
};
|
||||
const ALL_VARIANTS: Record<string, string[]> = {
|
||||
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
|
||||
team: ["faces", "list", "featured"], events: ["cards", "list", "calendar"], latestMessage: ["video", "card", "compact"], invitation: ["banner", "centred", "image"],
|
||||
};
|
||||
const HEADER_NAMES: Record<string, string> = {
|
||||
centred: "Centred", "centred-top-bar": "Centred, with a top bar", transparent: "Over the photo, solid when scrolling", solid: "Solid",
|
||||
"logo-left-button": "Logo left, with a Plan your visit button", "logo-left-tinted": "Logo left, on a tinted bar", small: "Small", "small-menu": "Small, menu on every screen",
|
||||
@@ -46,7 +34,7 @@ const STYLE = [
|
||||
export default function TemplatePage() {
|
||||
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
|
||||
const { busy, message, run } = useAction();
|
||||
const [tab, setTab] = useState<"template" | "home" | "style">("template");
|
||||
const [tab, setTab] = useState<"template" | "home" | "pages" | "style">("template");
|
||||
if (!data) return <Loading error={error} />;
|
||||
const { design, options } = data;
|
||||
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
|
||||
@@ -55,11 +43,8 @@ export default function TemplatePage() {
|
||||
return r;
|
||||
}, done);
|
||||
const move = (i: number, d: -1 | 1) => {
|
||||
const home = [...design.home];
|
||||
const j = i + d;
|
||||
if (j < 0 || j >= home.length) return;
|
||||
[home[i], home[j]] = [home[j]!, home[i]!];
|
||||
save({ home });
|
||||
const home = moved(design.home, i, d);
|
||||
if (home) save({ home });
|
||||
};
|
||||
return (
|
||||
<WithPreview path="/" version={JSON.stringify(design)}>
|
||||
@@ -68,6 +53,7 @@ export default function TemplatePage() {
|
||||
<Tabs label="Template and style" value={tab} onChange={setTab} tabs={[
|
||||
{ id: "template", label: "Template", icon: LayoutTemplate },
|
||||
{ id: "home", label: "Home page layout", icon: ListOrdered },
|
||||
{ id: "pages", label: "Other pages", icon: Files },
|
||||
{ id: "style", label: "Style", icon: SlidersHorizontal },
|
||||
]} />
|
||||
|
||||
@@ -94,11 +80,10 @@ export default function TemplatePage() {
|
||||
)}
|
||||
|
||||
{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's colours (a layout with a photo or band keeps its own). What each section says is on the home page, under Pages, where you can change all of this too.</>}>
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{design.home.map((e, i) => {
|
||||
const recommended = options.variants[design.template]?.[e.section] ?? [];
|
||||
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
|
||||
const { ordered, recommended } = layoutsFor(design, options, e.section);
|
||||
return (
|
||||
<li key={e.section} className={cx("flex flex-wrap items-center gap-3 py-3", e.hidden && "opacity-60")}>
|
||||
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-100 text-xs font-semibold text-gray-600" aria-hidden>{i + 1}</span>
|
||||
@@ -107,8 +92,18 @@ export default function TemplatePage() {
|
||||
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}>
|
||||
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
{/* 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: withBackground(design.home, e.section, ev.target.value) })}>
|
||||
{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">
|
||||
<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: withShown(design.home, e.section, ev.target.checked) })} />
|
||||
Show
|
||||
</label>
|
||||
<span className="ml-auto flex gap-1">
|
||||
@@ -122,6 +117,28 @@ export default function TemplatePage() {
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{tab === "pages" && (
|
||||
<Panel title="Other pages: layouts" icon={Files} sub={<>How the pages that list something show it. Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best, and the first of those is its suggestion. Each page's own blocks show after what it lists.</>}>
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{Object.entries(PAGE_LAYOUTS).map(([kind, { name }]) => {
|
||||
const p = pageLayoutsFor(design, options, kind)!;
|
||||
return (
|
||||
<li key={kind} className="flex flex-wrap items-center gap-3 py-3">
|
||||
<span className="w-36 font-medium">{name}</span>
|
||||
<select aria-label={`${name} page layout`} className={`${inputClass} w-72`} value={design.variants[p.key] ?? p.ordered[0]} disabled={busy}
|
||||
onChange={(ev) => save({ variants: { [p.key]: ev.target.value } })}>
|
||||
{p.ordered.map((v) => <option key={v} value={v}>{p.names[v]}{v === p.recommended[0] ? " (suggested)" : p.recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
{design.variants[p.key] !== p.recommended[0] && p.recommended[0] && (
|
||||
<Btn disabled={busy} onClick={() => save({ variants: { [p.key]: p.recommended[0]! } })}>Use the suggestion</Btn>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{tab === "style" && (
|
||||
<Panel title="Style" icon={SlidersHorizontal} sub="The finishing touches, on every page.">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
|
||||
@@ -59,18 +59,18 @@ h1, h2, h3 {
|
||||
* Section colour: tinted alternates the church colour as a soft background; mixed adds dark bands.
|
||||
* Never on a section that sets its own background (cc-own-bg: a banner, a photo, a dark band).
|
||||
*/
|
||||
[data-section-colour="tinted"] .cc-section:not(.cc-own-bg):nth-of-type(even) { background: rgb(var(--brand-tint)); }
|
||||
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) { background: rgb(var(--brand-dark)); color: rgb(var(--on-brand)); }
|
||||
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-card { background: rgb(255 255 255 / 0.06); border-color: rgb(255 255 255 / 0.2); color: inherit; }
|
||||
[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):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):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. */
|
||||
.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,
|
||||
[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):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-link,
|
||||
[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):not([data-bg]):nth-of-type(3n) .cc-brand-text { color: rgb(255 255 255); }
|
||||
|
||||
.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. */
|
||||
@@ -108,10 +108,32 @@ h1, h2, h3 {
|
||||
[data-buttons="pill"] .cc-btn { border-radius: 9999px; }
|
||||
[data-template="bold"] .cc-btn { @apply uppercase tracking-wider; }
|
||||
/* A button on a photo or a dark band: always light on dark. */
|
||||
.cc-on-dark .cc-btn, .cc-dark .cc-btn, [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-btn {
|
||||
.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);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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. */
|
||||
.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); }
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
* leaders, events, messages, contact details), then its blocks.
|
||||
*/
|
||||
import { preload } from "react-dom";
|
||||
import { LazyMap } from "./LazyMap";
|
||||
import { MessagePlayer } from "./MessagePlayer";
|
||||
import { t } from "./load";
|
||||
import { cx, DateBadge, dayName, fmtDate, Img, Paragraphs } from "./parts";
|
||||
import { EventLine, Sections } from "./sections";
|
||||
import type { Page, Published } from "./types";
|
||||
import type { Page, Published, Template } from "./types";
|
||||
|
||||
function PageTitle({ page, site }: { page: Page; site: Published }) {
|
||||
const template = site.snapshot.design.template;
|
||||
@@ -21,98 +22,332 @@ function PageTitle({ page, site }: { page: Page; site: Published }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Listing({ page, site }: { page: Page; site: Published }) {
|
||||
const zone = site.church?.timezone ?? "Africa/Johannesburg";
|
||||
const template = site.snapshot.design.template;
|
||||
switch (page.kind) {
|
||||
case "ministries":
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap space-y-14">
|
||||
{site.snapshot.ministries.map((m, i) => (
|
||||
<article key={m.slug} id={m.slug} className="grid scroll-mt-24 items-center gap-8 md:grid-cols-2">
|
||||
<Img image={m.image} className={cx(i % 2 === 1 && "md:order-2", template === "community" && "rounded-[2rem]")} />
|
||||
<div><h2 className="cc-h2">{m.name}</h2>{m.summary && <p className="cc-muted mt-3 text-lg">{m.summary}</p>}<Paragraphs text={m.body} className="mt-4" /></div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
case "leadership":
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{site.snapshot.leaders.map((l) => (
|
||||
<article key={l.name}>
|
||||
<Img image={l.photo} ratio="aspect-square" className={cx((template === "heritage" || template === "community") && "rounded-full", "mx-auto max-w-[14rem]")} />
|
||||
<h2 className="cc-h3 mt-4 text-center">{l.name}</h2>
|
||||
{l.role && <p className="cc-muted text-center">{l.role}</p>}
|
||||
<Paragraphs text={l.bio} className="mt-3 !text-base" />
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
case "events":
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap">
|
||||
{site.events.length === 0 && <p className="cc-muted">Nothing on the calendar just now. Check back soon.</p>}
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{site.events.map((e) => (
|
||||
<li key={e.url + e.startsAt} className="flex gap-5 py-6">
|
||||
<DateBadge iso={e.startsAt} timeZone={zone} />
|
||||
<div><h2 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h2><EventLine e={e} timeZone={zone} />{e.summary && <p className="mt-2">{e.summary}</p>}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
case "messages": {
|
||||
// The first thumbnail is the largest thing on screen (Lighthouse's LCP): ask for it from the
|
||||
// <head>, rather than once the HTML has been read. Thumbnails come from the site itself.
|
||||
const thumb = site.messages[0]?.thumbnail;
|
||||
if (thumb) preload(thumb, { as: "image", fetchPriority: "high" });
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 sm:grid-cols-2">
|
||||
{site.messages.map((m, i) => (
|
||||
<article key={m.slug} id={m.slug} className="scroll-mt-24">
|
||||
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} priority={i === 0} />
|
||||
{m.series && <p className="cc-eyebrow mt-4">{m.series}</p>}
|
||||
<h2 className="cc-h3 mt-1">{m.title}</h2>
|
||||
<p className="cc-muted text-sm">{[m.speaker, m.passage, fmtDate(m.date, zone, { day: "numeric", month: "long", year: "numeric" })].filter(Boolean).join(" · ")}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
case "contact": {
|
||||
const c = site.church;
|
||||
if (!c) return null;
|
||||
const a = c.contact.address;
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 md:grid-cols-2">
|
||||
<div className="space-y-6">
|
||||
{a && <div><h2 className="cc-h3">Address</h2><address className="not-italic">{[a.line1, a.line2, a.suburb, a.city, a.postalCode].filter(Boolean).join(", ")}</address></div>}
|
||||
{c.contact.phone && <div><h2 className="cc-h3">Phone</h2><a className="cc-link" href={`tel:${c.contact.phone}`}>{c.contact.phone}</a></div>}
|
||||
{c.contact.whatsapp && <div><h2 className="cc-h3">WhatsApp</h2><a className="cc-link" href={`https://wa.me/${c.contact.whatsapp.replace(/\D/g, "")}`}>{c.contact.whatsapp}</a></div>}
|
||||
{c.contact.email && <div><h2 className="cc-h3">Email</h2><a className="cc-link break-all" href={`mailto:${c.contact.email}`}>{c.contact.email}</a></div>}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="cc-h3">Service times</h2>
|
||||
<ul className="mt-2 space-y-1">{c.serviceTimes.map((s, i) => <li key={i}>{dayName(s.day)} {s.time}{s.label && ` · ${s.label}`}</li>)}</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
/**
|
||||
* The layout a listing page is drawn in (backend variants.ts PAGE_VARIANTS): the design's, or the
|
||||
* look it had before it had layouts (LEGACY_PAGE_LAYOUTS) for a version published back then.
|
||||
*/
|
||||
const LEGACY: Record<string, string> = { ministries: "alternating", leadership: "grid", events: "list", messages: "grid", contact: "columns" };
|
||||
const layoutOf = (site: Published, kind: string) => site.snapshot.design.variants[`${kind}Page`] ?? LEGACY[kind];
|
||||
|
||||
const roundPhoto = (template: Template) => template === "heritage" || template === "community";
|
||||
|
||||
// ─── Ministries: Alternating · Cards · List ──────────────────────────────────────
|
||||
// Each ministry keeps its own anchor (#slug): the homepage's "Find out more" links to it.
|
||||
|
||||
function MinistriesPage({ site, template, layout }: Props) {
|
||||
const list = site.snapshot.ministries;
|
||||
if (layout === "cards") {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<ul className="cc-wrap grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{list.map((m) => (
|
||||
<li key={m.slug} id={m.slug} className="cc-card flex scroll-mt-24 flex-col">
|
||||
<Img image={m.image} sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw" className="rounded-none" />
|
||||
<div className="flex-1 p-6">
|
||||
<h2 className="cc-h3">{m.name}</h2>
|
||||
{m.summary && <p className="cc-muted mt-2 text-lg">{m.summary}</p>}
|
||||
<Paragraphs text={m.body} className="mt-3 !text-base" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (layout === "list") {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className={cx("cc-wrap divide-y", template === "heritage" ? "max-w-4xl divide-brand-text/20" : "divide-gray-200")}>
|
||||
{list.map((m) => (
|
||||
<article key={m.slug} id={m.slug} className="grid scroll-mt-24 gap-6 py-10 first:pt-0 last:pb-0 sm:grid-cols-[12rem_1fr]">
|
||||
<Img image={m.image} sizes="12rem" ratio="aspect-square" className={cx("max-w-[12rem]", template === "community" && "rounded-[1.5rem]")} />
|
||||
<div><h2 className="cc-h2">{m.name}</h2>{m.summary && <p className="cc-muted mt-2 text-lg">{m.summary}</p>}<Paragraphs text={m.body} className="mt-4" /></div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap space-y-14">
|
||||
{list.map((m, i) => (
|
||||
<article key={m.slug} id={m.slug} className="grid scroll-mt-24 items-center gap-8 md:grid-cols-2">
|
||||
<Img image={m.image} className={cx(i % 2 === 1 && "md:order-2", template === "community" && "rounded-[2rem]")} />
|
||||
<div><h2 className="cc-h2">{m.name}</h2>{m.summary && <p className="cc-muted mt-3 text-lg">{m.summary}</p>}<Paragraphs text={m.body} className="mt-4" /></div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Leadership: Grid · Featured · List ──────────────────────────────────────────
|
||||
|
||||
type Leader = Published["snapshot"]["leaders"][number];
|
||||
|
||||
function LeaderCard({ l, template }: { l: Leader; template: Template }) {
|
||||
return (
|
||||
<article>
|
||||
<Img image={l.photo} sizes="14rem" ratio="aspect-square" className={cx(roundPhoto(template) && "rounded-full", "mx-auto max-w-[14rem]")} />
|
||||
<h2 className="cc-h3 mt-4 text-center">{l.name}</h2>
|
||||
{l.role && <p className="cc-muted text-center">{l.role}</p>}
|
||||
<Paragraphs text={l.bio} className="mt-3 !text-base" />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadershipPage({ site, template, layout }: Props) {
|
||||
const people = site.snapshot.leaders;
|
||||
if (layout === "list") {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap max-w-4xl divide-y divide-gray-200">
|
||||
{people.map((l) => (
|
||||
<article key={l.name} className="grid gap-6 py-8 first:pt-0 last:pb-0 sm:grid-cols-[9rem_1fr]">
|
||||
<Img image={l.photo} sizes="9rem" ratio="aspect-square" className={cx("max-w-[9rem]", roundPhoto(template) && "rounded-full")} />
|
||||
<div><h2 className="cc-h3">{l.name}</h2>{l.role && <p className="cc-muted">{l.role}</p>}<Paragraphs text={l.bio} className="mt-3 !text-base" /></div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (layout === "featured" && people.length > 0) {
|
||||
const [lead, ...rest] = people as [Leader, ...Leader[]];
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap">
|
||||
<article className="grid items-center gap-10 md:grid-cols-[2fr_3fr]">
|
||||
<Img image={lead.photo} sizes="(min-width: 768px) 40vw, 100vw" ratio="aspect-[4/5]" className={cx("mx-auto w-full max-w-sm", template === "community" && "rounded-[2rem]")} />
|
||||
<div>
|
||||
<h2 className="cc-h2">{lead.name}</h2>
|
||||
{lead.role && <p className="cc-eyebrow mt-2">{lead.role}</p>}
|
||||
<Paragraphs text={lead.bio} className="mt-5" />
|
||||
</div>
|
||||
</article>
|
||||
{rest.length > 0 && <div className="mt-16 grid gap-10 sm:grid-cols-2 lg:grid-cols-3">{rest.map((l) => <LeaderCard key={l.name} l={l} template={template} />)}</div>}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{people.map((l) => <LeaderCard key={l.name} l={l} template={template} />)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Events: List · Cards · By month ─────────────────────────────────────────────
|
||||
|
||||
function EventsPage({ site, zone, layout }: Props) {
|
||||
const list = site.events;
|
||||
if (list.length === 0) return <section className="cc-section"><div className="cc-wrap"><p className="cc-muted">Nothing on the calendar just now. Check back soon.</p></div></section>;
|
||||
if (layout === "cards") {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<ul className="cc-wrap grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{list.map((e) => (
|
||||
<li key={e.url + e.startsAt} className="cc-card flex flex-col">
|
||||
<div className="relative">
|
||||
<Img image={e.image} sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw" ratio="aspect-[16/10]" className="rounded-none" />
|
||||
<DateBadge iso={e.startsAt} timeZone={zone} className="absolute left-4 top-4 shadow" />
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col p-5">
|
||||
<h2 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h2>
|
||||
<div className="mt-2"><EventLine e={e} timeZone={zone} /></div>
|
||||
{e.summary && <p className="mt-3">{e.summary}</p>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (layout === "months") {
|
||||
const months: { name: string; events: typeof list }[] = [];
|
||||
for (const e of list) {
|
||||
const name = fmtDate(e.startsAt, zone, { month: "long", year: "numeric" });
|
||||
if (months.at(-1)?.name === name) months.at(-1)!.events.push(e);
|
||||
else months.push({ name, events: [e] });
|
||||
}
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap max-w-4xl space-y-12">
|
||||
{months.map((m) => (
|
||||
<div key={m.name}>
|
||||
<h2 className="cc-h2 border-b-2 border-brand pb-2">{m.name}</h2>
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{m.events.map((e) => (
|
||||
<li key={e.url + e.startsAt} className="grid grid-cols-[3.5rem_1fr] gap-4 py-5">
|
||||
<p className="text-center" aria-hidden="true">
|
||||
<span className="font-heading cc-brand-text block text-3xl font-bold leading-none">{fmtDate(e.startsAt, zone, { day: "numeric" })}</span>
|
||||
<span className="cc-eyebrow mt-1 block text-xs">{fmtDate(e.startsAt, zone, { weekday: "short" })}</span>
|
||||
</p>
|
||||
<div><h3 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h3><EventLine e={e} timeZone={zone} />{e.summary && <p className="mt-2">{e.summary}</p>}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap">
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{list.map((e) => (
|
||||
<li key={e.url + e.startsAt} className="flex gap-5 py-6">
|
||||
<DateBadge iso={e.startsAt} timeZone={zone} />
|
||||
<div><h2 className="cc-h3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h2><EventLine e={e} timeZone={zone} />{e.summary && <p className="mt-2">{e.summary}</p>}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Messages: Grid · Latest first · List ────────────────────────────────────────
|
||||
// Each message keeps its own anchor (#slug).
|
||||
|
||||
type Message = Published["messages"][number];
|
||||
const messageMeta = (m: Message, zone: string) => [m.speaker, m.passage, fmtDate(m.date, zone, { day: "numeric", month: "long", year: "numeric" })].filter(Boolean).join(" · ");
|
||||
|
||||
/** A message as a row: its thumbnail, words and a link to watch or listen where it's published. */
|
||||
function MessageRow({ m, zone, first }: { m: Message; zone: string; first: boolean }) {
|
||||
return (
|
||||
<li id={m.slug} className="grid scroll-mt-24 items-center gap-5 py-6 sm:grid-cols-[12rem_1fr_auto]">
|
||||
<div className="cc-frame aspect-video max-w-[12rem]">
|
||||
{m.thumbnail
|
||||
? <img src={m.thumbnail} alt="" width={320} height={180} loading={first ? "eager" : "lazy"} decoding="async" className="cc-img" />
|
||||
: <div aria-hidden="true" className="h-full w-full bg-gradient-to-br from-brand/25 via-brand-tint to-accent/30" />}
|
||||
</div>
|
||||
<div>
|
||||
{m.series && <p className="cc-eyebrow">{m.series}</p>}
|
||||
<h2 className="cc-h3 mt-1">{m.title}</h2>
|
||||
<p className="cc-muted text-sm">{messageMeta(m, zone)}</p>
|
||||
</div>
|
||||
<a href={m.url} rel="noopener" className="cc-btn justify-self-start">{m.source === "spotify" ? "Listen" : "Watch"}<span className="sr-only">: {m.title}</span></a>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function MessagesPage({ site, zone, layout }: Props) {
|
||||
const list = site.messages;
|
||||
// The first thumbnail is the largest thing on screen (Lighthouse's LCP): ask for it from the
|
||||
// <head>, rather than once the HTML has been read. Thumbnails come from the site itself.
|
||||
const thumb = list[0]?.thumbnail;
|
||||
if (thumb) preload(thumb, { as: "image", fetchPriority: "high" });
|
||||
if (layout === "list") {
|
||||
return <section className="cc-section"><ul className="cc-wrap max-w-5xl divide-y divide-gray-200">{list.map((m, i) => <MessageRow key={m.slug} m={m} zone={zone} first={i === 0} />)}</ul></section>;
|
||||
}
|
||||
if (layout === "featured" && list.length > 0) {
|
||||
const [latest, ...rest] = list as [Message, ...Message[]];
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap">
|
||||
<article id={latest.slug} className="scroll-mt-24">
|
||||
<p className="cc-eyebrow mb-3">Latest message</p>
|
||||
<MessagePlayer title={latest.title} embedUrl={latest.embedUrl} thumbnail={latest.thumbnail} url={latest.url} source={latest.source} priority />
|
||||
{latest.series && <p className="cc-eyebrow mt-6">{latest.series}</p>}
|
||||
<h2 className="cc-h2 mt-1">{latest.title}</h2>
|
||||
<p className="cc-muted mt-2">{messageMeta(latest, zone)}</p>
|
||||
</article>
|
||||
{rest.length > 0 && <ul className="mt-12 divide-y divide-gray-200 border-t border-gray-200">{rest.map((m) => <MessageRow key={m.slug} m={m} zone={zone} first={false} />)}</ul>}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 sm:grid-cols-2">
|
||||
{list.map((m, i) => (
|
||||
<article key={m.slug} id={m.slug} className="scroll-mt-24">
|
||||
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} priority={i === 0} />
|
||||
{m.series && <p className="cc-eyebrow mt-4">{m.series}</p>}
|
||||
<h2 className="cc-h3 mt-1">{m.title}</h2>
|
||||
<p className="cc-muted text-sm">{messageMeta(m, zone)}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Contact: Two columns · With map · Cards ─────────────────────────────────────
|
||||
|
||||
function ContactPage({ site, layout }: Props) {
|
||||
const c = site.church;
|
||||
if (!c) return null;
|
||||
const a = c.contact.address;
|
||||
const address = a ? [a.line1, a.line2, a.suburb, a.city, a.postalCode].filter(Boolean).join(", ") : null;
|
||||
const directions = a && (a.geo
|
||||
? `https://www.openstreetmap.org/?mlat=${a.geo.lat}&mlon=${a.geo.lng}#map=17/${a.geo.lat}/${a.geo.lng}`
|
||||
: `https://www.openstreetmap.org/search?query=${encodeURIComponent([a.line1, a.suburb, a.city].filter(Boolean).join(", "))}`);
|
||||
const ways = [
|
||||
address && { key: "address", title: "Address", body: <><address className="not-italic">{address}</address>{layout !== "columns" && directions && <a href={directions} rel="noopener" className="cc-link mt-2 inline-block font-semibold">Get directions</a>}</> },
|
||||
c.contact.phone && { key: "phone", title: "Phone", body: <a className="cc-link" href={`tel:${c.contact.phone}`}>{c.contact.phone}</a> },
|
||||
c.contact.whatsapp && { key: "whatsapp", title: "WhatsApp", body: <a className="cc-link" href={`https://wa.me/${c.contact.whatsapp.replace(/\D/g, "")}`}>{c.contact.whatsapp}</a> },
|
||||
c.contact.email && { key: "email", title: "Email", body: <a className="cc-link break-all" href={`mailto:${c.contact.email}`}>{c.contact.email}</a> },
|
||||
].filter((w): w is { key: string; title: string; body: React.ReactElement } => !!w);
|
||||
const times = (
|
||||
<div>
|
||||
<h2 className="cc-h3">Service times</h2>
|
||||
<ul className="mt-2 space-y-1">{c.serviceTimes.map((s, i) => <li key={i}>{dayName(s.day)} {s.time}{s.label && ` · ${s.label}`}</li>)}</ul>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (layout === "cards") {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<ul className="cc-wrap grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{ways.map((w) => <li key={w.key} className="cc-card p-6"><h2 className="cc-h3 mb-2">{w.title}</h2>{w.body}</li>)}
|
||||
{c.serviceTimes.length > 0 && <li className="cc-card p-6">{times}</li>}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
const geo = a?.geo;
|
||||
if (layout === "map" && geo) {
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid items-stretch gap-10 md:grid-cols-2">
|
||||
<div className="space-y-6">
|
||||
{ways.map((w) => <div key={w.key}><h2 className="cc-h3">{w.title}</h2>{w.body}</div>)}
|
||||
{times}
|
||||
</div>
|
||||
<LazyMap href={directions}
|
||||
src={`https://www.openstreetmap.org/export/embed.html?bbox=${geo.lng - 0.006}%2C${geo.lat - 0.004}%2C${geo.lng + 0.006}%2C${geo.lat + 0.004}&layer=mapnik&marker=${geo.lat}%2C${geo.lng}`} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
// Two columns (and With map when the church's address has no place on the map yet).
|
||||
return (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 md:grid-cols-2">
|
||||
<div className="space-y-6">{ways.map((w) => <div key={w.key}><h2 className="cc-h3">{w.title}</h2>{w.body}</div>)}</div>
|
||||
{times}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type Props = { site: Published; template: Template; zone: string; layout: string };
|
||||
|
||||
const LISTINGS: Record<string, (p: Props) => React.ReactNode> = {
|
||||
ministries: MinistriesPage, leadership: LeadershipPage, events: EventsPage, messages: MessagesPage, contact: ContactPage,
|
||||
};
|
||||
|
||||
function Listing({ page, site }: { page: Page; site: Published }) {
|
||||
const L = LISTINGS[page.kind];
|
||||
if (!L) return null;
|
||||
return <L site={site} template={site.snapshot.design.template} zone={site.church?.timezone ?? "Africa/Johannesburg"} layout={layoutOf(site, page.kind) ?? ""} />;
|
||||
}
|
||||
|
||||
export function PageView({ page, site }: { page: Page; site: Published }) {
|
||||
|
||||
@@ -9,8 +9,9 @@ import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, Pict
|
||||
import type { SectionProps, SiteEvent } from "../types";
|
||||
import { Hero } from "./Hero";
|
||||
|
||||
const Section = ({ children, className, id }: { children: React.ReactNode; className?: string; id?: string }) => (
|
||||
<section id={id} className={cx("cc-section", className)}>{children}</section>
|
||||
/** `data-bg`: the section's own background, when the church gave it one (globals.css). */
|
||||
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";
|
||||
@@ -79,7 +80,7 @@ function ServiceTimes(p: SectionProps) {
|
||||
if (p.section.variant === "map") {
|
||||
const geo = p.site.church?.contact.address?.geo;
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap grid items-stretch gap-8 md:grid-cols-2">
|
||||
{panel}
|
||||
{geo ? (
|
||||
@@ -90,7 +91,7 @@ function ServiceTimes(p: SectionProps) {
|
||||
</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 ────────────────
|
||||
@@ -108,7 +109,7 @@ function Welcome(p: SectionProps) {
|
||||
if (p.section.variant === "pastor" && d.pastor) {
|
||||
const photo = media(p.site, d.pastor.photoId, p.section.data);
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]">
|
||||
<figure className={cx(centred && "text-center")}>
|
||||
<Img image={photo} ratio="aspect-[4/5]" className={cx(p.template === "community" && "rounded-[2rem]", centred && "mx-auto max-w-xs")} />
|
||||
@@ -122,7 +123,7 @@ function Welcome(p: SectionProps) {
|
||||
}
|
||||
if (p.section.variant === "image-text") {
|
||||
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")}>
|
||||
<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>
|
||||
@@ -130,7 +131,7 @@ function Welcome(p: SectionProps) {
|
||||
</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 ───────────────────────────────
|
||||
@@ -145,7 +146,7 @@ function Ministries(p: SectionProps) {
|
||||
|
||||
if (p.section.variant === "bands") {
|
||||
return (
|
||||
<Section className="!pb-0">
|
||||
<Section p={p} className="!pb-0">
|
||||
<div className="cc-wrap">{head}</div>
|
||||
<div className={cx(p.template === "bold" ? "" : "cc-wrap space-y-10")}>
|
||||
{list.map((m, i) => (
|
||||
@@ -165,7 +166,7 @@ function Ministries(p: SectionProps) {
|
||||
}
|
||||
if (p.section.variant === "list") {
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<ul className={cx("divide-y", p.template === "heritage" ? "mx-auto max-w-2xl divide-brand-text/20" : "divide-gray-200")}>
|
||||
@@ -181,7 +182,7 @@ function Ministries(p: SectionProps) {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<ul className={cx("grid gap-6", list.length > 3 ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-3")}>
|
||||
@@ -220,7 +221,7 @@ function Team(p: SectionProps) {
|
||||
);
|
||||
if (p.section.variant === "list") {
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<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") {
|
||||
const [lead, ...rest] = people;
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
{face(lead!, true)}
|
||||
@@ -242,7 +243,7 @@ function Team(p: SectionProps) {
|
||||
</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 ─────────────────────────────
|
||||
@@ -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>
|
||||
{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 more = page && <p className={cx("mt-8", p.template === "heritage" && "text-center")}><a href={page.path} className="cc-link font-semibold">All events</a></p>;
|
||||
if (!list.length) {
|
||||
return <Section><div className="cc-wrap">{head}<p className="cc-muted">Nothing on the calendar just now. Check back soon.</p></div></Section>;
|
||||
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") {
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<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") {
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<ol className="flex snap-x gap-4 overflow-x-auto pb-4">
|
||||
@@ -314,7 +320,7 @@ function Events(p: SectionProps) {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<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") {
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
<div className="flex flex-col gap-4 border-y border-gray-200 py-6 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div><p className="cc-eyebrow">{d.heading ?? "Latest message"}</p><p className="font-heading text-xl font-semibold">{m.title}</p><p className="cc-muted text-sm">{meta}</p></div>
|
||||
@@ -363,7 +369,7 @@ function LatestMessage(p: SectionProps) {
|
||||
}
|
||||
if (p.section.variant === "video") {
|
||||
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">
|
||||
{head}
|
||||
<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 (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
{head}
|
||||
<div className="cc-card grid items-center gap-0 md:grid-cols-2">
|
||||
@@ -414,7 +420,7 @@ function Invitation(p: SectionProps) {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap text-center">
|
||||
<h2 className="cc-h2">{d.heading}</h2>
|
||||
{d.text && <p className="cc-muted mx-auto mt-4 max-w-2xl text-lg">{d.text}</p>}
|
||||
@@ -424,29 +430,57 @@ function Invitation(p: SectionProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Blocks on the other pages ──────────────────────────────────────────────────
|
||||
// ─── Blocks on the other pages, each in its layouts (backend variants.ts BLOCK_VARIANTS) ──
|
||||
|
||||
// Text: Standard · Centred
|
||||
function TextBlock(p: SectionProps) {
|
||||
const d = p.section.data as { heading: string | null; body: string };
|
||||
return <Section><div className="cc-wrap"><div className="cc-text">{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /></div></div></Section>;
|
||||
return <Section p={p}><div className="cc-wrap"><div className={cx("cc-text", p.section.variant === "centred" && "text-center")}>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /></div></div></Section>;
|
||||
}
|
||||
|
||||
// Image and text: Photo on the left · Photo on the right · Photo above
|
||||
function ImageTextBlock(p: SectionProps) {
|
||||
const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData };
|
||||
const image = media(p.site, d.imageId, p.section.data);
|
||||
const round = p.template === "community" && "rounded-[2rem]";
|
||||
const words = <>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /><div className="mt-6"><Button button={d.button} /></div></>;
|
||||
if (p.section.variant === "image-above") {
|
||||
return (
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
<Img image={image} ratio="aspect-[16/9]" sizes="(min-width: 1280px) 1200px, 100vw" className={cx(round)} />
|
||||
<div className="cc-text mt-10">{words}</div>
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<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]")} />
|
||||
<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>
|
||||
<Img image={image} className={cx(round, p.section.variant === "image-right" && "md:order-2")} />
|
||||
<div>{words}</div>
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
// Quote: Centred · With a line
|
||||
function QuoteBlock(p: SectionProps) {
|
||||
const d = p.section.data as { quote: string; by: string | null };
|
||||
if (p.section.variant === "line") {
|
||||
return (
|
||||
<Section p={p}>
|
||||
<div className="cc-wrap">
|
||||
<figure className="cc-text border-l-4 border-accent pl-6">
|
||||
<blockquote className="font-heading text-2xl leading-snug sm:text-3xl">“{d.quote}”</blockquote>
|
||||
{str(d.by) && <figcaption className="cc-muted mt-4">{d.by}</figcaption>}
|
||||
</figure>
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section>
|
||||
<Section p={p}>
|
||||
<figure className="cc-wrap text-center">
|
||||
<blockquote className="font-heading mx-auto max-w-3xl text-2xl leading-snug sm:text-3xl">“{d.quote}”</blockquote>
|
||||
{str(d.by) && <figcaption className="cc-muted mt-4">{d.by}</figcaption>}
|
||||
@@ -455,8 +489,9 @@ function QuoteBlock(p: SectionProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// Call to action: Centred · Banner (the invitation's, without a photo)
|
||||
function CtaBlock(p: SectionProps) {
|
||||
return <Invitation {...p} section={{ ...p.section, variant: "centred", data: { ...p.section.data, imageId: null } }} />;
|
||||
return <Invitation {...p} section={{ ...p.section, variant: p.section.variant === "banner" ? "banner" : "centred", data: { ...p.section.data, imageId: null } }} />;
|
||||
}
|
||||
|
||||
const SECTIONS: Record<string, (p: SectionProps) => React.ReactNode> = {
|
||||
|
||||
@@ -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 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 = {
|
||||
kind: string;
|
||||
@@ -59,7 +60,7 @@ export type SiteEvent = {
|
||||
slug: string | null;
|
||||
link: string | null;
|
||||
from: "website" | "events" | "app";
|
||||
registration: { status: string; priceFromCents: number | null } | null;
|
||||
registration: { mode: string; status: string; priceFromCents: number | null } | null;
|
||||
};
|
||||
|
||||
export type SiteMessage = {
|
||||
|
||||
+28
-15
@@ -30,10 +30,15 @@ links with the Website and Cross Events, so the three feel like one church.
|
||||
**Where things stand:** every earlier phase is released and rolled out, including the Church Website
|
||||
at Hope Family Church and a second church (confirmed by Joshua 2026-11-30). **Phase 6 progress
|
||||
(2026-11-30):** `contracts@1.20.0` to `1.23.0`, `accounts@1.9.0`, `events@3.8.0`, `website@1.8.0` and
|
||||
`agent@1.7.0` and Hub `v2.26.0` released (not deployed yet), with the new shared package `@crosscode/demo` 1.1.0 (§12, "Demo scenarios").
|
||||
`agent@1.7.0` released (not deployed yet), with the new shared package `@crosscode/demo` 1.1.0
|
||||
(§12, "Demo scenarios"); Hub `v2.26.0` and `v2.26.1` with `contracts@1.24.0` (devotionals two years
|
||||
ahead, Apps fetch 2 weeks, today included) released, and **the Hub runs 2.26.1 with two years of
|
||||
Cross Code's devotionals** (Joshua, 2026-12-01).
|
||||
The Bible publishers' terms were checked ([BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)): 1.0
|
||||
uses only the free translations, the KJV and the Berean Standard Bible (decision 14, contracts 1.22.0).
|
||||
Next: deploy the Hub and write the first devotionals, then `app@1.0.0` (§15).
|
||||
**Now: `app@1.0.0`** (§15), built in slices (HANDOVER, "Next up"). The foundation is done
|
||||
(2026-12-01, `apps/app` on the branch `feat/app-scaffold`, pushed, merged into main when 1.0.0 is done; not released: §1, §2, the roles and active members of §10, the Hub
|
||||
client of §12); the House of Prayer is next.
|
||||
|
||||
**Who uses 1.0:** the demo church (cross-demo2, Acacia Hill) first, then Hope Family Church. Then
|
||||
it goes on sale (crosscode-site, ROADMAP §9).
|
||||
@@ -46,8 +51,8 @@ it goes on sale (crosscode-site, ROADMAP §9).
|
||||
- On a demo client, **Load a demo scenario** in the Hub loads Accounts, Events, the Website and
|
||||
the App with the same church, people and events, in one step (§12, "Demo scenarios").
|
||||
- The Hub holds at least 3 months of Cross Code devotionals (written or imported from CSV) in the free
|
||||
translations (KJV, BSB; decision 14), and an App set to "From Cross Code" shows and sends them
|
||||
with the translation's notice.
|
||||
translations (KJV, BSB; decision 14) (**done**: two years, Joshua 2026-12-01), and an App set to
|
||||
"From Cross Code" shows and sends them with the translation's notice.
|
||||
- A member can add the App to their home screen (Android and iPhone), sign in once, book a one-off
|
||||
or recurring prayer slot, get its reminder by email or WhatsApp, and change or cancel it within
|
||||
the rules.
|
||||
@@ -314,10 +319,13 @@ Decision 1: **two sources**, chosen in Settings → Devotionals:
|
||||
reference YouVersion understands, a date already taken), then import the valid rows, replacing
|
||||
or skipping days already filled. Columns: `date, title, passage, translation, passage_text,
|
||||
body, prayer, author`. A template CSV can be downloaded from the page.
|
||||
- **Getting them to the App:** an App on "From Cross Code" fetches the next **2 weeks** from the
|
||||
Hub (`GET /api/v2/devotionals`, with its licence token; Joshua, 2026-11-30: 2 weeks at most,
|
||||
contracts `CROSSCODE_DEVOTIONALS_FETCH_DAYS`) once a night and keeps them, so a Hub outage of
|
||||
less than 2 weeks changes nothing (ROADMAP §1, rule 2). Edits in the Hub reach the App by the next night, or at
|
||||
- **Getting them to the App:** the Hub holds up to two years (it has two, Joshua 2026-12-01), but
|
||||
sends an App only the next **2 weeks, today included**: today and the 13 days after it
|
||||
(`GET /api/v2/devotionals?from=<today in the church's timezone>`, with its licence token;
|
||||
Joshua, 2026-11-30: 2 weeks at most, contracts `CROSSCODE_DEVOTIONALS_FETCH_DAYS`). The App
|
||||
fetches once a night, replaces its copy of those 14 days and keeps what it already has (days
|
||||
before today stay for the archive), so a Hub outage of less than 2 weeks changes nothing
|
||||
(ROADMAP §1, rule 2). Edits in the Hub reach the App by the next night, or at
|
||||
once with **Sync now** in the App's settings. The format is `crosscode.devotional/1`
|
||||
(contracts 1.20.0), so a church's own and Cross Code's devotionals look the same.
|
||||
- **Our own:** the same fields and the same CSV import in the App's admin, scheduled as far ahead as
|
||||
@@ -549,11 +557,12 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
|
||||
| Repo | Change | Version |
|
||||
|------|--------|---------|
|
||||
| `crosscode-platform` `apps/app` | New (§1–§12), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `app@1.0.0` |
|
||||
| `crosscode-platform` `apps/app` | New (§1–§12), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `app@1.0.0` (**being built** on `feat/app-scaffold`; the foundation done 2026-12-01) |
|
||||
| `crosscode-platform` `packages/contracts` | `app` in `DEMO_PRODUCTS`, `APP_MODULES`, the `app` part of the church export, `crosscode.devotional/1` and its CSV rules, the translations, `messaging.get`, `whatsapp.optout` | `contracts@1.20.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `agent.DEMO_SCENARIOS`, `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS` | `contracts@1.21.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | The free translations only in 1.0 (`licence`, `FREE_BIBLE_TRANSLATION_IDS`, the CSV `translations` option), the Berean Standard Bible (`BSB`) added; the publishers' exact notices (`copyright`, `acknowledgement`, the Bible Society's `disclaimer`), `publisher` and `permissionsUrl`, `FREE_QUOTE_VERSES`, `quotedVerses`; `AFR83` named "Afrikaans 1983/1992-vertaling" | `contracts@1.22.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `seed-scenario`: a whole demo scenario in one job, on whatever the church has installed (`SEED_SCENARIO_JOB_MIN_AGENT`) | `contracts@1.23.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS` (24: the Hub's two years ahead), `CROSSCODE_DEVOTIONALS_FETCH_DAYS` (14: an App's nightly fetch), the CSV up to 800 rows and 8 MB | `contracts@1.24.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/accounts` | `messaging.get` for linked products, a hint when the messaging settings change, the WhatsApp opt-out for every product; demo data (the scenario's church profile with its logo and icon, and its people) | `accounts@1.9.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/events` | STOP stops all WhatsApp, passed to Accounts; the opt-out read from Accounts; a demo profile per scenario (its four kept) | `events@3.8.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/website` | Demo profiles take the scenario's people and events (`--scenario`) | `website@1.8.0` (**released 2026-11-30**) |
|
||||
@@ -562,7 +571,7 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
| `crosscode-platform` `packages/ui` | The tab bar and bottom sheet, if worth sharing; otherwise nothing | workspace |
|
||||
| `crosscode-platform` `packages/seo` | `Article` builder for devotionals and announcements; the icon generator for the manifest | workspace |
|
||||
| `crosscode-platform` `scripts/` | `products/app.sh`, `app.env.template.json`, bats tests | — |
|
||||
| `events-hub` | App in New install, its releases, env template, billing on the band, renewal check, FastPanel email, Devotionals (write, schedule up to two years ahead, Import CSV in the free translations, the endpoint for Apps), **Load a demo scenario** on a demo client (one `seed-scenario` job; vendored contracts 1.23.0) | Hub `v2.26.0` (**released 2026-11-30**) |
|
||||
| `events-hub` | App in New install, its releases, env template, billing on the band, renewal check, FastPanel email, Devotionals (write, schedule up to two years ahead, Import CSV in the free translations, the endpoint for Apps), **Load a demo scenario** on a demo client (one `seed-scenario` job; vendored contracts 1.23.0) | Hub `v2.26.0` (**released 2026-11-30**); `v2.26.1`: two years ahead, Apps fetch 2 weeks (**released 2026-11-30**) |
|
||||
| `crosscode-site` | Church App on sale (ROADMAP §9): its page, the active-member tiers, House of Prayer screenshots, the bundle examples (§10), FAQ, `SoftwareApplication` JSON-LD | `v1.10.0` |
|
||||
|
||||
## 14. Testing
|
||||
@@ -577,8 +586,9 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
can't open, a day already filled), the YouVersion links, the nightly Cross Code fetch (and the
|
||||
last copy kept when the Hub is down), `messaging.get`, the notice under every quoted passage
|
||||
(screen, email, WhatsApp), only the free translations offered and imported.
|
||||
- **Hub:** the Devotionals page, Import CSV with its preview, the 3-month limit, a translation that isn't
|
||||
free refused, and the endpoint refusing anything but an App licence.
|
||||
- **Hub:** the Devotionals page, Import CSV with its preview, the two-year limit (3 months in
|
||||
2.26.0), a translation that isn't free refused, the endpoint answering 14 days from `from` (today
|
||||
included) and refusing anything but an App licence.
|
||||
- **Playwright** (phone, tablet and desktop): browse signed out; sign in from a slot and land back
|
||||
on it with the sheet open (through 2FA); book once, weekly and daily; skip, change and cancel;
|
||||
the 8-hour rule; two browsers, one books, the other's view updates live (and with the stream
|
||||
@@ -603,9 +613,12 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
rolled out to every church (not yet).
|
||||
2. `contracts@1.21.0` (demo scenarios, **released 2026-11-30**), with the scenario demo loaders in Accounts 1.9.0, Events
|
||||
3.8.0, `website@1.8.0` and `agent@1.7.0` (**both released 2026-11-30**).
|
||||
3. Hub `v2.26.0` (vendored contracts 1.23.0; **released 2026-11-30**) deployed, and the first 3 months of Cross Code
|
||||
devotionals written or imported, in the KJV or BSB (decision 14).
|
||||
4. `app@1.0.0` tagged after the e2e and Lighthouse runs.
|
||||
3. Hub `v2.26.0` (vendored contracts 1.23.0; **released 2026-11-30**) and `v2.26.1` (contracts 1.24.0:
|
||||
two years ahead, Apps fetch 2 weeks, today included; **released 2026-11-30**) deployed, and the
|
||||
first 3 months of Cross Code devotionals written or imported, in the KJV or BSB (decision 14).
|
||||
**Done:** the Hub runs 2.26.1 and holds two years (Joshua, 2026-12-01).
|
||||
4. `app@1.0.0` tagged after the e2e and Lighthouse runs. **Being built** from 2026-12-01 on `feat/app-scaffold` (merged into main when done): the
|
||||
foundation is done (`apps/app/CHANGELOG.md`, "Unreleased"); the slices are in the HANDOVER.
|
||||
5. **cross-demo2** (Acacia Hill): New install → App, every demo scenario loaded once, the
|
||||
throwaway test above.
|
||||
6. **Hope Family Church:** New install → App; the prayer coordinators set the wall up before it's
|
||||
|
||||
+59
-17
@@ -1,6 +1,6 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-30. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-12-01. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
@@ -26,7 +26,7 @@ every release).
|
||||
| Phase | What | State |
|
||||
|-------|------|-------|
|
||||
| 0 | contracts 1.0.0 → 1.21.0 | **Released and in use.** Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
|
||||
| 1 | Hub 2.0 → 2.20.0 | **Released, deployed and tested** (Hub `v2.20.0`; now `v2.26.0`, VERSIONS.md) |
|
||||
| 1 | Hub 2.0 → 2.20.0 | **Released, deployed and tested** (Hub `v2.20.0`; now `v2.26.1`, released 2026-11-30 and running by 2026-12-01 with two years of devotionals; VERSIONS.md) |
|
||||
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released, rolled out and tested.** Every install adopted onto the monorepo |
|
||||
| 1c | Cross Events 2.3.x: authenticator app 2FA | **Released and rolled out** (carried into Accounts in phase 4) |
|
||||
| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.5.0` on every server: from 1.4.0 the Hub reads and changes frps's / frpc's config and probes ports before an install; from 1.5.0 one product of a church can be uninstalled, exported or purged) |
|
||||
@@ -35,12 +35,14 @@ every release).
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (`events@3.7.2` rolled out; `3.8.0` released 2026-11-30 for phase 6, not deployed; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
|
||||
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26. **Done** (confirmed by Joshua 2026-11-30): crosscode-site deployed, Hope Family Church and a second church live, the remaining release checks finished. Now `website@1.8.0` (VERSIONS.md) |
|
||||
| 6 | Church App 1.0.0 | **Under way** (planned and started 2026-11-30): [APP-1.0-PLAN.md](./APP-1.0-PLAN.md), decisions confirmed 2026-11-30 (decision 13, the demo scenarios, added the same day); mockup on the Design canvas "Church App 1.0 mockup". Released 2026-11-30, not deployed: `contracts@1.20.0` to `1.24.0`, `accounts@1.9.0`, `events@3.8.0`, `website@1.8.0`, `agent@1.7.0`, Hub `v2.26.0` and `v2.26.1` (below). Next: deploy the Hub, the first devotionals, `app@1.0.0` |
|
||||
| 6 | Church App 1.0.0 | **Under way** (planned and started 2026-11-30): [APP-1.0-PLAN.md](./APP-1.0-PLAN.md), decisions confirmed 2026-11-30 (decision 13, the demo scenarios, added the same day); mockup on the Design canvas "Church App 1.0 mockup". Released 2026-11-30: `contracts@1.20.0` to `1.24.0`, `accounts@1.9.0`, `events@3.8.0`, `website@1.8.0`, `agent@1.7.0` (not deployed), Hub `v2.26.0` and `v2.26.1` (running, with two years of Cross Code's devotionals; below). **`app@1.0.0` being built** from 2026-12-01 on the branch `feat/app-scaffold` (pushed; merged into main only when 1.0.0 is done): the foundation done, the modules next |
|
||||
| 7 | App 1.x | Not started |
|
||||
|
||||
## Released 2026-11-30 (phase 6, first steps)
|
||||
|
||||
Tagged and pushed on 2026-11-30, **not deployed yet** (Accounts and Events have one migration each; the Website and the agent none). Details in
|
||||
Tagged and pushed on 2026-11-30. **The Hub (2.26.1) runs**, with two years of Cross Code's
|
||||
devotionals (Joshua, 2026-12-01); the rest is **not deployed yet** (Accounts and Events have one
|
||||
migration each; the Website and the agent none). Details in
|
||||
[VERSIONS.md](./VERSIONS.md), [CHANGELOG.md](../CHANGELOG.md) and the apps' CHANGELOGs.
|
||||
|
||||
| Release | What |
|
||||
@@ -52,7 +54,7 @@ Tagged and pushed on 2026-11-30, **not deployed yet** (Accounts and Events have
|
||||
| `events@3.8.0`, `@crosscode/demo` 1.1.0 | STOP stops all WhatsApp (not only news), checked before every message and passed on to Accounts; the eight scenarios as Events demo profiles, around each church's own people and campuses |
|
||||
| `contracts@1.23.0`, `agent@1.7.0` | `seed-scenario`: a whole demo scenario in one job, on whatever the church has installed (Accounts first, the rest skipped, every release checked first); `seed-demo` for Accounts and the App, and `--scenario` passed on to every product |
|
||||
| `website@1.8.0` | A profile loaded with `--scenario` takes the scenario's people as its leaders and, with a linked Cross Events, shows Events' events through the feed instead of its own; `crosscode demo <church> website --scenario`; `packages/demo` built with the Website. No migration |
|
||||
| `contracts@1.24.0`, Hub `v2.26.1` | Devotionals up to two years ahead (a CSV of two years in one file); `GET /api/v2/devotionals` answers 2 weeks (what an App fetches each night). No migration |
|
||||
| `contracts@1.24.0`, Hub `v2.26.1` | Devotionals up to two years ahead (a CSV of two years in one file); `GET /api/v2/devotionals` answers 2 weeks, today included (what an App fetches each night). No migration |
|
||||
| Hub `v2.26.0` | The App from New install (Accounts 1.9.0 first) and in every product list and filter; **Load a demo scenario** on a demo client (one `seed-scenario` job, "out of step" installs); demo data for every product; the Website's and App's .env; **Devotionals** (3 months ahead, Import CSV, KJV/BSB only) and `GET /api/v2/devotionals` (hub-protocol.md §3c); the App's tier alert. One migration (Hub) |
|
||||
|
||||
All four were checked on PostgreSQL 18 (local, details in `temp/`, never committed): migrations,
|
||||
@@ -121,8 +123,9 @@ Family Church and a second church are live on the Website, crosscode-site sells
|
||||
Joshua 2026-11-30; VERSIONS.md, "Deployed / rolled out").
|
||||
|
||||
1. **Phase 6, Church App 1.0.0** (ROADMAP §7, §9), [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) §15.
|
||||
**Done 2026-11-30 (released, not deployed):** contracts 1.20.0 to 1.23.0, Accounts
|
||||
1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0. The Bible publishers' terms checked: none covers a sold app, so **1.0 uses only the
|
||||
**Done 2026-11-30 (released):** contracts 1.20.0 to 1.24.0, Accounts 1.9.0, Events 3.8.0,
|
||||
Website 1.8.0, agent 1.7.0 (not deployed), Hub 2.26.0 and 2.26.1 (running, with two years of
|
||||
devotionals). The Bible publishers' terms checked: none covers a sold app, so **1.0 uses only the
|
||||
free translations, the KJV and the Berean Standard Bible** (APP-1.0-PLAN decision 14); the
|
||||
permission requests for the others are drafted in [BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)
|
||||
for later, and nothing waits for them. **Next:**
|
||||
@@ -135,16 +138,45 @@ Joshua 2026-11-30; VERSIONS.md, "Deployed / rolled out").
|
||||
(`crosscode demo <church> --scenario <s>`) loads the scenario on every product the church
|
||||
has installed, skipping the rest, every release checked first; `crosscode demo <church> app` refused clearly until
|
||||
App 1.0.0 brings `scripts/products/app.sh` and the App's demo.
|
||||
3. ~~**Hub 2.26.0**~~: **released 2026-11-30** (not deployed). Was: the App in New install and releases, billing on
|
||||
the active-member band, **Load a demo scenario** on a demo client (one `seed-scenario` job,
|
||||
agent 1.7.0+: the server seeds whatever the client has installed, Accounts first; show the
|
||||
report's `loaded` / `skipped`), the **Devotionals** page
|
||||
(up to two years ahead from 2.26.1, Import CSV, the free translations only: KJV and BSB) and
|
||||
`GET /api/v2/devotionals`. **Next:** deploy it (`scripts/deploy.sh` in events-hub, one
|
||||
migration), then write or import the first 3 months of Cross Code devotionals in the KJV or
|
||||
BSB (Hub → Devotionals).
|
||||
4. **`app@1.0.0`** → cross-demo2 (every scenario loaded, the throwaway install from the Hub) →
|
||||
Hope Family Church → crosscode-site 1.10.0 (the App on sale).
|
||||
3. ~~**Hub 2.26.0**~~ and ~~**2.26.1**~~ (with contracts 1.24.0): **released 2026-11-30, and
|
||||
the Hub runs 2.26.1 with two years of Cross Code's devotionals** (Joshua, 2026-12-01). Was:
|
||||
the App in New install and releases, billing on the active-member band, **Load a demo
|
||||
scenario** on a demo client (one `seed-scenario` job, agent 1.7.0+: the server seeds
|
||||
whatever the client has installed, Accounts first; show the report's `loaded` /
|
||||
`skipped`), the **Devotionals** page (up to two years ahead from 2.26.1, Import CSV, the free
|
||||
translations only: KJV and BSB) and `GET /api/v2/devotionals`: an App gets **2 weeks, today
|
||||
included** (today and the 13 days after it) per fetch, once a night. Keep the Hub filled
|
||||
well ahead: a day missing there is missing in every App.
|
||||
4. **`app@1.0.0`: being built** (from 2026-12-01, `apps/app`) on the branch
|
||||
**`feat/app-scaffold`** (pushed to c-git), in slices, each with its tests. The branch is
|
||||
**not merged into main until `app@1.0.0` is done** (Joshua, 2026-12-01): build every slice
|
||||
there, merge main into it when docs or shared packages change on main, and leave main's
|
||||
`apps/app` the placeholder until then. Docs about the App's progress go to main as well.
|
||||
1. ~~**The foundation**~~ (done 2026-12-01, not released; `apps/app/CHANGELOG.md`,
|
||||
"Unreleased"): backend and frontend as the Website's; the Hub client (`CCP-`, product
|
||||
`app`, the active-member band in the heartbeat); links and sign-in through Accounts
|
||||
(everyone a Member; 8 days renewed up to 90; every role only with 2FA; the first Owner
|
||||
from `HUB_ADMIN_EMAIL`); modules on and off; the manifest, icons, service worker, "Add to
|
||||
home screen", the tab bar and Me; the admin's first dashboard. One migration (`init`,
|
||||
checked on PostgreSQL 18: applies, no diff). 27 backend tests.
|
||||
2. **House of Prayer** (§3): slots in the church's timezone, commitments as rules, the
|
||||
24-hour clock, live coverage (SSE), reminders, renewals, "I prayed", campaigns,
|
||||
testimonies, the access log.
|
||||
3. **Prayer requests** (§4), with moderation and escalation.
|
||||
4. **Announcements, devotionals and events** (§5–§7): Cross Code's devotionals fetched each
|
||||
night from the Hub (`from` = today in the church's timezone; the App replaces its copy of
|
||||
those 14 days and keeps the rest), the church's own with the CSV import, the event feed.
|
||||
5. **Email and WhatsApp** (§8): the church's settings from Accounts (`messaging.get`), the
|
||||
STOP check before every WhatsApp, the sends and their counts.
|
||||
6. **The rest of the admin** (§10): side menu, setup checklist, members and roles, settings,
|
||||
background jobs, audit and access logs; the export (§11) and backups.
|
||||
7. **Demo and servers**: the Acacia Hill demo and the eight scenarios (`cmd_demo_scenario`),
|
||||
`scripts/products/app.sh` and `app.env.template.json` (with the Hub's: the env template
|
||||
in three places).
|
||||
8. **e2e, axe and Lighthouse** (§14), then the tag.
|
||||
|
||||
Then cross-demo2 (every scenario loaded, the throwaway install from the Hub) → Hope Family
|
||||
Church → crosscode-site 1.10.0 (the App on sale).
|
||||
Deploying Accounts 1.9.0, Events 3.8.0 and Website 1.8.0 to the churches can happen any time before the App;
|
||||
a church without Cross Events gives WAWP the address in Accounts → Admin → Email and WhatsApp.
|
||||
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
|
||||
@@ -208,6 +240,16 @@ rollout.
|
||||
`user.updated`); every product checks it before sending (Events: `utils/whatsappStop.js`), and
|
||||
whichever product receives a STOP passes it on with `whatsapp.optout`. The App and the Website
|
||||
must do the same.
|
||||
- **Cross Code's devotionals** (Hub 2.26.1, contracts 1.24.0): the Hub schedules them up to two
|
||||
years ahead (`CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS`; two years are in it, Joshua 2026-12-01),
|
||||
an App fetches 2 weeks each night, today included (`CROSSCODE_DEVOTIONALS_FETCH_DAYS`, 14 days:
|
||||
today and the 13 after it; Joshua 2026-11-30: 2 weeks at most), so a day not filled 2 weeks
|
||||
ahead is missing in every App until it is. A CSV holds up to 800 rows (8 MB).
|
||||
- **The Church App's foundation** (from 2026-12-01, `apps/app` on `feat/app-scaffold`): ports 5400 (backend) and 3400
|
||||
(frontend) in development; `APP_SECRET`, `APP_URL`, `APP_API_URL` in its env template (the
|
||||
Hub reads `apps/app/env.template.json` at the tag); its session cookie is `cca_session`. A
|
||||
module's tables, jobs, export records and memoryDb defaults are added with the module. Every
|
||||
page that shows prayer is `noindex` (next.config.ts and robots.ts list `/prayer`).
|
||||
- **Bible text** (BIBLE-PERMISSIONS.md, from contracts 1.22.0): the Hub and the App offer only
|
||||
`FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB). Any other needs its publisher's written permission
|
||||
first, then brings its exact `copyright` line (and the Bible Society's `disclaimer` for
|
||||
|
||||
+1
-1
@@ -642,7 +642,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0). **Released 2026-11-18** (`accounts@1.0.0`, 1.0.1 on 2026-11-19); the VM test and a run on real Postgres are still to do before a church gets it | Every later product signs in through it |
|
||||
| 4 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide. **Planned 2026-11-19:** [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0; decisions confirmed 2026-11-19) | Breaking change, so a major version. **Moved before the Website on 2026-11-19** (decision 38): Events is the product churches use today, so Accounts is proven on real users first, and the Website then starts with a church whose people already have accounts |
|
||||
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.17.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.21.0). **Released 2026-11-26, done 2026-11-30** (Hope Family Church and a second church live, crosscode-site sells it) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
|
||||
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed). **Planned 2026-11-30:** [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) (with contracts 1.20.0 and 1.21.0, Accounts 1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0, Hub 2.26.0; also **demo scenarios**: eight preset churches loaded into every product of a demo client). contracts 1.20.0 to 1.23.0, Accounts 1.9.0, Events 3.8.0, Website 1.8.0 and agent 1.7.0 **released 2026-11-30**; next Hub 2.26.0, then App 1.0.0 | Starts with shared users and the feed already in place |
|
||||
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed). **Planned 2026-11-30:** [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) (with contracts 1.20.0 and 1.21.0, Accounts 1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0, Hub 2.26.0; also **demo scenarios**: eight preset churches loaded into every product of a demo client). contracts 1.20.0 to 1.24.0, Accounts 1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0 and Hub 2.26.0 / 2.26.1 **released 2026-11-30**; the Hub runs 2.26.1 with two years of devotionals; **App 1.0.0 being built** from 2026-12-01 on the branch `feat/app-scaffold` (the foundation done) | Starts with shared users and the feed already in place |
|
||||
| 7 | Church App 1.x | Reading plans, sermons, groups, pastoral care, serving, giving links, directory | After House of Prayer is in use |
|
||||
|
||||
Each phase adds help content, audit log entries, tests, a CHANGELOG entry and updates to the
|
||||
|
||||
+51
-20
@@ -1,6 +1,6 @@
|
||||
# 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.**
|
||||
|
||||
"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 |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.8.0** | `events@3.8.0` | 2026-11-30 |
|
||||
| Church Website | `crosscode-platform` (`apps/website`) | **1.8.0** | `website@1.8.0` | 2026-11-30 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.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.12.0** | `website@1.12.0` | 2026-12-01 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
@@ -30,21 +30,52 @@ 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/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/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
|
||||
| Website | `apps/website` | 1.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) |
|
||||
| App | `apps/app` | 0.0.0 (not started, phase 6) |
|
||||
| `@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.12.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 to 1.12.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) |
|
||||
|
||||
These shared packages ship inside the apps that use them, from the same checkout, so they don't
|
||||
need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Website 1.12.0 (2026-12-01):** the Ministries, Leadership, Events, Messages and Contact pages
|
||||
each get three layouts, set on the page in Pages or together under Template and style → Other
|
||||
pages, with the template's suggestion marked; a site saved before keeps its pages' look until
|
||||
it picks one. No migration, no contracts change, works with any Accounts. Checked: the Website
|
||||
backend tests (156), the frontend's typecheck and lint, the new page-layouts e2e suite (60).
|
||||
Not deployed.
|
||||
|
||||
- **Website 1.11.0 (2026-12-01):** the other pages' blocks get layouts (text, image and text,
|
||||
quote, call to action) and their own backgrounds in the church's colours, and the hero's Video
|
||||
layout gets a video: MP4 uploads up to 20 MB, where it was filmed taken out. **Migration**
|
||||
(`Section.background`, nullable). No contracts change, works with any Accounts. On a FastPanel
|
||||
site, the site's upload size limit must allow 20 MB. Checked: the Website backend tests (152),
|
||||
the frontend's typecheck and lint, the admin, variants and templates e2e suites. **Deployed** 2026-12-01.
|
||||
|
||||
- **Website 1.10.0 (2026-12-01):** the home page's editor (Pages → Home) sets each section's
|
||||
layout, background, order and whether it shows (still under Template and style too), and a
|
||||
section offers only the photos its layout shows, a slot for each (1 for Photo, Video and Split,
|
||||
3 for Collage, none for Text only). Frontend only: no migration, no contracts change, works with
|
||||
any Accounts. Checked: the Website frontend's typecheck and lint, the admin e2e suite (13 tests).
|
||||
**Deployed** 2026-12-01.
|
||||
|
||||
- **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. **Deployed** 2026-12-01.
|
||||
|
||||
- **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
|
||||
years in one file (800 rows, 8 MB). `GET /api/v2/devotionals` answers **2 weeks**
|
||||
years in one file (800 rows, 8 MB). `GET /api/v2/devotionals` answers **2 weeks, today included**
|
||||
(`CROSSCODE_DEVOTIONALS_FETCH_DAYS`), not 3 months: what an App fetches each night. No
|
||||
migration. Checked: contracts' tests (341), the Hub's backend tests (301), frontend typecheck and
|
||||
lint. Not deployed yet.
|
||||
lint. Deployed by 2026-12-01, with two years of Cross Code's devotionals imported (Joshua).
|
||||
- **Hub 2.26.0 (2026-11-30):** the Church App (APP-1.0-PLAN §6, §12). The App from New install on
|
||||
`app.<address>`, with Accounts 1.9.0 first (also without "requires" in its notes), and in every
|
||||
product list and filter (installs, Updates). **Load a demo scenario** on a demo client: one
|
||||
@@ -55,14 +86,14 @@ need their own tags until something outside this repo depends on them.
|
||||
`GET /api/v2/devotionals` for App licences (hub-protocol.md §3c). An alert when an App's
|
||||
active-member band is above its tier. Contracts 1.23.0 vendored. One migration
|
||||
(`20261130120000_app_scenarios_devotionals`, checked on PostgreSQL 18: applies, no diff).
|
||||
Checked: the backend tests (301), frontend typecheck, lint and build. Not deployed yet.
|
||||
Checked: the backend tests (301), frontend typecheck, lint and build. Deployed (2.26.1 runs).
|
||||
- **Server agent 1.7.0 + contracts 1.23.0 + crosscode script (2026-11-30):** demo scenarios
|
||||
(APP-1.0-PLAN §12): the `seed-scenario` job, one per scenario load, which the server runs on
|
||||
**whatever the client has installed** (Accounts first, the rest skipped, every release checked
|
||||
first, the first failure naming what's out of step); `seed-demo` for Accounts and the App, and
|
||||
`--scenario` passed on to every product. For the Hub 2.26.0's **Load a demo scenario** (it
|
||||
vendors contracts 1.23.0). Checked: contracts (340), the agent's tests (60, the two version
|
||||
numbers match), the script's demo bats (21), `npm run check`. Not rolled out yet (Update
|
||||
numbers match), the script's demo bats (21), `npm run check`. **Rolled out** 2026-12-01 (Update
|
||||
agent from the Hub).
|
||||
- **Church Website 1.8.0 + crosscode script (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): a
|
||||
profile loaded with `--scenario` takes the scenario's people as its leaders (the pastor first,
|
||||
@@ -87,7 +118,7 @@ need their own tags until something outside this repo depends on them.
|
||||
(814), the script's bats (demo and events, 17), typecheck and lint, and on PostgreSQL 18 the
|
||||
migration and every scenario and demo profile loaded. The database also shows an older, unrelated
|
||||
drift on `_EventNotifyRecipients` (an index Prisma now wants as a primary key), there before 3.8.0.
|
||||
Not deployed yet.
|
||||
**Deployed** 2026-12-01.
|
||||
- **Accounts 1.9.0 + `@crosscode/demo` 1.0.0 + crosscode script (2026-11-30):** Church App
|
||||
groundwork (APP-1.0-PLAN §8, §12): `messaging.get` and `messaging.changed`; the WhatsApp opt-out
|
||||
for every product (`whatsapp.optout`, Accounts' own WAWP webhook, `whatsapp_opted_out`, "Turn
|
||||
@@ -96,7 +127,7 @@ need their own tags until something outside this repo depends on them.
|
||||
1.21.0 and `packages/demo` (the `crosscode` script on `main` installs and builds it). Checked:
|
||||
Accounts' tests (99), `@crosscode/demo`'s (8), the script's bats (111), the workspace typecheck
|
||||
and lint, and on PostgreSQL 18 the migrations, scenario loads (2 457 people in 3.4 s), the
|
||||
opt-out and `npm run demo`. Not deployed yet.
|
||||
opt-out and `npm run demo`. **Deployed** 2026-12-01.
|
||||
- **Contracts 1.21.0 (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): `agent.DEMO_SCENARIOS`,
|
||||
eight fictional churches, one per Website demo profile, that load Accounts, Events, the Website
|
||||
and the App alike; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS`, a profile per
|
||||
@@ -452,11 +483,11 @@ you deploy one.
|
||||
|
||||
| What | Running | Since | Notes |
|
||||
|------|---------|-------|-------|
|
||||
| Hub | 2.25.1 | 2026-11-28 | Jobs → Product filter lists every product |
|
||||
| Agent on church-server1 | 1.6.0 | 2026-11-27 | |
|
||||
| Agent on the central server | 1.6.0 | 2026-11-27 | |
|
||||
| Cross Events (churches) | 3.7.2 | 2026-11-27 | |
|
||||
| Accounts (churches) | 1.8.0 | 2026-11-27 | |
|
||||
| Church Website (cross-demo2, the demo church) | 1.7.1 | 2026-11-30 | Photos move and zoom in their frame, ministries, leaders and events too |
|
||||
| cross-demo2 (demo church) | Accounts 1.8.0, Cross Events 3.7.2, Church Website 1.7.1 | 2026-11-30 | The first Church Website install (`demo2.crosscode.co.za`) |
|
||||
| Hub | 2.26.1 | by 2026-12-01 | The App, demo scenarios, Devotionals (two years of Cross Code's imported; Apps get 2 weeks, today included) |
|
||||
| Agent on church-server1 | 1.7.0 | 2026-12-01 | Demo scenarios (`seed-scenario`) |
|
||||
| Agent on the central server | 1.7.0 | 2026-12-01 | Demo scenarios (`seed-scenario`) |
|
||||
| Cross Events (churches) | 3.9.0 | 2026-12-01 | The church's details from Accounts everywhere, SVG logos in PDFs |
|
||||
| Accounts (churches) | 1.10.0 | 2026-12-01 | The shared colour field in Church profile |
|
||||
| Church Website (cross-demo2, the demo church) | 1.11.0 | 2026-12-01 | Block layouts and backgrounds, a video for the top of the page; home page laid out from its editor (1.10.0); section backgrounds (1.9.0) |
|
||||
| cross-demo2 (demo church) | Accounts 1.10.0, Cross Events 3.9.0, Church Website 1.11.0 | 2026-12-01 | The first Church Website install (`demo2.crosscode.co.za`) |
|
||||
| crosscode.co.za | 1.9.1 | 2026-11-28 | Web address examples say yourchurch |
|
||||
|
||||
Generated
+18
-8
@@ -51,7 +51,7 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -89,7 +89,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -134,7 +134,7 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -160,6 +160,7 @@
|
||||
"pg-boss": "^11.1.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"raw-body": "^3.0.0",
|
||||
"svg-to-pdfkit": "0.1.8",
|
||||
"swagger-ui-dist": "^5.34.0",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3",
|
||||
@@ -185,7 +186,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -362,7 +363,7 @@
|
||||
},
|
||||
"apps/website/backend": {
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.12.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
@@ -392,7 +393,7 @@
|
||||
},
|
||||
"apps/website/frontend": {
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.12.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -21285,6 +21286,15 @@
|
||||
"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": {
|
||||
"version": "5.34.0",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.34.0.tgz",
|
||||
@@ -23192,7 +23202,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.23.0",
|
||||
"version": "1.24.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
@@ -23244,7 +23254,7 @@
|
||||
},
|
||||
"packages/ui": {
|
||||
"name": "@crosscode/ui",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/dm-sans": "5.3.0",
|
||||
"@fontsource-variable/eb-garamond": "5.3.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/ui",
|
||||
"version": "0.3.0",
|
||||
"version": "0.4.0",
|
||||
"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)",
|
||||
"main": "src/index.tsx",
|
||||
|
||||
@@ -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 }) {
|
||||
return (
|
||||
<label className="mb-3 flex items-start gap-3 text-sm">
|
||||
|
||||
Reference in New Issue
Block a user