Compare commits

...
Author SHA1 Message Date
joshua 1e3004189a Merge branch 'feat/website-framing-everywhere' 2026-11-28 00:30:26 +02:00
joshuaandClaude Opus 5.5 0c521ff614 Website 1.7.1: move and zoom for ministries', leaders' and events' photos
1.7.0 had Move and zoom in page sections only. Ministries, Leadership
and Events now have it on their photo, in the frame the site uses for
the current template and layouts. Saved with the row as `framing`
({ x, y, zoom }, null for centred; cleared when the photo changes).
Ministries and leaders are drafts until Publish (snapshot, Discard and
Restore carry it); an event's shows once the event is published.
Versions published before this compare unchanged.

One migration: a nullable JSONB `framing` column on Ministry, Leader
and SimpleEvent.

Also: the 1.7.0 e2e test waits for the media library to load before
counting it (it could count an empty list).

Checked: Website backend tests (136) and typecheck, frontend typecheck
and lint, production build, admin e2e suite in Chromium (12).
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:27:54 +02:00
joshua 4897489fb1 Merge branch 'docs/all-on-latest' 2026-11-28 00:06:12 +02:00
joshuaandClaude Opus 5.5 1c69b0cce9 docs: everything deployed on latest (crosscode.co.za 1.9.1; old rollout notes closed)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:06:11 +02:00
joshua b3318941ae Merge branch 'docs/deployed-table-website-1.7.0' 2026-11-28 00:04:49 +02:00
joshuaandClaude Opus 5.5 2efafa166e docs: Hub 2.25.1 deployed; deployed table catches up with Events 3.7.2 and Website 1.7.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:04:48 +02:00
joshua e0c82fe314 Merge branch 'docs/hub-2.25.1' 2026-11-27 23:47:07 +02:00
joshuaandClaude Opus 5.5 a474cdcda6 docs: Hub 2.25.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:47:07 +02:00
joshua 8234bb3bc1 Merge branch 'docs/deployed-website-1.7.0' 2026-11-27 23:41:54 +02:00
joshuaandClaude Opus 5.5 dd86021302 docs: Website 1.7.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:41:53 +02:00
joshua 19c12ef09e Merge branch 'feat/website-photo-framing' 2026-11-27 23:34:10 +02:00
joshuaandClaude Opus 5.5 a9215ac4e4 Website 1.7.0: move and zoom photos in their frame; delete unused photos
- A section's photo (hero, welcome, invitation, image-text) shows in the
  shape of its frame for the current template and layout, with a Move and
  zoom dialog: drag or arrow keys to choose what stays in view, zoom to
  300%. Saved with the section as data.framing ({ x, y, zoom } by media
  id), a draft until published. The site draws it with object-position
  and scale() around that point; Bold split/collage frames now clip, and
  a zoomed photo stays inside Heritage's mat. Framing for photos a section
  no longer shows is dropped on save.
- Media library: each photo says where it's used; one used nowhere can be
  deleted with its files (DELETE /admin/media/:id, 409 IN_USE otherwise,
  audited as media_deleted).

Checked: Website backend tests (135) and typecheck, frontend typecheck,
lint and production build, and an e2e test of both flows in Chromium.
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:34:10 +02:00
joshua 25100bd749 Merge branch 'docs/deployed-events-3.7.2-website-1.6.1' 2026-11-27 15:41:07 +02:00
joshuaandClaude Opus 5.5 f68f695934 docs: Events 3.7.2 and Website 1.6.1 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:41:05 +02:00
joshua ebcee43594 Merge branch 'fix/feed-after-reseed' 2026-11-27 15:35:42 +02:00
joshuaandClaude Opus 5.5 7f681c9e81 Events 3.7.2 + Website 1.6.1: no duplicate events after a reseed; "Events site" in the header
A reseed gives every event a new id without listing the old ones in the
feed's `deleted`, and consumers only fetched ?updatedSince= after the first
sync, so the old copies stayed beside the new ones.

- Both: the 15-minute feed poll and "Sync now" fetch the whole list and
  drop copies that aren't in it; the fetch after event.changed stays
  incremental.
- Events set-demo.js keeps FeedEntry and marks its live entries removed,
  resets the links' lastGoodAt, then publishes the new feed, sends
  event.changed and fetches the linked products' events back in.
- Website loadDemo lists the old published events in FeedRemoval and sends
  event.changed after publishing.
- Website header: links to the church's other sites read "Events site"
  with an external-link icon, not a second "Events".

Checked: Website backend tests (133), Events backend tests (802), both
typechecks, Website frontend build. set-demo.js not run end to end (no
local database).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:35:38 +02:00
joshua a75d2f7b46 Merge branch 'docs/released-site-1.9.1' 2026-11-27 15:13:39 +02:00
joshuaandClaude Opus 5.5 2edb9f681a docs: crosscode.co.za 1.9.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:13:38 +02:00
joshua d299442015 Merge branch 'docs/deployed-everything' 2026-11-27 15:09:29 +02:00
joshuaandClaude Opus 5.5 9994cbd760 docs: everything deployed on the latest releases
Hub 2.25.0, agent 1.6.0 (church-server1 and the central server), Cross Events
3.7.1 and Accounts 1.8.0 at the churches, the Church Website 1.6.0 on
cross-demo2, crosscode.co.za 1.9.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:09:29 +02:00
joshua 0d6afc7cd1 Merge branch 'docs/released-site-1.9.0' 2026-11-27 15:06:25 +02:00
joshuaandClaude Opus 5.5 3539bf0ac0 docs: crosscode.co.za 1.9.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:06:24 +02:00
joshua ff3d9aefa2 Merge branch 'docs/released-site-1.8.1' 2026-11-27 14:55:00 +02:00
joshuaandClaude Opus 5.5 8c4f5f244c docs: crosscode.co.za 1.8.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:55:00 +02:00
joshua edac4ee767 Merge branch 'test/website-demo-profile' 2026-11-27 14:47:01 +02:00
joshuaandClaude Opus 5.5 090453e14a test: the Website e2e server loads a demo profile (/test/demo?profile=); docs: crosscode.co.za 1.8.0 released
For the crosscode-site screenshots of another church on each template. Test
helper only, no Website release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:47:01 +02:00
joshua 9c87208428 Merge branch 'docs/released-website-1.6.0' 2026-11-27 14:32:15 +02:00
joshuaandClaude Opus 5.5 f931226e74 docs: Website 1.6.0 and crosscode.co.za 1.7.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:32:14 +02:00
52 changed files with 968 additions and 128 deletions
+30
View File
@@ -2,6 +2,36 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## website@1.7.1 - 2026-11-28
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
One migration: a nullable `framing` column on `Ministry`, `Leader` and `SimpleEvent`. Details in
`apps/website/CHANGELOG.md`.
## website@1.7.0 - 2026-11-27
Photos can be moved and zoomed in their frame, and unused photos deleted. Details in
`apps/website/CHANGELOG.md`. No migration.
- **Move and zoom:** a section's photo shows in its frame's shape for the template and layout,
with a dialog to drag and zoom it; saved with the section (`data.framing`), a draft until
published.
- **Delete photos:** the media library says where each photo is used, and deletes one used nowhere
(its files too); `DELETE /api/v1/admin/media/:id` refuses one in use.
## events@3.7.2 + website@1.6.1 - 2026-11-27
Events shown on the other product's site no longer show twice after a reseed, and the Website's
header marks the link to the Events site. Details in each app's CHANGELOG. No migrations.
- **Both:** the 15-minute event-feed poll and "Sync now" fetch the whole list and drop copies that
aren't in it, so events a sibling lost without listing them in `deleted` (a reseed, a restore)
can't stay beside the new ones. The fetch after an `event.changed` stays incremental.
- **Events 3.7.2:** new demo data (`set-demo.js`) lists the old events as removed in the feed,
publishes the new ones and tells the Website at once, and fetches the Website's events back in.
- **Website 1.6.1:** loading a demo lists the old events as removed and tells Events; the header
shows "Events site" with an external-link icon instead of a second "Events".
## website@1.6.0 - 2026-11-27
The demo church has real photos, and photos in small frames load at their size. Details in
+17
View File
@@ -5,6 +5,23 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/).
## [3.7.2] - 2026-11-27
No migrations, no new settings.
### Fixed
- **New demo data no longer leaves the old events on the church's Website.** `set-demo.js`
truncated `FeedEntry`, so the feed never listed the old events in `deleted` and the Website kept
showing them beside the new ones. Now `FeedEntry` is kept and its live entries are marked removed,
the links' `lastGoodAt` is reset (their copies were truncated, so the next fetch is a full one),
and after loading the script publishes the new events, sends `event.changed` to the linked
products and fetches their events back in (`demoFeed`), so the Website's next page load is right.
- **Copies of a linked product's events can't stay forever.** The 15-minute `feed-sync` job and
"Sync now" fetch the whole list and drop copies that aren't in it (`syncLink(link, now, { full: true })`),
so events a sibling lost without listing them in `deleted` (a reseed, a restore) go within 15
minutes. The fetch after an `event.changed` still asks only for what changed.
## [3.7.1] - 2026-11-26
No migrations, no new settings.
+5
View File
@@ -12,6 +12,11 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.7.2
- **Fixed: events from your Church Website could show twice** after the website's content was
replaced. Cross Events now checks the full list every 15 minutes and removes events that are gone.
## 3.7.1
- **Connecting to your new Church Website works straight away**, so its events page can show your
+5 -1
View File
@@ -63,9 +63,13 @@ previous demo and creates it again.
| The admin account, including its login history, trusted devices and 2FA | Every other user |
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
| Links to the church's other products (Accounts, the Website) | Copies of the linked products' events (fetched again straight away) |
| The event feed's history: the old events are listed as removed | |
The wipe and the new data are written in one database transaction. If that fails,
nothing changes. The past events' cashups run straight afterwards, through the same
nothing changes. Since 3.7.2 the script then publishes the new events in the event feed and
tells the linked products (the Church Website), so their next page load shows the new events
and not the old ones, and fetches the linked products' events back in. The past events' cashups run straight afterwards, through the same
code as the cashup screen. If one of those fails, re-run the script.
---
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.1",
"version": "3.7.2",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+42
View File
@@ -79,6 +79,9 @@ const KEEP_TABLES = new Set([
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
// its link nobody can sign in). Their feeds are data and go.
'ProductLink', 'LinkNonce',
// 3.7.2: what the feed last published. Its live entries are marked removed instead (clearData),
// so linked products are told the old events are gone, not left showing them beside the new.
'FeedEntry',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -1823,6 +1826,10 @@ async function clearData(tx) {
await tx.$executeRawUnsafe(`UPDATE "User" SET ${[...new Set(userRefs.map(r => `"${r.column}" = NULL`))].join(', ')}`);
for (const table of deleteInstead) await tx.$executeRawUnsafe(`DELETE FROM "${table}"`);
}
// 3.7.2: every event the feed published goes into its `deleted` list, and the copies of linked
// products' events (truncated above) are fetched again in full.
await tx.feedEntry.updateMany({ where: { removedAt: null }, data: { removedAt: new Date() } });
await tx.productLink.updateMany({ data: { lastGoodAt: null } });
// Their password resets, 2FA codes and trusted devices go with them (onDelete: Cascade).
const { count } = await tx.user.deleteMany({ where: { id: { not: admin.id } } });
await tx.securityEvent.deleteMany({ where: { OR: [{ userId: null }, { userId: { not: admin.id } }] } });
@@ -1911,6 +1918,7 @@ async function main() {
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts(oldSubs);
const feed = await demoFeed();
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1963,6 +1971,40 @@ async function main() {
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
}
if (feed && feed.links) console.log(`Connected products: ${feed.told} of ${feed.links} told the events changed${feed.failed ? `; ${feed.failed} couldn't be fetched from (the next poll catches up)` : ''}.`);
}
/**
* The backend's own code: the compiled code (dist/) on a server, the TypeScript through tsx in
* development. With dist/, its database client is a second one, disconnected at the end.
*/
function backendModule(rel) {
const dist = path.join(__dirname, '..', 'dist', `${rel}.js`);
if (fs.existsSync(dist)) {
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
return require(dist);
}
require('tsx/cjs');
return require(`../src/${rel}.ts`);
}
/**
* 3.7.2: the new events published in the feed straight away, linked products (the Website) told,
* so their next page load shows the new events without the old (marked removed in clearData), and
* their events fetched back in. Never fails the demo: the jobs catch up within 15 minutes.
*/
async function demoFeed() {
try {
const { refreshAndNotify } = backendModule('feed/notify');
const { syncAll } = backendModule('feed/sync');
const { told } = await refreshAndNotify(new Date());
const synced = await syncAll(new Date());
const links = await prisma.productLink.count();
return { links, told, failed: synced.failed };
} catch (e) {
console.warn(`[warn] The feed couldn't be refreshed now (${e.message}); the backend's feed jobs catch up within 15 minutes.`);
return null;
}
}
/**
+8 -3
View File
@@ -23,9 +23,14 @@ type Link = { installId: string; product: string; url: string; showEvents: boole
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
export async function syncLink(link: Link, now = new Date()): Promise<SyncResult> {
/**
* `full` asks for the whole list and drops copies no longer in it: a sibling that loses events
* without listing them in `deleted` (a reseed, a restore) would otherwise leave stale copies
* beside the new ones for good.
*/
export async function syncLink(link: Link, now = new Date(), { full = false }: { full?: boolean } = {}): Promise<SyncResult> {
if (!link.showEvents) return { installId: link.installId, ok: true, imported: 0, deleted: 0 };
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
const since = !full && link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(link.url, FEED_PATHS.events, since ? { updatedSince: since.toISOString() } : {});
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
@@ -62,7 +67,7 @@ async function upsert(linkId: string, e: CrosscodeEvent) {
export async function syncAll(now = new Date()): Promise<{ links: number; failed: number }> {
const links: Link[] = await prisma.productLink.findMany({ where: { showEvents: true } });
let failed = 0;
for (const link of links) if (!(await syncLink(link, now)).ok) failed++;
for (const link of links) if (!(await syncLink(link, now, { full: true })).ok) failed++;
return { links: links.length, failed };
}
@@ -207,7 +207,7 @@ export const syncNow = defineRoute({
async handler({ params }) {
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
if (!link) throw notFound('That connected product');
await syncLink(link);
await syncLink(link, new Date(), { full: true });
return { data: await overview() };
},
});
@@ -399,6 +399,16 @@ describe('events from a linked product', () => {
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
});
test('a full fetch (the poll) drops copies of events the source lost without saying (a reseed)', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
db.t.importedEvent.set('website:old', { key: 'website:old', linkId: WEBSITE_ID });
const e = sample();
answer(feedOf([e]));
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW, { full: true });
expect(String(global.fetch.mock.calls[0][0])).not.toContain('updatedSince=');
expect([...db.t.importedEvent.keys()]).toEqual([`website:${e.id}`]);
});
test('deleted events go; never re-published in this site\'s own feed', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
const e = sample();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.1",
"version": "3.7.2",
"private": true,
"scripts": {
"dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.7.1",
"version": "3.7.2",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+63
View File
@@ -1,5 +1,68 @@
# Changelog — Church Website
## [1.7.1] — 2026-11-28
One migration (`20261128000000_photo_framing`: a nullable `framing` column on `Ministry`,
`Leader` and `SimpleEvent`), run by `crosscode deploy`. No new environment settings.
### Fixed
- **Move and zoom everywhere a photo is framed, not only in page sections.** 1.7.0 had it in the
page editor only. Ministries, Leadership and Events now have the same **Move and zoom** on their
photo, shown in the frame the site uses for the current template and layouts (`frameFor` types
`ministry`, `leader`, `event`; `RowFraming` in `admin/framing.tsx`). It's saved with the row as
`framing` (`{ x, y, zoom }`, null for centred) and cleared when the photo is removed or changed.
Ministries and leaders are drafts until Publish (in the snapshot, Discard and Restore, as
`image.focus` / `photo.focus`); an event's shows once the event is published, like the rest of
it. Versions published before this compare unchanged (no framing key), so nothing shows as a
pending change after the update.
## [1.7.0] — 2026-11-27
No migration, no new environment settings.
### Added
- **Move and zoom a photo in its frame.** In a section's form (the top of the page, Welcome,
Invitation, Image and text), a chosen photo shows in the shape of the frame the site puts it in
for the current template and layout (`admin/framing.tsx`, `frameFor`), with **Move and zoom**:
drag (or arrow keys) to choose what stays in view, zoom up to 300% to crop closer, Reset. It's
saved with the section as `data.framing` (by media id: `{ x, y, zoom }`), so it's a draft
like any other edit: the live preview shows it on Save, visitors after Publish. The site draws it
with `object-position` and `scale()` around the same point (`focusStyle` in `site/parts.tsx`);
the Bold split and collage frames now clip (`overflow-hidden`), and a zoomed photo in a
Heritage frame stays inside its mat. Framing for a photo the section no longer shows is dropped
when it's saved.
- **Delete photos from the media library.** Each photo says where it's used (draft pages and
their sections, ministries, leaders, series, events, the site icon, the live site, the church's
logo); one used nowhere has **Delete** (Editors and up), which removes the row and its files
(the photo and its responsive sizes, never outside the uploads folder) and frees the storage.
`DELETE /api/v1/admin/media/:id` refuses one in use (409 `IN_USE`, saying where); audited as
`media_deleted`.
## [1.6.1] — 2026-11-27
No migration, no new environment settings.
### Fixed
- **Events from Cross Events no longer show twice after Events is reseeded.** After the first
fetch, the Website only asked for what changed (`?updatedSince=`) and dropped a copy only when
the feed listed it in `deleted`. A reseed (or a restore) gives every event a new id without
listing the old ones, so the old copies stayed beside the new. The 15-minute poll and "Sync now"
now fetch the whole list and drop copies that aren't in it (`syncLink(…, { full: true })`); the
fetch after an `event.changed` still asks only for what changed.
- **Loading a demo (`npm run demo`, `crosscode demo … website`) tells Cross Events.** The old
published events go into the feed's `deleted` (`FeedRemoval`) and linked products get an
`event.changed`, so Events drops its copies straight away instead of showing them beside the
new ones.
### Changed
- **The header's links to the church's other sites say so:** "Events site" with an external-link
icon (title "Our separate site"), instead of "Events", which looked like a second link to this
site's own Events page.
## [1.6.0] — 2026-11-27
No migration, no new environment settings.
+24
View File
@@ -3,6 +3,30 @@
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.7.1
- **Move and zoom now works for ministries, your team and events too**, not only for page
sections. Edit a ministry, a person or an event, and press **Move and zoom** on its photo.
Ministries and people show it on your site once you publish; an event shows it once the event
is published.
## 1.7.0
- **Move and zoom your photos.** When you choose a photo for a section, you now see it in the
shape it has on your site. Press **Move and zoom** to drag it so the right part shows (faces,
not the ceiling) and zoom in to crop closer. Save, and the preview shows it; publish, and
visitors see it.
- **Delete photos you don't need.** In the **Media library**, each photo says where it's used.
Photos that aren't used anywhere have a **Delete** button, which frees up their storage.
## 1.6.1
- **The link to your Cross Events site is easier to tell apart** in your website's menu: it now
says "Events site" with a small arrow icon, so visitors don't mistake it for your website's own
Events page.
- **Fixed: events from Cross Events could show twice** after the Events site's data was replaced.
Your website now checks the full list every 15 minutes and removes events that are gone.
## 1.6.0
- **Photos load faster on phones.** Photos in small frames (the collage at the top of the
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-backend",
"version": "1.6.0",
"version": "1.7.1",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
@@ -0,0 +1,4 @@
-- Move and zoom for ministries', leaders' and events' photos (Website 1.7.1).
ALTER TABLE "Ministry" ADD COLUMN "framing" JSONB;
ALTER TABLE "Leader" ADD COLUMN "framing" JSONB;
ALTER TABLE "SimpleEvent" ADD COLUMN "framing" JSONB;
@@ -104,6 +104,8 @@ model Ministry {
summary String?
body String?
imageId String?
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
framing Json?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
@@ -117,6 +119,8 @@ model Leader {
role String?
bio String?
photoId String?
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
framing Json?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
@@ -170,6 +174,8 @@ model SimpleEvent {
location String?
description String?
imageId String?
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
framing Json?
link String?
/// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10).
ministryId String?
+9 -3
View File
@@ -9,13 +9,17 @@
import { z } from 'zod';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { Prisma } from '../generated/prisma/client.js';
import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.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';
type Who = { id: string; role: string };
/** A row's photo framing to save: kept only while it has a photo (a new photo starts centred). */
export const framingFor = (photo: string | null, f: { x: number; y: number; zoom: number } | null) => (photo && f ? f : Prisma.DbNull);
/** zod issues as `{ field: message }`, for the form. */
function fieldsOf(e: z.ZodError): Record<string, string> {
const out: Record<string, string> = {};
@@ -231,6 +235,7 @@ const ministrySchema = z.object({
summary: z.string().trim().max(300).nullable().default(null),
body: z.string().trim().max(8000).nullable().default(null),
imageId: z.string().uuid().nullable().default(null),
framing: rowFraming,
position: z.int().min(0).max(1000).optional(),
});
@@ -239,6 +244,7 @@ const leaderSchema = z.object({
role: z.string().trim().max(120).nullable().default(null),
bio: z.string().trim().max(4000).nullable().default(null),
photoId: z.string().uuid().nullable().default(null),
framing: rowFraming,
position: z.int().min(0).max(1000).optional(),
});
@@ -253,7 +259,7 @@ export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, b
const slug = m.slug ?? slugify(m.name);
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, framing: framingFor(m.imageId, m.framing), ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.ministry.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
@@ -274,7 +280,7 @@ export async function listLeaders(ctx: Ctx) {
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const l = check(leaderSchema, body);
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, framing: framingFor(l.photoId, l.framing), ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.leader.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
+5 -3
View File
@@ -9,10 +9,11 @@ import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { youtubeId, spotifyEmbed, messageThumbnail } from '../site/content.js';
import { rowFraming } from '../site/sections.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
import { notChangedSince } from './content.js';
import { framingFor, notChangedSince } from './content.js';
type Who = { id: string; role: string };
@@ -121,6 +122,7 @@ const eventSchema = z.object({
location: optional(500),
description: optional(8000),
imageId: z.string().uuid().nullable().default(null),
framing: rowFraming,
ministryId: z.string().uuid().nullable().default(null),
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
@@ -130,7 +132,7 @@ export async function listEvents(ctx: Ctx) {
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
return rows.map((e) => ({
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, framing: e.framing, link: e.link, ministryId: e.ministryId,
cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(),
}));
}
@@ -144,7 +146,7 @@ export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by:
if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
const data = {
title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description,
imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
imageId: e.imageId, framing: framingFor(e.imageId, e.framing), link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
+57
View File
@@ -147,6 +147,63 @@ export async function processImage(body: Buffer, kind: Kind, basePath: string) {
return { main, width, height, sizes, files };
}
/**
* Where each photo is used, so one in use is never deleted (it would leave a hole on the site):
* the draft pages and their sections, ministries, leaders, series, events, the site icon, the
* live site (the latest published version) and the church's logo. Returns a lookup by media id.
*/
export async function mediaUsage(ctx: Ctx): Promise<(m: { id: string; filename: string }) => string[]> {
const [pages, sections, ministries, leaders, series, events, settings, latest, church] = await Promise.all([
ctx.db.page.findMany({ where: { archivedAt: null } }),
ctx.db.section.findMany(),
ctx.db.ministry.findMany({ where: { archivedAt: null } }),
ctx.db.leader.findMany({ where: { archivedAt: null } }),
ctx.db.messageSeries.findMany(),
ctx.db.simpleEvent.findMany(),
ctx.db.appSetting.findMany(),
ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { snapshot: true } }),
import('../church/profile.js').then((p) => p.churchProfile(ctx)).catch(() => null),
]);
const titles = new Map(pages.map((p) => [p.id, p.title]));
const places: { label: string; text: string }[] = [
...pages.map((p) => ({ label: `${p.title} page`, text: String(p.imageId ?? '') })),
...sections.filter((s) => titles.has(s.pageId)).map((s) => ({ label: `${titles.get(s.pageId)} page`, text: JSON.stringify(s.data ?? null) })),
...ministries.map((m) => ({ label: `Ministry: ${m.name}`, text: String(m.imageId ?? '') })),
...leaders.map((l) => ({ label: `Leader: ${l.name}`, text: String(l.photoId ?? '') })),
...series.map((s) => ({ label: `Series: ${s.title}`, text: String(s.imageId ?? '') })),
...events.map((e) => ({ label: `Event: ${e.title}`, text: String(e.imageId ?? '') })),
...settings.filter((s) => !s.key.startsWith('hub_')).map((s) => ({ label: 'Site settings', text: s.value })),
{ label: 'The live site', text: JSON.stringify(latest?.snapshot ?? null) },
{ label: 'Church logo', text: JSON.stringify(church?.branding ?? null) },
];
return (m) => {
const url = mediaUrl(m.filename);
// A page's sections each name it: list each place once.
return [...new Set(places.filter((p) => p.text.includes(m.id) || p.text.includes(url)).map((p) => p.label))];
};
}
/** Deletes a photo and its files, unless it's used somewhere (then says where). */
export async function deleteMedia(ctx: Ctx, id: string, by: { id: string; role: string }) {
const row = await ctx.db.mediaAsset.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
const usedIn = (await mediaUsage(ctx))(row);
if (usedIn.length) {
throw new ApiError(409, 'IN_USE', `That photo is still used (${usedIn.join(', ')}). Take it out there first; if it's on the live site, publish after.`);
}
await ctx.db.mediaAsset.delete({ where: { id } });
const dir = uploadDir(ctx);
const sub = path.dirname(row.filename);
const sizes = Array.isArray(row.sizes) ? (row.sizes as Sizes) : [];
const files = [row.filename, ...sizes.flatMap((s) => [path.join(sub, s.webp), path.join(sub, s.jpg)])];
await Promise.all(files.map((f) => {
const full = path.resolve(dir, f);
// Never outside the uploads folder, whatever the row says.
return full.startsWith(dir + path.sep) ? fs.rm(full, { force: true }).catch(() => undefined) : undefined;
}));
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'media_deleted', targetType: 'media', targetId: id, metadata: { alt: row.alt, bytes: row.bytes } });
}
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
/** The open "Get more storage" request, if any: open until the limit goes up. */
+5 -5
View File
@@ -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 { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
@@ -96,10 +96,10 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
const s = await storage(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 })) };
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) })) };
}));
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) =>
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).
@@ -179,7 +179,7 @@ export function adminRouter(ctx: Ctx) {
r.post('/links/:id/sync', editor, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
return syncLink(ctx, link);
return syncLink(ctx, link, { full: true });
}));
r.put('/feed', editor, json, handle(async (req) => {
await ctx.settings.set('feed_publish', req.body?.publish === false ? 'false' : 'true');
+11 -2
View File
@@ -18,6 +18,7 @@ import { fileURLToPath } from 'node:url';
import { CHURCH_SCHEMA, WEBSITE_TEMPLATES, type agent, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { markRemoved, notifyLinks } 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';
@@ -248,6 +249,10 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
// The site icon is a setting, so its picture stays; every other picture goes with the content.
const faviconId = classic ? null : await ctx.settings.get('favicon_media_id');
// 1.6.1: the published events that go are listed in the feed's `deleted`, so linked products
// (Cross Events) drop their copies instead of showing them beside the new ones.
const gone = (await db.simpleEvent.findMany({ where: { publishedAt: { not: null } }, select: { id: true } })).map((e) => e.id);
for (const id of gone) await markRemoved(ctx, id, true);
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'siteVersion', 'siteDesign', 'slugHistory', 'previewLink'] as const) {
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
}
@@ -324,9 +329,13 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', thumbnailUrl, speaker, passage, seriesId: series.id, publishedAt: now } });
}
n = 0;
const made: string[] = [];
for (const [slug, title, inDays, description] of seed.events) {
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), imageId: img[`event${n++}`] ?? null, publishedAt: now } });
made.push((await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), imageId: img[`event${n++}`] ?? null, publishedAt: now } })).id);
}
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
const version = await publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
// Linked products fetch the feed now, not at their next poll (one try; the poll catches up).
await notifyLinks(ctx, [...gone, ...made]).catch(() => {});
return version;
}
+9 -5
View File
@@ -113,15 +113,19 @@ type LinkRow = { installId: string; product: string; url: string; showEvents: bo
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
/** Fetches one sibling's feed into read-only copies. */
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
/**
* Fetches one sibling's feed into read-only copies. `full` asks for the whole list and drops copies
* no longer in it: a sibling that loses events without listing them in `deleted` (a reseed, a
* restore) would otherwise leave stale copies beside the new ones for good.
*/
export async function syncLink(ctx: Ctx, link: LinkRow, { full = false }: { full?: boolean } = {}): Promise<SyncResult> {
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
if (!link.showEvents) {
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
}
const now = ctx.now();
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
const since = !full && link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
if (since) url.searchParams.set('updatedSince', since.toISOString());
@@ -153,11 +157,11 @@ export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
}
}
/** Every linked sibling, one after another; one failing never stops the rest. */
/** Every linked sibling's whole list, one after another; one failing never stops the rest. */
export async function syncAll(ctx: Ctx) {
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
let failed = 0;
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
for (const link of links) if (!(await syncLink(ctx, link, { full: true })).ok) failed++;
return { links: links.length, failed };
}
+2 -2
View File
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { buildSnapshot, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { buildSnapshot, framed, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
@@ -139,7 +139,7 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
};
const own: SiteEvent[] = simple.map((e) => ({
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
allDay: e.allDay, location: e.location, image: framed(image(e.imageId), e.framing), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
}));
const copies: SiteEvent[] = imported.flatMap((row) => {
const e = row.data as unknown as CrosscodeEvent;
+26 -4
View File
@@ -12,6 +12,26 @@ import type { SectionType } from './variants.js';
const text = (max: number) => z.string().trim().max(max);
const optional = (max: number) => text(max).nullable().default(null);
const mediaId = z.string().uuid();
/**
* How each photo sits in its frame, by media id: the point kept in view (`x`, `y`, 0 to 100 from
* the left and top, as CSS `object-position`) and how far it's zoomed in (1 fills the frame).
*/
export const focusSchema = z.object({ x: z.number().min(0).max(100), y: z.number().min(0).max(100), zoom: z.number().min(1).max(4) });
/** A ministry's, leader's or event's one photo: how it sits in its frame, or null (centred). */
export const rowFraming = focusSchema.nullable().default(null);
const framing = z.record(z.string().uuid(), focusSchema).optional();
/** Keeps framing only for the photos the section still shows (a removed photo's would hold it "in use"). */
function pruneFraming<T extends { framing?: Record<string, unknown> }>(d: T): T {
if (!d.framing) return d;
const ids = new Set<string>();
const walk = (x: unknown): void => {
if (typeof x === 'string') ids.add(x);
else if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
};
walk({ ...d, framing: undefined });
return { ...d, framing: Object.fromEntries(Object.entries(d.framing).filter(([id]) => ids.has(id))) };
}
/** A link on the site (`/visit`) or elsewhere (https only). */
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
@@ -25,7 +45,8 @@ export const SECTION_SCHEMAS = {
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
videoId: mediaId.nullable().default(null),
button,
}),
framing,
}).transform(pruneFraming),
serviceTimes: z.object({
heading: optional(80),
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
@@ -38,12 +59,13 @@ export const SECTION_SCHEMAS = {
body: text(4000).default(''),
imageId: mediaId.nullable().default(null),
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
}),
framing,
}).transform(pruneFraming),
ministries: z.object({ heading: optional(80), intro: optional(400) }),
team: z.object({ heading: optional(80), intro: optional(400) }),
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
latestMessage: z.object({ heading: optional(80) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null), framing }).transform(pruneFraming),
} as const satisfies Record<SectionType, z.ZodType>;
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
@@ -51,7 +73,7 @@ export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
export const BLOCK_SCHEMAS = {
text: z.object({ heading: optional(120), body: text(20000) }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button, framing }).transform(pruneFraming),
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
} as const;
+24 -7
View File
@@ -16,7 +16,21 @@ import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionTy
export const SNAPSHOT_VERSION = 1;
/** An image to show: the photo, and its responsive sizes as `srcset`s when it has them (§3). */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string }; focus?: Focus };
/** How a photo sits in its frame (Move and zoom): the point kept in view and the zoom. */
export type Focus = { x: number; y: number; zoom: number };
/** A row's saved framing, if it is one (a Json column: anything else is ignored). */
export function focusOf(f: unknown): Focus | undefined {
const x = f as Partial<Focus> | null | undefined;
return x && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.zoom === 'number' ? { x: x.x, y: x.y, zoom: x.zoom } : undefined;
}
/** The image with its framing, when it has one. */
export const framed = (img: Image | null, f: unknown): Image | null => {
const focus = img ? focusOf(f) : undefined;
return img && focus ? { ...img, focus } : img;
};
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
@@ -89,8 +103,8 @@ export type Source = {
inNav: boolean; position: number; imageId: string | null;
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
}[];
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
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 }[];
};
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
@@ -105,6 +119,9 @@ export async function readWorkingCopy(ctx: Ctx) {
return { design, pages, ministries, leaders };
}
/** Framing in a source row only when there is some: versions published before it compare equal. */
const withFraming = (f: unknown) => (focusOf(f) ? { framing: focusOf(f) } : {});
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
return {
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
@@ -113,8 +130,8 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
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 })),
})),
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
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 })),
};
}
@@ -179,8 +196,8 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
v: SNAPSHOT_VERSION,
design: d,
pages: snapshotPages,
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: framed(image(m.imageId), m.framing) })),
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: framed(image(l.photoId), l.framing) })),
media: used,
redirects: {},
source,
+3 -2
View File
@@ -12,6 +12,7 @@
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { Prisma } from '../generated/prisma/client.js';
import { audit } from '../lib/audit.js';
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
@@ -103,14 +104,14 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
if (what === 'ministry') {
const m = source?.ministries.find((x) => x.id === id);
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, framing: (m.framing ?? Prisma.DbNull) as never, position: m.position, archivedAt: null, ...stamp };
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
return;
}
if (what === 'leader') {
const l = source?.leaders.find((x) => x.id === id);
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, framing: (l.framing ?? Prisma.DbNull) as never, position: l.position, archivedAt: null, ...stamp };
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
return;
}
+36
View File
@@ -226,3 +226,39 @@ describe('uploads and storage (§10, decision 12)', () => {
assert.equal((await as.get('/media')).body.storage.full, true);
});
});
describe('move and zoom for ministries, leaders and events', () => {
it('saves framing with the row, publishes it onto the photo, drops it with the photo, and leaves old versions unchanged', async () => {
const { as, app } = await signedIn('editor');
// Published before framing existed: nothing shows as changed.
assert.deepEqual((await as.get('/changes')).body, []);
const focus = { x: 20, y: 70, zoom: 1.6 };
const m = ((await as.get('/ministries')).body as { id: string; name: string; imageId: string; updatedAt: string }[])[0]!;
assert.ok(m.imageId);
assert.equal((await as.put(`/ministries/${m.id}`, { name: m.name, imageId: m.imageId, framing: focus })).status, 200);
assert.equal((await as.put(`/ministries/${m.id}`, { name: m.name, imageId: m.imageId, framing: { x: 200, y: 0, zoom: 1 } })).status, 400);
const l = ((await as.get('/leaders')).body as { id: string; name: string; photoId: string }[])[0]!;
assert.equal((await as.put(`/leaders/${l.id}`, { name: l.name, photoId: l.photoId, framing: focus })).status, 200);
assert.deepEqual(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, focus);
assert.deepEqual((await as.get('/changes')).body.map((c: { what: string }) => c.what).sort(), ['leader', 'ministry']);
assert.equal((await as.post('/publish')).status, 200);
const site = (await request(app).get('/api/v1/site/content')).body;
assert.deepEqual(site.snapshot.ministries.find((x: { name: string }) => x.name === m.name).image.focus, focus);
assert.deepEqual(site.snapshot.leaders.find((x: { name: string }) => x.name === l.name).photo.focus, focus);
// Discard puts the published framing back; a photo removed takes its framing with it.
await as.put(`/leaders/${l.id}`, { name: l.name, photoId: null, framing: focus });
assert.equal(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, null);
assert.equal((await as.post('/discard', { key: `leader:${l.id}` })).status, 200);
assert.deepEqual(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, focus);
// Events: saved with the event, shown on the live site straight away once published.
const e = ((await as.get('/events')).body as { id: string; title: string; startsAt: string; endsAt: string | null; imageId: string | null }[]).find((x) => x.imageId)!;
assert.equal((await as.put(`/events/${e.id}`, { title: e.title, startsAt: e.startsAt, endsAt: e.endsAt, imageId: e.imageId, framing: focus })).status, 200);
assert.deepEqual(((await as.get('/events')).body as { id: string; framing: unknown }[]).find((x) => x.id === e.id)!.framing, focus);
const live = (await request(app).get('/api/v1/site/content')).body;
assert.deepEqual(live.events.find((x: { title: string }) => x.title === e.title).image.focus, focus);
});
});
+13
View File
@@ -135,6 +135,19 @@ describe('showing events from Cross Events (Show events from)', () => {
assert.equal(await db.importedEvent.count(), 0);
});
it('a full fetch (the 15-minute poll) drops copies of events Events lost without saying (a reseed)', async () => {
const { ctx, events, link, db } = await site();
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Family Fun Day', 10)] };
await syncLink(ctx, await link());
// Reseeded: the same event under a new id, and no word about the old one.
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c', 'Family Fun Day', 10)] };
await syncLink(ctx, await link());
assert.equal(await db.importedEvent.count(), 2, 'an incremental fetch can\'t know');
await syncLink(ctx, await link(), { full: true });
assert.doesNotMatch(events.state.asked.at(-1)!, /updatedSince=/);
assert.deepEqual((await db.importedEvent.findMany()).map((e) => e.originId), ['9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c']);
});
it('switching Show events off removes its events; a signed event.changed fetches at once', async () => {
const { ctx, events, link, db, go, app } = await site();
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10)] };
+58
View File
@@ -0,0 +1,58 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { parseSectionData } from '../src/site/sections.js';
import { harness, SITE } from './support/harness.js';
async function site() {
const uploads = await fs.mkdtemp(path.join(os.tmpdir(), 'ccw-media-'));
const h = await harness({ linked: false, env: { UPLOAD_DIR: uploads } });
const id = '00000000-0000-4000-8000-00000000000a';
await h.db.websiteUser.create({ data: { id, name: 'Ann', email: 'ann@hope.test', role: 'editor' } });
await h.db.session.create({ data: { tokenHash: hashToken('ann'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'delete', p: string) => request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=ann').set('Origin', SITE);
return { ...h, go, uploads };
}
describe('deleting photos', () => {
it('deletes one that is not used, with its files, and refuses one that is, saying where', async () => {
const { go, db, uploads, ctx } = await site();
const dir = path.resolve(ctx.config.uploadDir ?? uploads);
await fs.mkdir(path.join(dir, '2026/11'), { recursive: true });
for (const f of ['old.jpg', 'old-480.webp', 'old-480.jpg']) await fs.writeFile(path.join(dir, '2026/11', f), 'x');
const old = await db.mediaAsset.create({ data: { filename: '2026/11/old.jpg', mime: 'image/jpeg', bytes: 3, width: 960, sizes: [{ w: 480, webp: 'old-480.webp', jpg: 'old-480.jpg' }] } });
const used = await db.mediaAsset.create({ data: { filename: '2026/11/used.jpg', mime: 'image/jpeg', bytes: 3 } });
const page = await db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
await db.section.create({ data: { pageId: page.id, type: 'hero', data: { headline: 'Hi', images: [used.id] } } });
const list = (await go('get', '/media')).body.items as { id: string; usedIn: string[] }[];
assert.deepEqual(list.find((m) => m.id === used.id)!.usedIn, ['Home page']);
assert.deepEqual(list.find((m) => m.id === old.id)!.usedIn, []);
const refused = await go('delete', `/media/${used.id}`);
assert.equal(refused.status, 409);
assert.match(refused.body.error.message, /Home page/);
assert.ok(await db.mediaAsset.findUnique({ where: { id: used.id } }));
assert.equal((await go('delete', `/media/${old.id}`)).status, 200);
assert.equal(await db.mediaAsset.findUnique({ where: { id: old.id } }), null);
assert.deepEqual(await fs.readdir(path.join(dir, '2026/11')), []);
assert.equal((await go('delete', `/media/${old.id}`)).status, 404);
});
});
describe('framing a photo in its frame', () => {
it('keeps where each photo sits and how far it is zoomed, and refuses nonsense', () => {
const id = '11111111-1111-4111-8111-111111111111';
const ok = parseSectionData('hero', { headline: 'Hi', images: [id], framing: { [id]: { x: 30, y: 60, zoom: 1.5 } } });
assert.deepEqual(ok?.framing, { [id]: { x: 30, y: 60, zoom: 1.5 } });
assert.equal(parseSectionData('image-text', {})?.framing, undefined);
// A photo taken out of the section takes its framing with it (or it would count as "in use").
assert.deepEqual(parseSectionData('hero', { headline: 'Hi', images: [], framing: { [id]: { x: 30, y: 60, zoom: 1 } } })?.framing, {});
assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null);
});
});
+12
View File
@@ -188,6 +188,18 @@ describe('the public site\'s content', () => {
assert.equal((await siteContent(h.ctx)).church?.name, 'Acacia Hill Church', 'the profile saved by the first demo stays');
});
it('1.6.1: loading a demo again lists the old events as removed in the feed, so Cross Events drops its copies', async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const old = (await h.db.simpleEvent.findMany()).map((e) => e.id).sort();
assert.ok(old.length > 0);
await loadDemo(h.ctx, 'community-town', { uploadDir: dir });
assert.deepEqual((await h.db.feedRemoval.findMany()).map((r) => r.eventId).sort(), old);
const now = (await h.db.simpleEvent.findMany()).map((e) => e.id);
assert.ok(now.length > 0 && now.every((id) => !old.includes(id)));
});
it('1.3.0: a profile on a site with no church profile at all saves the demo one, so the site has a name', async () => {
const h = await harness({ linked: false });
await loadDemo(h.ctx, 'clean-campus', { uploadDir: tmp() });
@@ -9,13 +9,13 @@ import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
ministry: () => ({ summary: null, body: null, imageId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
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 }),
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, link: null, cancelled: 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 }),
siteVersion: () => ({ note: null }),
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
@@ -66,7 +66,9 @@ export function matches(row: Row, where: Row = {}): boolean {
});
}
const clone = <T>(x: T): T => structuredClone(x);
/** Prisma.DbNull / JsonNull (a nullable Json field set to null) are stored as null, as Postgres does. */
const nulls = (x: unknown) => (x && typeof x === 'object' && /^(Db|Json)Null$/.test(x.constructor?.name ?? '') ? null : x);
const clone = <T>(x: T): T => structuredClone(x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.entries(x).map(([k, y]) => [k, nulls(y)])) as T : x);
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
function order(rows: Row[], orderBy?: Row | Row[]) {
+60
View File
@@ -185,3 +185,63 @@ test("the admin's screens are accessible", async ({ page, context }) => {
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
expect(axe.violations.map((v) => `editor: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
});
test("move and zoom a photo in its frame, then delete a photo nothing uses", 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.getByRole("button", { name: "Move and zoom" }).first().click();
const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" });
await expect(dialog).toBeVisible();
await dialog.getByRole("slider").fill("2");
const box = (await dialog.getByLabel(/in its frame/).boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width / 2 + 80, box.y + box.height / 2 + 30, { steps: 5 });
await page.mouse.up();
await dialog.getByRole("button", { name: "Done" }).click();
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
await page.getByRole("button", { name: "Save", exact: true }).click();
await expect(page.getByText("Saved as a draft.")).toBeVisible();
// The live preview draws it the same way.
const frame = page.frameLocator('iframe[title="Live preview of this page"]');
await expect(frame.locator(".cc-section-hero img").first()).toHaveAttribute("style", /scale\(2\)/);
await page.screenshot({ path: "e2e/test-results/framing.png" });
// Upload one nothing uses, then delete it; one in use says where instead.
await page.goto("/admin/media");
// Count once the library has loaded (it can still be empty for a moment).
await expect(page.locator("main li").first()).toBeVisible();
const before = await page.locator("main li").count();
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
await page.locator('input[type="file"]').setInputFiles({ name: "dot.png", mimeType: "image/png", buffer: png });
await page.getByLabel("What the photo shows").fill("A dot to delete");
await page.getByRole("button", { name: "Upload" }).click();
await expect(page.locator("main li")).toHaveCount(before + 1);
await expect(page.getByText("Used on:").first()).toBeVisible();
page.once("dialog", (d) => d.accept());
await page.locator("main li").filter({ has: page.locator('input[value="A dot to delete"]') }).getByRole("button", { name: "Delete" }).click();
await expect(page.getByText("Deleted.")).toBeVisible();
await expect(page.locator("main li")).toHaveCount(before);
});
test("move and zoom a ministry's, a leader's and an event's photo", async ({ page, context }) => {
await signIn(context);
for (const [path, saved] of [["/admin/ministries", "Saved as a draft."], ["/admin/leaders", "Saved as a draft."], ["/admin/events", null]] as const) {
await page.goto(path);
await page.getByRole("button", { name: "Edit", exact: true }).first().click();
await page.getByRole("button", { name: "Move and zoom" }).first().click();
const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" });
await dialog.getByRole("slider").fill("2");
await dialog.getByRole("button", { name: "Done" }).click();
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
await page.getByRole("button", { name: "Save", exact: true }).click();
if (saved) await expect(page.getByText(saved)).toBeVisible();
else await expect(page.getByRole("button", { name: "Save", exact: true })).toHaveCount(0);
// Saved with the row: it's there when the form opens again.
await page.getByRole("button", { name: "Edit", exact: true }).first().click();
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
}
});
+11 -2
View File
@@ -4,7 +4,8 @@
* (freshPostgres, below), and the demo church published. The pages run as a production build on
* 3310 and send /api here.
*
* Test helpers: POST /test/demo?template=<id> loads the demo church on that template;
* Test helpers: POST /test/demo?template=<id> loads the demo church on that template (or
* ?profile=<id>, a demo profile);
* POST /test/design { variants?, style?, home? } changes the design and publishes again.
*/
import { execSync } from 'node:child_process';
@@ -15,7 +16,7 @@ import express from 'express';
import pg from 'pg';
import sharp from 'sharp';
import { PrismaPg } from '@prisma/adapter-pg';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { agent, websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../backend/src/generated/prisma/client.js';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
@@ -67,6 +68,14 @@ await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'he
const app = express();
app.post('/test/demo', async (req, res) => {
// ?profile=<id>: one of the demo profiles (the crosscode-site screenshots of another church on
// a template); it keeps the church profile the template demo saved (Acacia Hill).
const profile = String(req.query.profile ?? '');
if (profile) {
if (!(agent.WEBSITE_DEMO_PROFILES as readonly string[]).includes(profile)) return res.status(400).json({ error: 'profile' });
await loadDemo(ctx, profile as agent.WebsiteDemoProfile, { uploadDir: uploads });
return res.json({ ok: true, profile });
}
const t = websiteTemplateSchema.safeParse(req.query.template);
if (!t.success) return res.status(400).json({ error: 'template' });
await loadDemo(ctx, t.data, { uploadDir: uploads });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-frontend",
"version": "1.6.0",
"version": "1.7.1",
"private": true,
"description": "Church Website: the church's public site in its template, and the admin",
"scripts": {
+15 -3
View File
@@ -3,10 +3,15 @@
/** A list of things the church keeps (ministries, its team): add, edit, remove. Drafts until Publish. */
import { useState } from "react";
import { api } from "./api";
import type { Focus } from "@/site/types";
import { RowFraming } from "./framing";
import { ImagePicker } from "./media";
import { Btn, Field, inputClass, Loading, Notice, Panel, useAction, useAdmin } from "./ui";
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string };
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string;
/** An image field: its photo can be moved and zoomed in this frame (saved as the row's `framing`). */
frame?: "ministry" | "leader";
};
type Row = Record<string, unknown> & { id: string };
@@ -14,7 +19,14 @@ function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: L
const [v, setV] = useState<Record<string, unknown>>(initial);
return (
<div className="space-y-3">
{fields.map((f) => f.kind === "image"
{fields.map((f) => f.kind === "image" && f.frame
? (
<RowFraming key={f.key} type={f.frame} value={v.framing as Focus | null} onChange={(framing) => setV({ ...v, framing })}>
{/* Another photo starts centred. */}
<ImagePicker label={f.label} slot={{ key: f.key }} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id, framing: null })} />
</RowFraming>
)
: f.kind === "image"
? <ImagePicker key={f.key} label={f.label} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id })} />
: (
<Field key={f.key} label={f.label} hint={f.hint} error={errors[f.key]}>
@@ -36,7 +48,7 @@ export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }:
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
const row = id ? data.find((r) => r.id === id) : null;
// When the form was loaded: someone else's save in between isn't overwritten (§4).
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(fields.some((f) => f.frame) ? { framing: v.framing ?? null } : {}), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
setEditing(null);
await reload();
+23 -5
View File
@@ -4,6 +4,8 @@
* The forms for each homepage section and block, from one description per type (the backend's
* zod schemas in src/site/sections.ts check what's saved; field errors come back by path).
*/
import type { Focus } from "@/site/types";
import { FramingContext, type Framing } from "./framing";
import { ImagePicker } from "./media";
import { Btn, Field, inputClass } from "./ui";
@@ -52,9 +54,13 @@ export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
type Data = Record<string, unknown>;
export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string }) {
/**
* 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"] }) {
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
return (
const form = (
<div className="space-y-4">
{fields.map((f) => {
const err = errors[`${prefix}${f.key}`];
@@ -67,14 +73,14 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie
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 "image":
return <div key={f.key}><ImagePicker 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>;
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[]) : [];
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}`} 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}`} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
{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])} />}
</div>
);
}
@@ -111,4 +117,16 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie
})}
</div>
);
if (!frame) return form;
const framing = (value.framing ?? {}) as Record<string, Focus>;
const ctx: Framing = {
get: (id) => framing[id],
set: (id, f) => {
const next = { ...framing };
if (f) next[id] = f; else delete next[id];
onChange({ ...value, framing: next });
},
frame,
};
return <FramingContext.Provider value={ctx}>{form}</FramingContext.Provider>;
}
+174
View File
@@ -0,0 +1,174 @@
"use client";
/**
* Framing a photo: see it in the shape of the frame the site puts it in (the template and layout
* chosen), drag it to move it and zoom in to crop. Saved with the section (`data.framing`, by media
* id), so it's a draft like any other change: previewed, then published.
*/
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { focusStyle } from "@/site/parts";
import type { Focus } from "@/site/types";
import { Btn, cx, useAdmin } from "./ui";
export type Frame = { ratio: number; round?: boolean; label: string };
export const CENTRE: Focus = { x: 50, y: 50, zoom: 1 };
type Design = { template?: string; variants?: Record<string, string> } | null | undefined;
/**
* The frame a section's photo is shown in, as wide as the site's desktop layout draws it
* (site/sections). `key` is the field (images, imageId, photoId); `index` the photo in a list.
*/
export function frameFor(design: Design, type: string, key: string, index = 0): Frame {
const t = design?.template ?? "heritage";
const v = design?.variants?.[type];
if (type === "hero") {
if (v === "text") return { ratio: 16 / 9, label: "Not shown: the top of the page is set to Text only" };
if (v === "split") return t === "bold" ? { ratio: 4 / 5, label: "Half the screen, beside the headline" } : { ratio: 4 / 3, label: "Beside the headline" };
if (v === "collage") {
if (t === "bold") return { ratio: 3 / 5, label: `Column ${index + 1} of 3, behind the headline` };
if (t === "community") return { ratio: 1, round: index === 2, label: `Photo ${index + 1} of the overlapping three` };
return { ratio: t === "heritage" ? 3 / 4 : 1, label: `Photo ${index + 1} of 3` };
}
if (t === "bold") return { ratio: 16 / 9, label: "The whole screen, behind the headline (taller on phones)" };
if (t === "heritage") return { ratio: 16 / 7, label: "Wide, above the headline" };
if (t === "community") return { ratio: 21 / 9, label: "Wide, behind the headline card (16:9 on phones)" };
return { ratio: 16 / 9, label: "Below the headline" };
}
if (type === "welcome") {
if (key === "photoId") return { ratio: 4 / 5, label: "The pastor's photo" };
return t === "bold" ? { ratio: 1, label: "Beside the welcome" } : { ratio: 4 / 3, label: "Beside the welcome" };
}
// A ministry's, leader's or event's photo: the home page section's frame for the layout chosen.
if (type === "ministry") {
const vm = design?.variants?.ministries;
if (vm === "bands") return t === "bold" ? { ratio: 4 / 3, label: "Beside its name on the home page (4:3 on the Ministries page)" } : { ratio: 16 / 10, label: "Beside its name on the home page (4:3 on the Ministries page)" };
return { ratio: 4 / 3, label: "On its card on the home page and beside it on the Ministries page" };
}
if (type === "leader") {
const round = t === "heritage" || t === "community";
if (t === "bold") return { ratio: 3 / 4, label: "Their photo on the home page (square on the Leadership page)" };
return { ratio: 1, round, label: round ? "Their photo, in a circle" : "Their photo" };
}
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)" };
return { ratio: 4 / 3, label: "Beside the text" };
}
/** What DataForm shares with each ImagePicker in a section: its framing, and the frame per field. */
export type Framing = {
get: (id: string) => Focus | undefined;
set: (id: string, f: Focus | null) => void;
frame: (key: string, index?: number) => Frame;
};
export const FramingContext = createContext<Framing | null>(null);
export const useFraming = () => useContext(FramingContext);
/**
* Framing for a row with one photo (a ministry, a leader, an event): saved as the row's `framing`,
* in the frame of `type` (frameFor) for the site's current template and layouts.
*/
export function RowFraming({ type, value, onChange, children }: { type: "ministry" | "leader" | "event"; value: Focus | null | undefined; onChange: (f: Focus | null) => void; children: React.ReactNode }) {
const design = useAdmin<{ design: Design }>("/design");
const ctx: Framing = { get: () => value ?? undefined, set: (_, f) => onChange(f), frame: (key, i) => frameFor(design.data?.design, type, key, i) };
return <FramingContext.Provider value={ctx}>{children}</FramingContext.Provider>;
}
/** The photo drawn in its frame, as the site draws it (object-cover, point kept in view, zoom). */
export function Framed({ url, frame, focus, className, imgRef }: { url: string; frame: Frame; focus: Focus | undefined; className?: string; imgRef?: React.Ref<HTMLImageElement> }) {
return (
<div className={cx("relative overflow-hidden bg-gray-100", frame.round ? "rounded-full" : "rounded", className)} style={{ aspectRatio: String(frame.ratio) }}>
<img ref={imgRef} src={url} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full select-none object-cover" style={focusStyle(focus)} />
</div>
);
}
const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
/** Drag to move, slider (or wheel) to zoom; Done keeps it, Cancel leaves it as it was. */
export function FramingDialog({ url, alt, frame, initial, onDone, onClose }: {
url: string; alt: string; frame: Frame; initial: Focus | undefined; onDone: (f: Focus | null) => void; onClose: () => void;
}) {
const [f, setF] = useState<Focus>(initial ?? CENTRE);
const box = useRef<HTMLDivElement>(null);
const img = useRef<HTMLImageElement>(null);
const drag = useRef<{ x: number; y: number; start: Focus } | null>(null);
useEffect(() => {
const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
window.addEventListener("keydown", esc);
return () => window.removeEventListener("keydown", esc);
}, [onClose]);
/** How far the photo can move (px) across 0–100%: its drawn size, zoomed, less the frame's. */
const room = () => {
const b = box.current?.getBoundingClientRect();
const i = img.current;
if (!b || !i?.naturalWidth) return { x: 0, y: 0 };
const cover = Math.max(b.width / i.naturalWidth, b.height / i.naturalHeight);
return { x: i.naturalWidth * cover * f.zoom - b.width, y: i.naturalHeight * cover * f.zoom - b.height };
};
const down = (e: React.PointerEvent) => {
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
drag.current = { x: e.clientX, y: e.clientY, start: f };
};
const move = (e: React.PointerEvent) => {
const d = drag.current;
if (!d) return;
const r = room();
// Dragging the photo right shows more of its left: the point in view moves left.
setF({
...d.start,
x: r.x > 1 ? clamp(d.start.x - ((e.clientX - d.x) / r.x) * 100, 0, 100) : d.start.x,
y: r.y > 1 ? clamp(d.start.y - ((e.clientY - d.y) / r.y) * 100, 0, 100) : d.start.y,
});
};
const key = (e: React.KeyboardEvent) => {
const step = e.shiftKey ? 10 : 2;
const by: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };
const m = by[e.key];
if (!m) return;
e.preventDefault();
setF({ ...f, x: clamp(f.x + m[0], 0, 100), y: clamp(f.y + m[1], 0, 100) });
};
const round = (x: Focus): Focus => ({ x: Math.round(x.x * 10) / 10, y: Math.round(x.y * 10) / 10, zoom: Math.round(x.zoom * 100) / 100 });
const centred = f.x === 50 && f.y === 50 && f.zoom === 1;
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4" role="dialog" aria-modal="true" aria-label="Move and zoom the photo">
<div className="max-h-[95vh] w-full max-w-2xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
<h2 className="text-lg font-semibold">Move and zoom</h2>
<p className="mt-1 text-sm text-gray-600">{frame.label}. Drag the photo to choose what shows; zoom in to crop closer.</p>
<div
ref={box}
tabIndex={0}
aria-label={`${alt || "The photo"} in its frame. Arrow keys move it.`}
onPointerDown={down}
onPointerMove={move}
onPointerUp={() => { drag.current = null; }}
onPointerCancel={() => { drag.current = null; }}
onKeyDown={key}
onWheel={(e) => setF((x) => ({ ...x, zoom: clamp(x.zoom - e.deltaY * 0.002, 1, 3) }))}
className="mx-auto mt-4 cursor-grab touch-none outline-none ring-brand focus-visible:ring-2 active:cursor-grabbing"
style={{ maxWidth: frame.ratio < 1 ? `${Math.round(360 * frame.ratio)}px` : undefined }}
>
<Framed url={url} frame={frame} focus={f} imgRef={img} />
</div>
<label className="mt-5 flex items-center gap-3 text-sm text-gray-700">
Zoom
<input type="range" min={1} max={3} step={0.01} value={f.zoom} onChange={(e) => setF({ ...f, zoom: Number(e.target.value) })} className="flex-1" />
<span className="w-12 text-right tabular-nums">{Math.round(f.zoom * 100)}%</span>
</label>
<p className="mt-2 text-xs text-gray-500">On phones the frame can be a different shape; the part you chose stays in view.</p>
<div className="mt-5 flex flex-wrap items-center gap-3">
<Btn kind="primary" onClick={() => onDone(centred ? null : round(f))}>Done</Btn>
<Btn onClick={onClose}>Cancel</Btn>
<Btn kind="link" onClick={() => setF(CENTRE)} disabled={centred}>Reset</Btn>
</div>
</div>
</div>
);
}
+29 -7
View File
@@ -2,10 +2,12 @@
/** The media library: pick an image, or upload one (with its alt text) and pick it. */
import { useRef, useState } from "react";
import { Move } from "lucide-react";
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 };
export type MediaItem = { id: string; url: 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`;
@@ -49,21 +51,41 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
);
}
/** One image field: shows the chosen image, with Choose and Remove. */
export function ImagePicker({ value, onChange, label }: { value: string | null; onChange: (id: string | null) => void; label: string }) {
/**
* 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.
*/
export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) {
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 focus = value ? framing?.get(value) : undefined;
return (
<div>
<span className="block text-sm font-medium text-gray-800">{label}</span>
<div className="mt-1 flex items-center gap-3">
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
</div>
<div className="mt-1 flex flex-wrap items-center gap-3">
{chosen && frame ? (
<button type="button" onClick={() => setFramingOpen(true)} title="Move and zoom" className="shrink-0 rounded border border-gray-200"
style={{ width: `${Math.round(Math.min(160, Math.max(48, 72 * frame.ratio)))}px` }}>
<Framed url={chosen.url} frame={frame} focus={focus} />
</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>}
</div>
)}
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
{chosen && frame && <Btn onClick={() => setFramingOpen(true)}><Move className="h-4 w-4" aria-hidden />Move and zoom</Btn>}
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
</div>
{chosen && frame && focus && <p className="mt-1 text-xs text-gray-500">Moved{focus.zoom > 1 ? ` and zoomed to ${Math.round(focus.zoom * 100)}%` : ""}. Save to see it in the preview.</p>}
{framingOpen && chosen && frame && framing && (
<FramingDialog url={chosen.url} alt={chosen.alt} frame={frame} initial={focus}
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="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
@@ -8,15 +8,17 @@
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { RowFraming } from "@/admin/framing";
import { ImagePicker } from "@/admin/media";
import type { Focus } from "@/site/types";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { CalendarDays } from "lucide-react";
type Ev = {
id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null;
imageId: string | null; image: string | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
imageId: string | null; image: string | null; framing: Focus | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
};
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string; ministryId: string | null };
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; framing: Focus | null; link: string; ministryId: string | null };
type Me = { user: { role: string; ministryId: string | null } };
/** "2026-12-05" + "18:30" in the browser's time zone (the church's, for its admins) → ISO with offset. */
@@ -53,11 +55,14 @@ function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { i
</select>
</Field>
)}
<ImagePicker label="Photo" value={v.imageId} onChange={(id) => set("imageId", id)} />
<RowFraming type="event" value={v.framing} onChange={(f) => set("framing", f)}>
{/* Another photo starts centred. */}
<ImagePicker label="Photo" slot={{ key: "imageId" }} value={v.imageId} onChange={(id) => setV({ ...v, imageId: id, framing: null })} />
</RowFraming>
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave({
title: v.title, startsAt: iso(v.date, v.allDay ? "00:00" : v.time), endsAt: v.endDate ? iso(v.endDate, v.allDay ? "23:59" : v.endTime) : null,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, framing: v.framing, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
}))}>Save</Btn>
<Btn onClick={onCancel}>Cancel</Btn>
</div>
@@ -66,7 +71,7 @@ function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { i
);
}
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "", ministryId: null };
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, framing: null, link: "", ministryId: null };
export default function Events() {
const me = useAdmin<Me>("/me");
@@ -82,7 +87,7 @@ export default function Events() {
const toForm = (e: Ev): Form => {
const s = local(e.startsAt);
const f = local(e.endsAt);
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "", ministryId: e.ministryId };
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, framing: e.framing ?? null, link: e.link ?? "", ministryId: e.ministryId };
};
const state = (e: Ev, change: object, done: string) => run(async () => { await api(`/events/${e.id}/state`, { body: change }); await reload(); }, done);
const form = (e: Ev | null) => (
@@ -15,7 +15,7 @@ export default function Leaders() {
{ key: "name", label: "Name", kind: "text", max: 120 },
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
{ key: "bio", label: "About them", kind: "textarea", max: 4000 },
{ key: "photoId", label: "Photo", kind: "image" },
{ key: "photoId", label: "Photo", kind: "image", frame: "leader" },
]} />
</>
);
@@ -1,10 +1,10 @@
"use client";
import { useState } from "react";
import { api } from "@/admin/api";
import { api, canEdit } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { Image as ImageIcon } from "lucide-react";
import { Image as ImageIcon, Trash2 } from "lucide-react";
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
export default function Media() {
@@ -15,6 +15,7 @@ export default function Media() {
const { busy, message, run } = useAction();
if (!data) return <Loading error={error} />;
const manager = ["owner", "admin"].includes(me.data?.user.role ?? "");
const editor = canEdit(me.data?.user.role ?? "");
const s = data.storage;
return (
<>
@@ -35,6 +36,15 @@ export default function Media() {
)}
{!m.alt && <p className="text-xs font-medium text-amber-800">Add what it shows, for people who can&apos;t see it.</p>}
<p className="text-xs text-gray-500">{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}</p>
{m.usedIn?.length ? (
<p className="text-xs text-gray-600">Used on: {m.usedIn.join(", ")}</p>
) : editor && (
<Btn kind="danger" busy={busy} onClick={() => {
if (window.confirm(`Delete this photo${m.alt ? ` (“${m.alt}”)` : ""}? It isn't used anywhere. This can't be undone.`)) {
void run(async () => { await api(`/media/${m.id}`, { method: "DELETE" }); await reload(); }, "Deleted.");
}
}}><Trash2 className="h-4 w-4" aria-hidden />Delete</Btn>
)}
</li>
))}
</ul>
@@ -15,7 +15,7 @@ export default function Ministries() {
{ key: "name", label: "Name", kind: "text", max: 120 },
{ key: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
{ key: "body", label: "More about it", kind: "textarea", max: 8000 },
{ key: "imageId", label: "Photo", kind: "image" },
{ key: "imageId", label: "Photo", kind: "image", frame: "ministry" },
]} />
</>
);
@@ -15,13 +15,14 @@ import {
} 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 { 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 PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
type Design = { home: { section: string; hidden: boolean }[] };
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> = {
@@ -48,8 +49,8 @@ const summary = (data: Record<string, unknown>) => {
return null;
};
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }: {
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>;
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame }: {
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;
}) {
const [value, setValue] = useState(initial);
@@ -73,7 +74,7 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }:
</div>
{open && (
<div className="space-y-4 border-t border-gray-100 p-4">
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} frame={frame} />
<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>
@@ -134,7 +135,7 @@ 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 }>(isHome ? "/design" : null);
const design = useAdmin<{ design: Design }>("/design");
const blocks = useAction();
const remove = useAction();
const [tab, setTab] = useState<"content" | "details">("content");
@@ -171,7 +172,7 @@ export default function EditPage() {
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 ?? {}}
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)}
hidden={hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Not shown</span>}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
})}
@@ -184,7 +185,7 @@ export default function EditPage() {
const spec = BLOCK_FIELDS[s.type];
if (!spec) return null;
return (
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data}
<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)}
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={<>
+10 -4
View File
@@ -1,20 +1,23 @@
/**
* Each template's header (WEBSITE-1.0-PLAN §3, "Headers"), with its options from the Header style
* setting. Every header collapses to a Menu button on phones (a <details>, so it works without
* JavaScript). Links to the church's other sites (Events, App) sit next to the pages (§9).
* JavaScript). Links to the church's other sites sit next to the pages (§9), as "Events site" with an
* external-link icon (1.6.1), so they aren't mistaken for this site's own Events page.
*/
import Link from "next/link";
import { ExternalLink } from "lucide-react";
import { productLinks } from "@crosscode/ui";
import { ScrollSolid } from "./ScrollSolid";
import { cx } from "./parts";
import type { Published } from "./types";
type Item = { label: string; href: string; current: boolean };
/** `external`: one of the church's other sites (1.6.1), marked so it isn't mistaken for a page here. */
type Item = { label: string; href: string; current: boolean; external?: boolean };
function items(site: Published, path: string): { nav: Item[]; visit: Item | null } {
const pages = site.snapshot.pages;
const nav: Item[] = pages.filter((p) => p.inNav).map((p) => ({ label: p.navLabel, href: p.path, current: p.path === path }));
for (const l of site.church ? productLinks(site.church.links, "website") : []) nav.push({ label: l.label, href: l.href, current: false });
for (const l of site.church ? productLinks(site.church.links, "website") : []) nav.push({ label: `${l.label} site`, href: l.href, current: false, external: true });
const v = pages.find((p) => p.kind === "visit");
return { nav, visit: v ? { label: v.navLabel, href: v.path, current: v.path === path } : null };
}
@@ -36,7 +39,10 @@ function Links({ nav, className, linkClass }: { nav: Item[]; className?: string;
<ul className={className}>
{nav.map((n) => (
<li key={n.href}>
<a href={n.href} aria-current={n.current ? "page" : undefined} className={cx("no-underline hover:underline underline-offset-8", n.current && "underline", linkClass)}>{n.label}</a>
<a href={n.href} aria-current={n.current ? "page" : undefined} title={n.external ? "Our separate site" : undefined} className={cx("no-underline hover:underline underline-offset-8", n.current && "underline", n.external && "inline-flex items-center gap-1", linkClass)}>
{n.label}
{n.external && <ExternalLink className="h-[0.85em] w-[0.85em] shrink-0 opacity-70" aria-hidden />}
</a>
</li>
))}
</ul>
+7 -3
View File
@@ -1,6 +1,6 @@
import { cookies, headers } from "next/headers";
import { cache } from "react";
import type { Image, Published, SiteContent, Template } from "./types";
import type { Focus, Image, Published, SiteContent, Template } from "./types";
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
@@ -57,8 +57,12 @@ export async function loadPublished(): Promise<Published | null> {
return c.mode === "published" ? c : null;
}
/** An image from a section's data (a media id), or null. */
export const media = (site: Published, id: unknown): Image | null => (typeof id === "string" ? site.snapshot.media[id] ?? null : null);
/** An image from a section's data (a media id), or null; placed as the section frames it (`data.framing`). */
export const media = (site: Published, id: unknown, data?: Record<string, unknown>): Image | null => {
const img = typeof id === "string" ? site.snapshot.media[id] ?? null : null;
const focus = img && (data?.framing as Record<string, Focus> | undefined)?.[id as string];
return img && focus ? { ...img, focus } : img;
};
/** Per-template class names: `t(template, { heritage: "…", bold: "…" }, "fallback")`. */
export const t = (template: Template, by: Partial<Record<Template, string>>, otherwise = "") => by[template] ?? otherwise;
+18 -3
View File
@@ -1,8 +1,18 @@
/** Small building blocks every template uses. */
import type { Image } from "./types";
import type { Focus, Image } from "./types";
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
/**
* How a photo sits in its frame (object-cover): the chosen point kept in view, zoomed around that
* point. The frame clips it (overflow hidden). The admin's framing dialog draws it the same way.
*/
export function focusStyle(f: Focus | undefined): React.CSSProperties | undefined {
if (!f) return undefined;
const at = `${f.x}% ${f.y}%`;
return f.zoom > 1 ? { objectPosition: at, transform: `scale(${f.zoom})`, transformOrigin: at } : { objectPosition: at };
}
/**
* An uploaded image at the size the screen needs (§3: responsive sizes in WebP and JPEG): the
* browser picks from the `srcset`s by `sizes`. `alt` overrides the image's own (e.g. "" when it's
@@ -12,7 +22,7 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a
const img = (
<img src={image.url} srcSet={image.srcset?.jpg} sizes={image.srcset ? sizes : undefined} alt={alt ?? image.alt}
width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} />
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} style={focusStyle(image.focus)} />
);
return image.srcset ? <picture><source type="image/webp" srcSet={image.srcset.webp} sizes={sizes} />{img}</picture> : img;
}
@@ -21,7 +31,12 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a
export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) {
return (
<div className={cx("cc-frame", ratio, className)}>
{image ? (
{image && (image.focus?.zoom ?? 1) > 1 ? (
// Zoomed: clipped inside the frame's mat (Heritage pads its frames), not over it.
<div className="h-full w-full overflow-hidden" style={{ borderRadius: "var(--cc-radius-sm, 0)" }}>
<Picture image={image} sizes={sizes} priority={priority} className="cc-img" />
</div>
) : image ? (
<Picture image={image} sizes={sizes} priority={priority} 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" />
@@ -49,9 +49,9 @@ function Fullbleed({ d, site, children }: { d: HeroData; site: SectionProps["sit
export function Hero({ section, site, template }: SectionProps) {
const d = section.data as unknown as HeroData;
const variant = section.variant ?? "photo";
const imgs = (d.images ?? []).map((id) => media(site, id));
const imgs = (d.images ?? []).map((id) => media(site, id, section.data));
const first = imgs[0] ?? null;
const video = media(site, d.videoId);
const video = media(site, d.videoId, section.data);
const services = (site.church?.serviceTimes ?? []).filter((s) => s.day === "sunday").map((s) => s.time);
if (variant === "text") {
@@ -79,7 +79,7 @@ export function Hero({ section, site, template }: SectionProps) {
if (template === "bold") {
return (
<section className="cc-section-hero grid bg-gray-950 text-white md:min-h-[80vh] md:grid-cols-2">
<div className="relative min-h-[50vh] md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
<div className="relative min-h-[50vh] overflow-hidden md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
<div className="flex flex-col justify-center px-6 pb-16 pt-32 sm:px-12"><Words d={d} light /></div>
</section>
);
@@ -100,7 +100,7 @@ export function Hero({ section, site, template }: SectionProps) {
return (
<Fullbleed d={d} site={site}>
<div className="grid h-full grid-cols-3 gap-1">
{three.map((im, i) => <div key={i} className="relative">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
{three.map((im, i) => <div key={i} className="relative overflow-hidden">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
</div>
</Fullbleed>
);
@@ -106,7 +106,7 @@ function Welcome(p: SectionProps) {
</div>
);
if (p.section.variant === "pastor" && d.pastor) {
const photo = media(p.site, d.pastor.photoId);
const photo = media(p.site, d.pastor.photoId, p.section.data);
return (
<Section>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]">
@@ -124,7 +124,7 @@ function Welcome(p: SectionProps) {
return (
<Section>
<div className={cx("grid items-center gap-10 md:grid-cols-2", p.template === "bold" ? "px-0 md:gap-0" : "cc-wrap")}>
<Img image={media(p.site, d.imageId)} ratio={p.template === "bold" ? "aspect-square md:aspect-auto md:h-full md:min-h-[28rem]" : "aspect-[4/3]"} className={cx(p.template === "community" && "rounded-[2rem]", p.template === "bold" && "rounded-none")} />
<Img image={media(p.site, d.imageId, p.section.data)} ratio={p.template === "bold" ? "aspect-square md:aspect-auto md:h-full md:min-h-[28rem]" : "aspect-[4/3]"} className={cx(p.template === "community" && "rounded-[2rem]", p.template === "bold" && "rounded-none")} />
<div className={cx(p.template === "bold" && "px-6 py-10 sm:px-12")}>{words}</div>
</div>
</Section>
@@ -390,7 +390,7 @@ function LatestMessage(p: SectionProps) {
function Invitation(p: SectionProps) {
const d = p.section.data as { heading: string; text: string | null; button: ButtonData; imageId: string | null };
if (p.section.variant === "image") {
const img = media(p.site, d.imageId);
const img = media(p.site, d.imageId, p.section.data);
return (
<section className="cc-section cc-own-bg cc-dark relative isolate overflow-hidden bg-gray-900 text-white">
{img && <Picture image={img} alt="" className="cc-img absolute inset-0 -z-10" />}
@@ -436,7 +436,7 @@ function ImageTextBlock(p: SectionProps) {
return (
<Section>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-2">
<Img image={media(p.site, d.imageId)} className={cx(p.template === "community" && "rounded-[2rem]")} />
<Img image={media(p.site, d.imageId, p.section.data)} className={cx(p.template === "community" && "rounded-[2rem]")} />
<div>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /><div className="mt-6"><Button button={d.button} /></div></div>
</div>
</Section>
+4 -1
View File
@@ -7,7 +7,10 @@ import type { Church } from "@crosscode/contracts";
export type Template = "heritage" | "bold" | "community" | "clean";
/** An uploaded image; `srcset` lists its responsive sizes (WebP and JPEG) when it has them. */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
/** Where a photo sits in its frame: the point kept in view (0 to 100 from left and top) and its zoom (1 fills the frame). */
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> };
+5
View File
@@ -237,6 +237,11 @@ from"). When on:
secret). It fetches `?updatedSince=<lastGoodAt minus 5 minutes>`, 15 s timeout, parses with
`parseEventFeed` (rejected events are logged, never block the rest), and upserts into
`ImportedEvent`. One failing link never holds up another (separate jobs).
**Changed in Events 3.7.2 / Website 1.6.1:** the 15-minute poll and "Sync now" fetch the whole
list (no `updatedSince`) and drop copies that aren't in it, so events a sibling lost without
listing them in `deleted` (a reseed, a restore) can't stay forever. Only the fetch after an
`event.changed` asks for what changed. Demo reseeds (`set-demo.js`, the Website's `loadDemo`)
list the old events in `deleted` and send `event.changed`, so siblings are right at once.
- **The last good copy stays.** A failed sync only sets `lastSyncError`; admins see "Last synced
2 hours ago" on Linked products and on the dashboard's event list.
- **Read-only**, keyed by `origin.product` + `id` (`eventKey`), and **never re-published**: the
+71 -24
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-27. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-28. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -10,13 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.5.0** | `website@1.5.0` | 2026-11-27 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.2** | `events@3.7.2` | 2026-11-27 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.19.0** | `contracts@1.19.0` | 2026-11-27 |
| Cross Code Hub | `events-hub` | **2.25.0** | `v2.25.0` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.7.0** | `v1.7.0` | 2026-11-26 |
| Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
@@ -30,7 +30,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 1.5.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.5.0 on 2026-11-27; installed for the demo church cross-demo2 (1.2.0) only, Hope Family Church next) |
| Website | `apps/website` | 1.7.1 (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; installed for the demo church cross-demo2 (1.7.0) only, Hope Family Church next) |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -38,13 +38,59 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Church Website 1.7.1 (2026-11-28):** Move and zoom for ministries', leaders' and events'
photos too (1.7.0 had it in page sections only), saved with the row (`framing`). One migration
(a nullable column on three tables). Checked: backend tests (136) and typecheck, frontend
typecheck and lint, and the admin e2e suite in Chromium (12). Lighthouse not run. **Not deployed
yet.**
- **Hub 2.25.1 (2026-11-27):** Jobs → Product filter lists every product. It offered only Cross
Events and Accounts, so the Church Website's jobs couldn't be picked out; the list now comes from
the frontend's products list (Events, Accounts, the Church Website, the App). Frontend only. No
migration. Checked: the backend tests (283), frontend typecheck and lint. **Deployed** 2026-11-28.
- **Church Website 1.7.0 (2026-11-27):** a section's photo shows in the shape of its frame and can
be moved and zoomed (saved with the section, a draft until published); the media library says
where each photo is used and deletes one used nowhere. **Deployed** 2026-11-27.
- **Cross Events 3.7.2 + Church Website 1.6.1 (2026-11-27):** events from the other product no
longer show twice after a reseed: the 15-minute feed poll and "Sync now" fetch the whole list and
drop copies that are gone, and both demo loaders list the old events as removed and tell the
other product at once (Events' `set-demo.js` also fetches the Website's events back in). The
Website's header says "Events site" with an external-link icon instead of a second "Events".
**Deployed** 2026-11-27.
- **crosscode.co.za 1.9.1 (2026-11-27):** the web address examples (both product pages and the
Church Website brochure) say yourchurch instead of a real church's name (hopefamily). **Deployed**
2026-11-28.
- **crosscode.co.za 1.9.0 (2026-11-27):** a Church Website brochure (`church-website-brochure.pdf`,
five A4 pages, from the site's data and the demo screenshots), linked from the Church Website
page; `npm run brochure` renders both brochures. The Website's founding offer no longer mentions
tiers. Brochure links carry a hash of the file (`?v=`), like the screenshots. **Deployed** 2026-11-27.
- **crosscode.co.za 1.8.1 (2026-11-27):** readable on dark: the template pages' "Compare the
templates" button (it was dark text on the navy hero) and the "Good for" text there, the
WhatsApp buttons' green (#168243, white text 4.9:1; was 3.1:1) and the Founding heading on the
Cross Events price table. axe (WCAG 2.2 AA) on all 16 pages, desktop and phone: no problems
(was 20). **Deployed** 2026-11-27.
- **crosscode.co.za 1.8.0 (2026-11-27):** each Church Website template's page shows the whole
demo website (a gallery of Plan your visit, About us, Ministries, Leadership, Events, an event,
Messages and Contact) and "the same template, a different church" (the template's second demo
profile). Screenshot URLs carry a hash of the file (`?v=`): `/assets/` is cached for 30 days, so
after deploying 1.7.1 the template grid still showed the old illustrated screenshots. The
Website's e2e server takes `/test/demo?profile=` for these screenshots (test helper only, no
Website release). **Deployed** 2026-11-27.
- **Church Website 1.6.0 + crosscode.co.za 1.7.1 (2026-11-27):** the demo church has real photos:
104 Unsplash stock photos (models; free under the Unsplash License, credited in
`apps/website/backend/demo-photos/CREDITS.md`, 12 MB) instead of the generated "hills and sun"
illustration: a set per demo profile, a portrait for every leader, a picture per event and a
photo per message (before: the stand-in video's thumbnail). Faster on phones: the collage hero,
the team's portraits and the ministry cards say their real width (`sizes`). No migration.
Checked: backend tests (131), the Website e2e (130; the variant screenshots taken again;
Lighthouse mobile 90–98 performance, 100 accessibility and SEO), typecheck, lint and both
builds. crosscode.co.za 1.7.1: the 24 Church Website screenshots taken again from the new demo.
**Deployed** 2026-11-27.
- **Church Website 1.5.0 + crosscode script (2026-11-27):** the nightly backup also backs up the
photos and files: a snapshot of `backend/uploads` in `backups/uploads-…/`, unchanged files hard
links to the last snapshot (after the first full copy, a night costs only the new files), with
its own switch on Admin → Backups. Script: an uninstall keeps the snapshots with `rsync -aH`. No
migration. Checked: backend tests (130), the admin e2e's axe check, both builds, typecheck and
lint, the website and uninstall bats tests (11). **Not deployed yet**: cross-demo2's Website
still reports 1.2.0 (`/api/health`, checked 2026-11-27). The script change is live (servers pull
lint, the website and uninstall bats tests (11). **Deployed** 2026-11-27. The script change is live (servers pull
`main`).
- **Church Website 1.4.0 (2026-11-27):** nightly database backups (02:20, `backend/backups/`, the
same files crosscode makes before updates) with Admin → Backups, and background jobs on pg-boss
@@ -52,7 +98,7 @@ need their own tags until something outside this repo depends on them.
to switch each on or off, reschedule or run it. The heartbeat reports the newest backup (before:
always none, so the Hub warned "No backup reported") and the real job state. No migration.
Uploads weren't in the backups (1.5.0 adds them). Checked: backend tests (125), the admin e2e (10, axe
on both new pages), both builds, typecheck and lint. **Not deployed yet** (cross-demo2: 1.2.0).
on both new pages), both builds, typecheck and lint. **Deployed** 2026-11-27.
- **Hub 2.25.0 + Church Website 1.3.0 + agent 1.6.0 + contracts 1.19.0 + crosscode script
(2026-11-27):** demo clients and demo data for the Website. Hub: a customer can be a demo client:
every install a demo site (Accounts included, and any it gets later) and never billed (billing
@@ -63,8 +109,8 @@ need their own tags until something outside this repo depends on them.
`crosscode demo <church> website --profile <p>`. No migrations outside the Hub. Checked:
contracts (271), agent (58), the Website's backend tests (115) and build, the script's bats
tests (107), the Hub's backend tests (283), frontend typecheck and lint. **Hub 2.25.0 and agent
1.6.0 deployed 2026-11-27.** Website 1.3.0 not yet (cross-demo2 reports 1.2.0), so the Website's
demo data can't be loaded there until it's on 1.3.0 or later.
1.6.0 deployed 2026-11-27.** The Website followed (cross-demo2 on 1.7.0 since 2026-11-27), so its
demo data can be loaded there.
- **Hub 2.24.1 (2026-11-27):** Servers → Updates offers every product. Its tabs were a fixed list of
Cross Events and Accounts from before the Church Website, so Website installs couldn't be updated
in a batch there; now Events, Accounts, the Church Website, and the App once it has an install.
@@ -88,7 +134,7 @@ need their own tags until something outside this repo depends on them.
first publish across the top, and a live preview beside the page editor (drafts for a framed
request with an admin session, no preview cookie). No migrations, no backend changes. Checked:
typechecks and lint, the Website's e2e (10, with axe on the admin and the editor) and Accounts' e2e
(11). **Not deployed yet.**
(11). **Deployed** 2026-11-27.
- **Accounts 1.7.1 + Church Website 1.0.2 + Cross Events 3.7.1 (2026-11-26):** found installing
the Website for cross-demo2. All three: a connect involving an install that isn't in the cached
copy of the Hub's list yet asks the Hub for a fresh one (one heartbeat, at most once a minute)
@@ -148,15 +194,15 @@ need their own tags until something outside this repo depends on them.
church footer from its profile in Accounts (`GET /api/v2/church`, kept 10 minutes), with links to
its other sites in the header; `church.changed` from Accounts is now accepted (it answered 404
before). The dashboard and setup screens are unchanged. `@crosscode/ui` 0.3.0. No migrations.
Requires Accounts 1.7.0 (the Hub updates it first). **On cross-demo2 only** (by 2026-11-26, now
3.7.1); not rolled out to the churches yet.
Requires Accounts 1.7.0 (the Hub updates it first). **Deployed:** on cross-demo2 first (2026-11-26), then
the churches (all on 3.7.2 since 2026-11-27).
- **Contracts 1.17.0 + Accounts 1.7.0 (2026-11-24):** the first piece of the Church Website. Contracts:
the 8 font pairings, corner styles and template ids (`./style`), an optional `branding.style` on the
church profile, `church.update` (the Website changes shared profile facts), an optional `website`
part of the church export and an optional `limits.storageBytes` on the licence. Accounts: Brand
style under Church profile, the church's fonts, corners and shared footer on its pages, and
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **On cross-demo2
only** (by 2026-11-26, now 1.7.1); not rolled out to the churches yet.
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **Deployed:** on
cross-demo2 first (2026-11-26), then the churches (all on Accounts 1.8.0 since 2026-11-27).
- **Hub 2.20.0 (2026-11-23):** the port list says what each port is for (church, product, web or API,
linked to the install); a church server's hand-written frpc tunnels are listed as taken on each frp
config read. frps's allow_ports is checked against the port list (the Hub's range plus listed ports
@@ -204,7 +250,7 @@ need their own tags until something outside this repo depends on them.
with Cross Events, FAQ, `SoftwareApplication` JSON-LD with its offer) and a page per template; the
products and home pages, the contact form's topics, the Cross Events page and the brochure updated.
Screenshots from the Website's e2e demo (`npm run screenshots:website`). The Hub already had these
prices (2.21.0). **Not deployed yet** (`deploy/deploy.sh` on the server).
prices (2.21.0). **Deployed** 2026-11-27.
- **crosscode.co.za 1.6.1 (2026-11-23):** the web address choices on the Cross Events page are three
cards (name, price, "best if", an example address, short points); the option names were white on
a light background and couldn't be seen. Prices unchanged. Deployed 2026-11-23.
@@ -333,10 +379,11 @@ you deploy one.
| What | Running | Since | Notes |
|------|---------|-------|-------|
| Hub | 2.24.1 | 2026-11-27 | Servers → Updates offers every product (the Church Website too). Before it, 2.24.0 (2026-11-27): "Update everything to latest" on a customer's Sites card: every product that's behind, in one batch (Accounts first); before that, 2.23.1 (2026-11-26): a church's Accounts version comes from its heartbeat in New install, and heartbeats keep the install record's version current; 2.23.0 (2026-11-26): release requirements carry forward (`requires accounts …` written once in WHATS-NEW.md) |
| Agent on church-server1 | 1.5.0 | 2026-11-23 | Uninstalls one product of a church at a time |
| Agent on the central server | 1.5.0 | 2026-11-23 | Reads and changes frps's config from the Hub (no longer read-only; decision 35 superseded) |
| Cross Events (churches) | 3.6.1 | 2026-11-20 | Every install adopted onto the monorepo and signing in through Accounts |
| Accounts (churches) | 1.6.0 | 2026-11-20 | |
| cross-demo2 (demo church) | Accounts 1.7.1, Cross Events 3.7.1, Church Website 1.2.0 | 2026-11-27 | The first Church Website install (`demo2.crosscode.co.za`, added next to the church's Accounts) |
| crosscode.co.za | 1.6.1 | 2026-11-23 | Clearer web address choices on the Cross Events page |
| 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.0 | 2026-11-27 | Photos move and zoom in their frame |
| cross-demo2 (demo church) | Accounts 1.8.0, Cross Events 3.7.2, Church Website 1.7.0 | 2026-11-27 | The first Church Website install (`demo2.crosscode.co.za`) |
| crosscode.co.za | 1.9.1 | 2026-11-28 | Web address examples say yourchurch |
+4 -4
View File
@@ -133,7 +133,7 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "3.7.1",
"version": "3.7.2",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
@@ -183,7 +183,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.7.1",
"version": "3.7.2",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -360,7 +360,7 @@
},
"apps/website/backend": {
"name": "@crosscode/website-backend",
"version": "1.6.0",
"version": "1.7.1",
"hasInstallScript": true,
"dependencies": {
"@crosscode/auth-client": "*",
@@ -389,7 +389,7 @@
},
"apps/website/frontend": {
"name": "@crosscode/website-frontend",
"version": "1.6.0",
"version": "1.7.1",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",