Merge branch 'feat/blocks-layouts-video'

This commit is contained in:
2026-12-01 09:57:13 +02:00
28 changed files with 543 additions and 69 deletions
+11
View File
@@ -2,6 +2,17 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## website@1.11.0 - 2026-12-01
Layouts and backgrounds for the other pages' blocks, and a video for the top of the page
(Joshua, 2026-12-01). **Migration** (`Section.background`, nullable). No contracts change.
- **Website 1.11.0:** each block has its own layout (`BLOCK_VARIANTS`: text, image and text,
quote, call to action) and background in the church's colours; MP4 uploads (up to 20 MB, where
it was filmed taken out) for the hero's Video layout, with a video field in the admin.
- Checked: the Website backend tests (152, three new), the frontend's typecheck and lint, and the
admin, variants and templates e2e suites.
## website@1.10.0 - 2026-12-01 ## website@1.10.0 - 2026-12-01
The home page laid out from its editor, and photos that match the layout (Joshua, 2026-12-01). The home page laid out from its editor, and photos that match the layout (Joshua, 2026-12-01).
+34
View File
@@ -1,5 +1,39 @@
# Changelog — Church Website # Changelog — Church Website
## [1.11.0] — 2026-12-01
**Migration** `20261201000000_block_background` (adds the nullable `Section.background`; nothing
to fill in). No new environment settings.
### Added
- **Block layouts** (`BLOCK_VARIANTS` in `src/site/variants.ts`): text `standard` · `centred`;
image and text `image-left` · `image-right` · `image-above`; quote `centred` · `line`; call to
action `centred` · `banner`. Stored on the block (`Section.variant`, which blocks had but never
used); `PUT /pages/:id/blocks/:sid` refuses an id that isn't the type's. The snapshot draws an
unknown or missing one as the type's default (`blockVariant`), which is how every block looked
before, so nothing changes until a church picks one. The demo's image-and-text block had the id
`image-text`; it's now `image-left`.
- **A block's own background** (`Section.background`, one of `SECTION_BACKGROUNDS` or null), set
with the same endpoint and carried to the snapshot's section, where the site draws it as the
homepage's (`data-bg`). The published source lists it only when set, so earlier versions compare
equal; Discard and Restore put it back.
- **Videos in the media library:** `POST /media` takes an MP4 (sniffed by its `ftyp` box) up to
20 MB (`MAX_VIDEO_BYTES`, under the installers' nginx `client_max_body_size 25m`) and keeps it
as uploaded, with no other sizes, counted towards storage. QuickTime (`.mov`) is refused with a
message to export MP4. Its metadata boxes (`udta`, `meta`, `uuid` in the file and its tracks)
are turned into `free` boxes of the same size, zeroed (`cleanVideo`), so where it was filmed is
gone and the offsets to the frames hold. Width and height come from the first track's `tkhd`.
`GET /media` lists each item's `mime`.
- **Admin:** a block, when open, has its Layout and Background (saved straight away); the hero has
a Video field for the Video layout, which only offers videos (photo fields only offer photos);
the media library shows videos and takes them.
### Changed
- A request larger than the upload limit says so ("photos can be up to 15 MB and videos up to 20
MB") instead of "That request isn't valid."
## [1.10.0] — 2026-12-01 ## [1.10.0] — 2026-12-01
No migration, no new environment settings, no backend change. No migration, no new environment settings, no backend change.
+12
View File
@@ -3,6 +3,18 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged). WHATS-NEW.md; a section shows once its version is tagged).
## 1.11.0
- **Layouts and backgrounds for the blocks on your other pages.** Open a block in **Pages** to
choose how it looks: text standard or centred; a photo on the left, on the right or above the
text; a quote centred or with a line beside it; a call to action centred or as a banner in your
colour. Each block can also have its own background in your church's colours, like the home
page's sections.
- **A video for the top of your home page.** Choose the **Video** layout and upload a short MP4
clip (up to 20 MB; 10 to 20 seconds is plenty). It plays muted, on a loop, over your still
photo; phones and visitors who prefer less motion see the still photo. Like photos, the place a
video was filmed is taken out of it when you upload it.
## 1.10.0 ## 1.10.0
- **Lay out your home page while you edit it.** In **Pages → Home**, open a section to choose its - **Lay out your home page while you edit it.** In **Pages → Home**, open a section to choose its
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.10.0", "version": "1.11.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads", "description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true, "private": true,
"type": "module", "type": "module",
@@ -0,0 +1,2 @@
-- A block's own background, in the church's colours (Website 1.11.0).
ALTER TABLE "Section" ADD COLUMN "background" TEXT;
+5 -1
View File
@@ -81,7 +81,8 @@ model Page {
} }
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant` /// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
/// is one of that type's ids. Content is never tied to a template (§2). /// is one of that type's ids (a homepage section's is on the design; a block's, BLOCK_VARIANTS, here).
/// Content is never tied to a template (§2).
model Section { model Section {
id String @id @default(uuid()) id String @id @default(uuid())
pageId String pageId String
@@ -90,6 +91,9 @@ model Section {
variant String? variant String?
position Int @default(0) position Int @default(0)
hidden Boolean @default(false) hidden Boolean @default(false)
/// A block's own background (variants.ts SECTION_BACKGROUNDS), or null to follow the style.
/// Homepage sections keep theirs on the design's home entries instead.
background String?
data Json data Json
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
updatedBy String? updatedBy String?
+17 -3
View File
@@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js';
import { ApiError } from '../http.js'; import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js'; import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js';
import { cleanDesign } from '../site/snapshot.js'; import { cleanDesign } from '../site/snapshot.js';
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js'; import { BLOCK_VARIANTS, BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_BACKGROUNDS, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
type Who = { id: string; role: string }; type Who = { id: string; role: string };
@@ -182,7 +182,8 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo
return getPage(ctx, pageId); return getPage(ctx, pageId);
} }
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() }); /** A block's change: its data, its layout (one of its type's BLOCK_VARIANTS), whether it shows, its own background (null follows the style). */
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional(), background: z.enum(SECTION_BACKGROUNDS).nullable().optional() });
/** The blocks of any other page: add, change, move, remove. */ /** The blocks of any other page: add, change, move, remove. */
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) { export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
@@ -203,7 +204,20 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod
const patch = check(blockPatch, body); const patch = check(blockPatch, body);
await notChangedSince(ctx, s, body, by); await notChangedSince(ctx, s, body, by);
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data); const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } }); const layouts = (BLOCK_VARIANTS as Record<string, readonly string[]>)[s.type] ?? [];
if (patch.variant && !layouts.includes(patch.variant)) {
throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` });
}
await ctx.db.section.update({
where: { id: sectionId },
data: {
...(data !== undefined ? { data: data as never } : {}),
...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}),
...(patch.variant !== undefined ? { variant: patch.variant } : {}),
...(patch.background !== undefined ? { background: patch.background } : {}),
updatedBy: by.id,
},
});
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } }); await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId); return getPage(ctx, pageId);
} }
+91 -2
View File
@@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js'; import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
/**
* A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it
* stays under the installers' nginx `client_max_body_size 25m`.
*/
export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
/** The most the upload route reads, photo or video. */
export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES);
type Kind = { ext: string; mime: string }; type Kind = { ext: string; mime: string };
/** What the bytes are, whatever the name says. */ /** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null { export function sniff(b: Buffer): Kind | null {
// An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out:
// browsers other than Safari often can't play it.
if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' };
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' }; if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' }; if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' }; if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
@@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.'); if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
const kind = sniff(body); const kind = sniff(body);
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.'); if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by);
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.');
const s = await storage(ctx); const s = await storage(ctx);
if (s.usedBytes + body.length > s.limitBytes) { if (s.usedBytes + body.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.'); throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
@@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
return { ...row, url: mediaUrl(row.filename) }; return { ...row, url: mediaUrl(row.filename) };
} }
/**
* A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the
* site plays it as it is. Counted towards storage like a photo.
*/
async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) {
if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.');
if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.');
const clean = cleanVideo(body);
if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.');
const s = await storage(ctx);
if (s.usedBytes + clean.bytes.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
}
const now = ctx.now();
const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`;
const dir = uploadDir(ctx);
await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true });
await fs.writeFile(path.join(dir, filename), clean.bytes);
const row = await ctx.db.mediaAsset.create({
data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by },
});
return { ...row, url: mediaUrl(row.filename) };
}
/** Boxes that hold a video's own boxes, which are searched for metadata. */
const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']);
/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */
const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']);
/**
* An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was
* filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so
* nothing moves and the offsets to the frames stay right. Also reads the picture's size from the
* first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video).
*/
export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null {
const b = Buffer.from(input);
let moov = false;
let width: number | null = null;
let height: number | null = null;
const walk = (start: number, end: number, depth: number): boolean => {
let i = start;
while (i < end) {
if (end - i < 8) return false;
let size = b.readUInt32BE(i);
const type = b.toString('latin1', i + 4, i + 8);
let header = 8;
if (size === 1) {
if (end - i < 16) return false;
const big = b.readBigUInt64BE(i + 8);
if (big > BigInt(end - i)) return false;
size = Number(big);
header = 16;
} else if (size === 0) size = end - i;
if (size < header || i + size > end) return false;
if (depth === 0 && type === 'moov') moov = true;
if (VIDEO_METADATA.has(type)) {
b.write('free', i + 4, 'latin1');
b.fill(0, i + header, i + size);
} else if (VIDEO_CONTAINERS.has(type)) {
if (!walk(i + header, i + size, depth + 1)) return false;
} else if (type === 'tkhd' && width === null) {
const v1 = b[i + header] === 1;
const at = i + header + (v1 ? 88 : 76);
if (at + 8 <= i + size) {
const w = b.readUInt32BE(at) >>> 16;
const h = b.readUInt32BE(at + 4) >>> 16;
if (w > 0 && h > 0) [width, height] = [w, h];
}
}
i += size;
}
return true;
};
if (!walk(0, b.length, 0) || !moov) return null;
return { bytes: b, width, height };
}
export const MAX_WIDTH = 2400; export const MAX_WIDTH = 2400;
export const WIDTHS = [480, 960, 1600] as const; export const WIDTHS = [480, 960, 1600] as const;
+3 -3
View File
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js'; import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js'; import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js'; import { linkedProducts } from '../links/store.js';
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js'; import { deleteMedia, MAX_BODY_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js'; import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js'; import { maintenanceRouter } from './maintenance.js';
@@ -97,10 +97,10 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ─── // ─── Media library and storage ───
r.get('/media', handle(async () => { r.get('/media', handle(async () => {
const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]); const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) }; return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), mime: m.mime, alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
})); }));
r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; })); r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) => r.post('/media', editor, express.raw({ type: () => true, limit: MAX_BODY_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id))); 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). // Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req)))); r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req))));
+2
View File
@@ -108,6 +108,8 @@ export function createApp(ctx: Ctx) {
if (err instanceof ApiError) return sendError(res, err); if (err instanceof ApiError) return sendError(res, err);
const e = err as { type?: string; status?: number }; const e = err as { type?: string; status?: number };
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.')); if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
// Only an upload is ever this large (express.raw's limit on POST /media).
if (e?.type === 'entity.too.large') return sendError(res, new ApiError(413, 'TOO_LARGE', 'That file is too large: photos can be up to 15 MB and videos up to 20 MB. Make it smaller and try again.'));
// A missing upload (express.static), or another known client error. // A missing upload (express.static), or another known client error.
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid.")); if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
return sendError(res, err); return sendError(res, err);
+1 -1
View File
@@ -333,7 +333,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
{ {
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [ kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } }, { type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, { type: 'image-text', variant: 'image-left', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } },
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } }, { type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
], ],
}, },
+6 -5
View File
@@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js'; import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js'; import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js'; import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js'; import { blockVariant, defaultDesign, isSectionBackground, isVariant, SECTION_BACKGROUNDS, SECTION_TYPES, switchTemplate, type SectionBackground, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1; export const SNAPSHOT_VERSION = 1;
@@ -34,7 +34,7 @@ export const framed = (img: Image | null, f: unknown): Image | null => {
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown }; type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
/** `background`: a homepage section's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */ /** `background`: a homepage section's or block's own background (variants.ts SECTION_BACKGROUNDS), when it has one. */
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown>; background?: SectionBackground }; export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown>; background?: SectionBackground };
export type SnapshotPage = { export type SnapshotPage = {
@@ -106,7 +106,8 @@ export type Source = {
pages: { pages: {
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
inNav: boolean; position: number; imageId: string | null; inNav: boolean; position: number; imageId: string | null;
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[]; /** `background` only when a block has one, so versions published before it compare equal. */
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; background?: string; data: unknown }[];
}[]; }[];
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[]; 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 }[]; leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[];
@@ -133,7 +134,7 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
pages: w.pages.map((p) => ({ pages: w.pages.map((p) => ({
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
position: p.position, imageId: p.imageId, position: p.position, imageId: p.imageId,
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })), sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })),
})), })),
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })), 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 })), 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 })),
@@ -189,7 +190,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
const data = parseSectionData(x.type, x.data); const data = parseSectionData(x.type, x.data);
if (!data) continue; if (!data) continue;
collect(data); collect(data);
sections.push({ type: x.type, variant: x.variant, data }); sections.push({ type: x.type, variant: blockVariant(x.type, x.variant), data, ...(isSectionBackground(x.background) ? { background: x.background } : {}) });
} }
} }
return { return {
+23
View File
@@ -114,6 +114,29 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h
export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const; export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const;
export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number]; export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number];
export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v);
/**
* The layouts of the other pages' blocks, the default first. Stored on the block's own row
* (`Section.variant`); like the homepage's, **an id never changes or goes away** once released,
* and one that isn't listed (an older row's) is drawn as the default.
*/
export const BLOCK_VARIANTS = {
text: ['standard', 'centred'],
'image-text': ['image-left', 'image-right', 'image-above'],
quote: ['centred', 'line'],
cta: ['centred', 'banner'],
} as const;
export type BlockVariantType = keyof typeof BLOCK_VARIANTS;
/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */
export function blockVariant(type: string, variant: string | null | undefined): string | null {
const list = (BLOCK_VARIANTS as Record<string, readonly string[]>)[type];
if (!list) return variant ?? null;
return variant && list.includes(variant) ? variant : list[0]!;
}
/** A homepage entry: the section, whether it shows, and its own background when it has one. */ /** A homepage entry: the section, whether it shows, and its own background when it has one. */
export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground }; export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground };
+1 -1
View File
@@ -98,7 +98,7 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp }; const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data }); await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
await db.section.deleteMany({ where: { pageId: id } }); await db.section.deleteMany({ where: { pageId: id } });
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } }); for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, background: x.background ?? null, data: x.data as never, ...stamp } });
return; return;
} }
if (what === 'ministry') { if (what === 'ministry') {
@@ -4,6 +4,7 @@ import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js'; import { hashToken } from '../src/lib/crypto.js';
import { previewContent, siteContent } from '../src/site/content.js'; import { previewContent, siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js'; import { publish } from '../src/site/snapshot.js';
import { changes, discard } from '../src/site/workingCopy.js';
import { harness, SITE } from './support/harness.js'; import { harness, SITE } from './support/harness.js';
async function site() { async function site() {
@@ -85,3 +86,42 @@ describe('an address that changed (§6)', () => {
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' }); assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
}); });
}); });
describe("a block's layout and background", () => {
it('saves one of its own layouts and a background from the church\'s colours, previews them, and discards them', async () => {
const { ctx, db, as } = await site();
const page = await db.page.create({ data: { kind: 'custom', slug: 'join', title: 'Join us' } });
const block = await db.section.create({ data: { pageId: page.id, type: 'cta', data: { heading: 'Come along', text: null, button: null } } });
await db.section.create({ data: { pageId: page.id, type: 'text', variant: 'something-old', data: { heading: null, body: 'Hi' } } });
await publish(ctx, { id: 'x', role: 'system' });
// Drawn with its type's default until it has a layout; an id it doesn't know is drawn so too.
const shown = async () => {
const c = await previewContent(ctx);
assert.ok(c.mode === 'published');
return c.snapshot.pages.find((p) => p.slug === 'join')!.sections.map((s) => ({ type: s.type, variant: s.variant, background: s.background }));
};
assert.deepEqual(await shown(), [{ type: 'cta', variant: 'centred', background: undefined }, { type: 'text', variant: 'standard', background: undefined }]);
const put = (b: object) => as('ann')('put', `/pages/${page.id}/blocks/${block.id}`, b);
assert.equal((await put({ variant: 'banner' })).status, 200);
assert.equal((await put({ background: 'dark' })).status, 200);
const wrong = await put({ variant: 'image-left' });
assert.equal(wrong.status, 400);
assert.match(wrong.body.error.message, /isn't a layout of this block/);
assert.equal((await put({ background: 'pink' })).status, 400);
assert.deepEqual((await shown())[0], { type: 'cta', variant: 'banner', background: 'dark' });
// A change like any other: listed, and discarded back to what's published.
const pending = (await changes(ctx)).find((c) => c.key === `page:${page.id}`);
assert.ok(pending);
await discard(ctx, `page:${page.id}`, { id: 'x', role: 'editor' });
const back = await db.section.findUnique({ where: { id: block.id } });
assert.equal(back?.background, null);
assert.equal(back?.variant, null);
// Back to null follows the style again.
assert.equal((await put({ background: 'tint' })).status, 200);
assert.equal((await put({ background: null })).status, 200);
assert.equal((await shown())[0]!.background, undefined);
});
});
+69
View File
@@ -5,6 +5,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import request from 'supertest'; import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js'; import { hashToken } from '../src/lib/crypto.js';
import { cleanVideo } from '../src/admin/media.js';
import { parseSectionData } from '../src/site/sections.js'; import { parseSectionData } from '../src/site/sections.js';
import { harness, SITE } from './support/harness.js'; import { harness, SITE } from './support/harness.js';
@@ -56,3 +57,71 @@ describe('framing a photo in its frame', () => {
assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null); assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null);
}); });
}); });
/** An MP4 box: its size, its type, then what's in it. */
const box = (type: string, ...parts: Buffer[]) => {
const body = Buffer.concat(parts);
const head = Buffer.alloc(8);
head.writeUInt32BE(8 + body.length, 0);
head.write(type, 4, 'latin1');
return Buffer.concat([head, body]);
};
/** A version 0 track header for a picture `w` by `h` (16.16 fixed point at its end). */
const tkhd = (w: number, h: number) => {
const b = Buffer.alloc(84);
b.writeUInt32BE(w << 16, 76);
b.writeUInt32BE(h << 16, 80);
return box('tkhd', b);
};
const PLACE = '+52.3676+004.9041/';
/** A small MP4 filmed somewhere: where in `udta` (©xyz) and Apple's `meta`, as phones save them. */
function mp4(brand = 'isom') {
return Buffer.concat([
box('ftyp', Buffer.from(`${brand}\0\0\0\0isommp42`, 'latin1')),
box('moov',
box('mvhd', Buffer.alloc(100)),
box('trak', tkhd(640, 360), box('mdia', box('mdhd', Buffer.alloc(24)))),
box('udta', box('©xyz', Buffer.from(PLACE, 'latin1'))),
box('meta', Buffer.from(`com.apple.quicktime.location.ISO6709${PLACE}`, 'latin1'))),
box('mdat', Buffer.from('frames go here')),
]);
}
describe('a video for the top of the page', () => {
it('takes away where it was filmed without moving anything, and reads its size', () => {
const v = mp4();
const clean = cleanVideo(v)!;
assert.equal(clean.bytes.length, v.length);
assert.equal(clean.bytes.includes(Buffer.from(PLACE)), false);
assert.equal(clean.bytes.includes(Buffer.from('com.apple.quicktime.location')), false);
assert.ok(clean.bytes.includes(Buffer.from('frames go here')));
// The frames sit where they did, so the offsets to them still hold.
assert.equal(clean.bytes.indexOf('mdat'), v.indexOf('mdat'));
assert.deepEqual([clean.width, clean.height], [640, 360]);
// The upload itself isn't changed.
assert.ok(v.includes(Buffer.from(PLACE)));
// Boxes that don't add up, or no moov: not a video.
assert.equal(cleanVideo(Buffer.concat([v.subarray(0, 40), Buffer.from([0, 0, 1, 0])])), null);
assert.equal(cleanVideo(box('ftyp', Buffer.from('isom\0\0\0\0', 'latin1'))), null);
});
it('uploads an MP4 to the library, and refuses QuickTime and one too large', async () => {
const { app, db, uploads } = await site();
const post = (b: Buffer) => request(app).post('/api/v1/admin/media?alt=People%20arriving').set('Cookie', 'ccw_session=ann').set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(b);
const ok = await post(mp4());
assert.equal(ok.status, 200, JSON.stringify(ok.body));
assert.equal(ok.body.mime, 'video/mp4');
assert.match(ok.body.url, /\.mp4$/);
const row = await db.mediaAsset.findUnique({ where: { id: ok.body.id } });
assert.deepEqual([row?.width, row?.height, row?.alt], [640, 360, 'People arriving']);
const saved = await fs.readFile(path.join(uploads, String(row!.filename)));
assert.equal(saved.includes(Buffer.from(PLACE)), false);
const mov = await post(mp4('qt '));
assert.equal(mov.status, 415);
assert.match(mov.body.error.message, /MP4/);
const big = await post(Buffer.concat([mp4(), Buffer.alloc(20 * 1024 * 1024)]));
assert.equal(big.status, 413);
assert.match(big.body.error.message, /20 MB/);
});
});
@@ -13,7 +13,7 @@ const DEFAULTS: Record<string, () => Row> = {
leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }), leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
messageSeries: () => ({ summary: null, imageId: null }), messageSeries: () => ({ summary: null, imageId: null }),
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }), page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }), section: () => ({ variant: null, background: null, position: 0, hidden: false, updatedBy: null }),
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }), message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }), 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 }), mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
+73 -1
View File
@@ -274,7 +274,6 @@ test("on the home page: each section's layout, background, place and showing, an
await expect(welcome.getByText("Pastor's photo and quote")).toBeVisible(); await expect(welcome.getByText("Pastor's photo and quote")).toBeVisible();
await page.getByLabel("Welcome: background").selectOption("brand"); await page.getByLabel("Welcome: background").selectOption("brand");
await expect(page.getByLabel("Welcome: background")).toHaveValue("brand"); await expect(page.getByLabel("Welcome: background")).toHaveValue("brand");
await page.screenshot({ path: "e2e/test-results/home-sections.png", fullPage: true });
// Hide it, show it, and move it. // Hide it, show it, and move it.
await page.getByRole("button", { name: "Hide Welcome" }).click(); await page.getByRole("button", { name: "Hide Welcome" }).click();
@@ -293,3 +292,76 @@ test("on the home page: each section's layout, background, place and showing, an
await expect(page.getByLabel("Top of the page layout")).toHaveValue("text"); await expect(page.getByLabel("Top of the page layout")).toHaveValue("text");
await expect(page.getByLabel("Welcome background")).toHaveValue("brand"); await expect(page.getByLabel("Welcome background")).toHaveValue("brand");
}); });
/** A small MP4 (ftyp, moov with one track, mdat): enough to upload; browsers needn't play it. */
function tinyMp4(): Buffer {
const box = (type: string, ...parts: Buffer[]) => {
const body = Buffer.concat(parts);
const head = Buffer.alloc(8);
head.writeUInt32BE(8 + body.length, 0);
head.write(type, 4, "latin1");
return Buffer.concat([head, body]);
};
const tkhd = Buffer.alloc(84);
tkhd.writeUInt32BE(640 << 16, 76);
tkhd.writeUInt32BE(360 << 16, 80);
return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isommp42", "latin1")), box("moov", box("mvhd", Buffer.alloc(100)), box("trak", box("tkhd", tkhd))), box("mdat", Buffer.from("frames"))]);
}
test("a page's blocks: their layouts and backgrounds", async ({ page, context }) => {
await signIn(context);
await page.goto("/admin/pages");
await page.getByRole("link", { name: /^Plan your visit\b/ }).first().click();
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
const preview = page.frameLocator('iframe[title="Live preview of this page"]');
await expect(preview.locator("section[data-bg]")).toHaveCount(0);
await page.getByRole("button", { name: /^Text/ }).first().click();
await page.getByLabel("Text block 1: background").selectOption("dark");
await expect(preview.locator('section[data-bg="dark"]')).toHaveCount(1);
await page.getByLabel("Text block 1: layout").selectOption("centred");
await expect(preview.locator("section .cc-text.text-center")).toHaveCount(1);
await page.getByRole("button", { name: /^Image and text/ }).first().click();
await page.getByLabel("Image and text block 2: layout").selectOption("image-right");
await expect(preview.locator('.cc-frame[class*="md:order-2"]')).toHaveCount(1);
await page.getByRole("button", { name: /^Call to action/ }).first().click();
await expect(preview.locator("section.cc-own-bg")).toHaveCount(0);
await page.getByLabel("Call to action block 3: layout").selectOption("banner");
await expect(preview.locator("section.cc-own-bg")).toHaveCount(1);
// Saved on the blocks: there when the page opens again.
await page.reload();
await page.getByRole("button", { name: /^Image and text/ }).first().click();
await expect(page.getByLabel("Image and text block 2: layout")).toHaveValue("image-right");
await expect(page.getByRole("button", { name: /^Call to action/ }).first()).toContainText("Banner in your colour");
});
test("upload a video for the top of the page's Video layout", async ({ page, context }) => {
await signIn(context);
await page.goto("/admin/pages");
await page.getByRole("link", { name: /^Home\b/ }).first().click();
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
await page.getByRole("button", { name: /^Top of the page/ }).click();
await page.getByLabel("Top of the page (hero): layout").selectOption("photo");
await expect(page.getByText("Video (plays muted, on a loop)")).toHaveCount(0);
await page.getByLabel("Top of the page (hero): layout").selectOption("video");
await expect(page.getByText("Still photo (shown before the video plays, and on phones)")).toBeVisible();
await page.getByRole("button", { name: "Choose", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Choose a video" });
await expect(dialog.getByText("No videos in your library yet")).toBeVisible();
await dialog.locator('input[type="file"]').setInputFiles({ name: "welcome.mp4", mimeType: "video/mp4", buffer: tinyMp4() });
await dialog.getByLabel("What the video shows").fill("People arriving on a Sunday");
await dialog.getByRole("button", { name: "Upload" }).click();
await expect(dialog).toHaveCount(0);
await page.getByRole("button", { name: "Save", exact: true }).click();
await expect(page.getByText("Saved as a draft.")).toBeVisible();
const preview = page.frameLocator('iframe[title="Live preview of this page"]');
await expect(preview.locator(".cc-section-hero video")).toHaveAttribute("src", /\.mp4$/);
// The library lists it with the photos; photo fields never offer it.
await page.goto("/admin/media");
await expect(page.locator("main li video")).toHaveCount(1);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.10.0", "version": "1.11.0",
"private": true, "private": true,
"description": "Church Website: the church's public site in its template, and the admin", "description": "Church Website: the church's public site in its template, and the admin",
"scripts": { "scripts": {
+4 -1
View File
@@ -17,7 +17,7 @@ import { Btn, Field, inputClass } from "./ui";
type Spec = { layouts?: string[] } & ( type Spec = { layouts?: string[] } & (
| { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number } | { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number }
| { key: string; kind: "number"; label: string; min: number; max: number } | { key: string; kind: "number"; label: string; min: number; max: number }
| { key: string; kind: "image"; label: string } | { key: string; kind: "image" | "video"; label: string }
| { key: string; kind: "images"; label: string; max: number; count?: Record<string, number>; labels?: Record<string, string> } | { key: string; kind: "images"; label: string; max: number; count?: Record<string, number>; labels?: Record<string, string> }
| { key: string; kind: "button"; label: string } | { key: string; kind: "button"; label: string }
| { key: string; kind: "group"; label: string; fields: Spec[] }); | { key: string; kind: "group"; label: string; fields: Spec[] });
@@ -29,6 +29,7 @@ export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> =
hero: { name: "Top of the page (hero)", fields: [ hero: { name: "Top of the page (hero)", fields: [
{ key: "headline", kind: "text", label: "Headline", max: 120 }, { key: "headline", kind: "text", label: "Headline", max: 120 },
{ key: "subline", kind: "textarea", label: "Under the headline", max: 300 }, { key: "subline", kind: "textarea", label: "Under the headline", max: 300 },
{ key: "videoId", kind: "video", label: "Video (plays muted, on a loop)", layouts: ["video"] },
// As site/sections/Hero.tsx draws them: Photo, Video (its still) and Split one, Collage three. // As site/sections/Hero.tsx draws them: Photo, Video (its still) and Split one, Collage three.
{ key: "images", kind: "images", label: "Photos", max: 3, count: { photo: 1, video: 1, split: 1, collage: 3, text: 0 }, { key: "images", kind: "images", label: "Photos", max: 3, count: { photo: 1, video: 1, split: 1, collage: 3, text: 0 },
labels: { photo: "Photo", video: "Still photo (shown before the video plays, and on phones)", split: "Photo (beside the headline)", collage: "Photos (three, for the collage)" } }, labels: { photo: "Photo", video: "Still photo (shown before the video plays, and on phones)", split: "Photo (beside the headline)", collage: "Photos (three, for the collage)" } },
@@ -83,6 +84,8 @@ export function DataForm({ fields, value, onChange, errors, prefix = "", frame,
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>; return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>;
case "number": 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>; return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
case "video":
return <div key={f.key}><ImagePicker kind="video" label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
case "image": case "image":
return <div key={f.key}><ImagePicker label={f.label} slot={{ key: f.key }} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>; 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": { case "images": {
@@ -53,6 +53,8 @@ export function frameFor(design: Design, type: string, key: string, index = 0):
} }
if (type === "event") return { ratio: 16 / 10, label: "On the event's card (a little taller on its own page)" }; if (type === "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)" }; if (type === "invitation") return { ratio: 3, label: "Behind the invitation, darkened (the Image background layout)" };
// A block's own layout (passed in as the design's variant for its type).
if (type === "image-text" && v === "image-above") return { ratio: 16 / 9, label: "Above the text, the page's full width" };
return { ratio: 4 / 3, label: "Beside the text" }; return { ratio: 4 / 3, label: "Beside the text" };
} }
@@ -31,6 +31,20 @@ export function layoutsFor(design: Design, options: DesignOptions | undefined, s
return { ordered: [...recommended, ...(ALL_VARIANTS[section] ?? []).filter((v) => !recommended.includes(v))], recommended }; return { ordered: [...recommended, ...(ALL_VARIANTS[section] ?? []).filter((v) => !recommended.includes(v))], recommended };
} }
/** The other pages' blocks' layouts, the default first (backend variants.ts BLOCK_VARIANTS). */
export const BLOCK_LAYOUTS: Record<string, { id: string; name: string }[]> = {
text: [{ id: "standard", name: "Standard" }, { id: "centred", name: "Centred" }],
"image-text": [{ id: "image-left", name: "Photo on the left" }, { id: "image-right", name: "Photo on the right" }, { id: "image-above", name: "Photo above" }],
quote: [{ id: "centred", name: "Centred" }, { id: "line", name: "With a line" }],
cta: [{ id: "centred", name: "Centred" }, { id: "banner", name: "Banner in your colour" }],
};
/** A block's layout as the site draws it: its own when it's one of its type's, else the default. */
export function blockLayout(type: string, variant: string | null): string | undefined {
const list = BLOCK_LAYOUTS[type];
return list?.some((l) => l.id === variant) ? variant! : list?.[0]?.id;
}
/** A section's own background (backend variants.ts SECTION_BACKGROUNDS), each from the church's colours; "" follows Style → Section colour. */ /** A section's own background (backend variants.ts SECTION_BACKGROUNDS), each from the church's colours; "" follows Style → Section colour. */
export const BACKGROUNDS: { id: string; name: string; swatch: string }[] = [ export const BACKGROUNDS: { id: string; name: string; swatch: string }[] = [
{ id: "", name: "As the style sets it", swatch: "repeating-linear-gradient(45deg, #fff 0 4px, rgb(var(--brand-tint)) 4px 8px)" }, { id: "", name: "As the style sets it", swatch: "repeating-linear-gradient(45deg, #fff 0 4px, rgb(var(--brand-tint)) 4px 8px)" },
+42 -18
View File
@@ -7,7 +7,7 @@ import { api } from "./api";
import { Framed, FramingDialog, useFraming } from "./framing"; import { Framed, FramingDialog, useFraming } from "./framing";
import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui"; import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui";
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] }; export type MediaItem = { id: string; url: string; mime?: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] };
export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number }; export 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`; export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
@@ -23,15 +23,28 @@ export function StorageMeter({ s }: { s: Storage }) {
); );
} }
/** Upload form: a photo and what it shows (alt text is required, §3 "Every image needs alt text"). */ /** What a picker or upload takes: photos, a video (MP4, for the top of the page's Video layout), or either (the library). */
export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) => void; disabled?: boolean }) { export type MediaKind = "image" | "video" | "any";
/** Whether a library item is a video (by its type; items listed before videos existed are photos). */
export const isVideo = (m: Pick<MediaItem, "mime">) => !!m.mime?.startsWith("video/");
const UPLOAD = {
image: { label: "Photo", accept: "image/jpeg,image/png,image/webp", hint: "JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.", noun: "photo" },
video: { label: "Video", accept: "video/mp4", hint: "MP4, up to 20 MB. A short, quiet clip (10 to 20 seconds) works best: it plays muted, on a loop.", noun: "video" },
any: { label: "Photo or video", accept: "image/jpeg,image/png,image/webp,video/mp4", hint: "Photos as JPEG, PNG or WebP, up to 15 MB; a video for the top of the page as MP4, up to 20 MB.", noun: "file" },
} as const;
/** Upload form: a photo or video and what it shows (alt text is required, §3 "Every image needs alt text"). */
export function Uploader({ onUploaded, disabled, kind = "image" }: { onUploaded: (m: MediaItem) => void; disabled?: boolean; kind?: MediaKind }) {
const file = useRef<HTMLInputElement>(null); const file = useRef<HTMLInputElement>(null);
const [alt, setAlt] = useState(""); const [alt, setAlt] = useState("");
const { busy, message, run } = useAction(); const { busy, message, run } = useAction();
const u = UPLOAD[kind];
const go = () => run(async () => { const go = () => run(async () => {
const f = file.current?.files?.[0]; const f = file.current?.files?.[0];
if (!f) throw new Error("Choose a photo first."); if (!f) throw new Error(`Choose a ${u.noun} first.`);
if (!alt.trim()) throw new Error("Say what the photo shows (for people who can't see it)."); if (!alt.trim()) throw new Error(`Say what the ${u.noun === "file" ? "photo or video" : u.noun} shows (for people who can't see it).`);
const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f }); const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f });
setAlt(""); setAlt("");
if (file.current) file.current.value = ""; if (file.current) file.current.value = "";
@@ -39,10 +52,10 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
}, "Uploaded."); }, "Uploaded.");
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<Field label="Photo" hint="JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page."> <Field label={u.label} hint={u.hint}>
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="block text-sm" disabled={disabled} /> <input ref={file} type="file" accept={u.accept} className="block text-sm" disabled={disabled} />
</Field> </Field>
<Field label="What the photo shows" hint="Read out to people who can't see it, e.g. “Families at the church picnic”."> <Field label={kind === "video" ? "What the video shows" : "What the photo shows"} hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
<input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} /> <input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} />
</Field> </Field>
<Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn> <Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn>
@@ -51,17 +64,27 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
); );
} }
/** A library item small: the photo, or the video's first frame (muted, never playing). */
export function MediaThumb({ m, className, alt = m.alt }: { m: MediaItem; className?: string; alt?: string }) {
return isVideo(m)
? <video src={`${m.url}#t=0.1`} muted playsInline preload="metadata" aria-label={alt || undefined} className={className} />
: <img src={m.url} alt={alt} className={className} />;
}
/** /**
* One image field: shows the chosen image, with Choose and Remove. In a section (`slot` and a * One image field (or, with `kind="video"`, a video field): shows the chosen one, with Choose and
* FramingContext), it's shown in the shape of its frame on the site, with Move and zoom. * Remove, and only offers its kind from the library. In a section (`slot` and a FramingContext), a
* photo is shown in the shape of its frame on the site, with Move and zoom.
*/ */
export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) { export function ImagePicker({ value, onChange, label, slot, kind = "image" }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number }; kind?: "image" | "video" }) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [framingOpen, setFramingOpen] = useState(false); const [framingOpen, setFramingOpen] = useState(false);
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null); const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
const chosen = data?.items.find((m) => m.id === value); const chosen = data?.items.find((m) => m.id === value);
const framing = useFraming(); const framing = useFraming();
const frame = framing && slot ? framing.frame(slot.key, slot.index) : null; const frame = framing && slot && kind === "image" ? framing.frame(slot.key, slot.index) : null;
const items = data?.items.filter((m) => isVideo(m) === (kind === "video"));
const noun = kind === "video" ? "video" : "image";
const focus = value ? framing?.get(value) : undefined; const focus = value ? framing?.get(value) : undefined;
return ( return (
<div> <div>
@@ -74,7 +97,7 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
</button> </button>
) : ( ) : (
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50"> <div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>} {chosen ? <MediaThumb m={chosen} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No {noun}</span>}
</div> </div>
)} )}
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn> <Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
@@ -87,17 +110,18 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
onDone={(f) => { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} /> onDone={(f) => { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} />
)} )}
{open && ( {open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image"> <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label={`Choose ${kind === "video" ? "a video" : "an image"}`}>
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl"> <div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
<div className="mb-4 flex items-center justify-between"> <div className="mb-4 flex items-center justify-between">
<h2 className="text-lg font-semibold">Choose an image</h2> <h2 className="text-lg font-semibold">Choose {kind === "video" ? "a video" : "an image"}</h2>
<Btn onClick={() => setOpen(false)}>Close</Btn> <Btn onClick={() => setOpen(false)}>Close</Btn>
</div> </div>
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4"> <div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
{data?.items.map((m) => ( {items?.length === 0 && <p className="col-span-full text-sm text-gray-600">No {noun}s in your library yet: upload one below.</p>}
{items?.map((m) => (
<button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }} <button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }}
className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}> className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}>
<img src={m.url} alt="" className="aspect-[4/3] w-full object-cover" /> <MediaThumb m={m} alt="" className="aspect-[4/3] w-full object-cover" />
<span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span> <span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span>
</button> </button>
))} ))}
@@ -105,7 +129,7 @@ export function ImagePicker({ value, onChange, label, slot }: { value: string |
<div className="mt-6 border-t border-gray-200 pt-4"> <div className="mt-6 border-t border-gray-200 pt-4">
<h3 className="mb-2 font-semibold">Upload a new one</h3> <h3 className="mb-2 font-semibold">Upload a new one</h3>
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>} {data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>}
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} /> <Uploader kind={kind} disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
</div> </div>
</div> </div>
</div> </div>
@@ -2,7 +2,7 @@
import { useState } from "react"; import { useState } from "react";
import { api, canEdit } from "@/admin/api"; import { api, canEdit } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media"; import { gb, MediaThumb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui"; import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
import { Image as ImageIcon, Trash2 } from "lucide-react"; import { Image as ImageIcon, Trash2 } from "lucide-react";
@@ -19,15 +19,15 @@ export default function Media() {
const s = data.storage; const s = data.storage;
return ( return (
<> <>
<Title icon={ImageIcon} sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title> <Title icon={ImageIcon} sub="Photos for your pages, and a short video for the top of your home page. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]"> <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<Panel> <Panel>
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>} {message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
{data.items.length === 0 && <p className="text-gray-600">No photos yet.</p>} {data.items.length === 0 && <p className="text-gray-600">No photos or videos yet.</p>}
<ul className="grid gap-4 sm:grid-cols-2"> <ul className="grid gap-4 sm:grid-cols-2">
{data.items.map((m) => ( {data.items.map((m) => (
<li key={m.id} className="space-y-2"> <li key={m.id} className="space-y-2">
<img src={m.url} alt={m.alt} className="aspect-[4/3] w-full rounded object-cover" /> <MediaThumb m={m} className="aspect-[4/3] w-full rounded object-cover" />
<label className="block text-xs text-gray-600">What it shows <label className="block text-xs text-gray-600">What it shows
<input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} /> <input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} />
</label> </label>
@@ -70,7 +70,7 @@ export default function Media() {
</div> </div>
</Panel> </Panel>
<Panel title="Upload a photo"> <Panel title="Upload a photo">
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />} {s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader kind="any" onUploaded={() => reload()} />}
</Panel> </Panel>
</div> </div>
</div> </div>
@@ -18,11 +18,11 @@ import { api } from "@/admin/api";
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields"; import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { frameFor, type Framing } from "@/admin/framing"; import { frameFor, type Framing } from "@/admin/framing";
import { WithPreview } from "@/admin/LivePreview"; import { WithPreview } from "@/admin/LivePreview";
import { BACKGROUNDS, layoutsFor, moved, TEMPLATE_NAMES, VARIANT_NAMES, withBackground, withShown, type Design, type DesignOptions, type HomeEntry } from "@/admin/layouts"; import { BACKGROUNDS, BLOCK_LAYOUTS, blockLayout, layoutsFor, moved, TEMPLATE_NAMES, VARIANT_NAMES, withBackground, withShown, type Design, type DesignOptions, type HomeEntry } from "@/admin/layouts";
import { ImagePicker } from "@/admin/media"; import { ImagePicker } from "@/admin/media";
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui"; import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string }; type Section = { id: string; type: string; variant: string | null; hidden: boolean; background: string | null; data: Record<string, unknown>; updatedAt: string };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] }; type 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[] };
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"]; const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
@@ -50,11 +50,25 @@ const summary = (data: Record<string, unknown>) => {
return null; return null;
}; };
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame, layout, settings }: { /** A section's or block's own background, from the church's colours ("" follows the style). */
function BackgroundField({ name, value, busy, onChange }: { name: string; value: string; busy: boolean; onChange: (background: string) => void }) {
return (
<Field label="Background" hint="From your church's colours. A layout with a photo or band keeps its own.">
<span className="flex items-center gap-2">
<span className="h-9 w-9 shrink-0 rounded border border-gray-300" style={{ background: BACKGROUNDS.find((b) => b.id === value)?.swatch }} aria-hidden />
<select aria-label={`${name}: background`} className={inputClass} value={value} disabled={busy} onChange={(ev) => onChange(ev.target.value)}>
{BACKGROUNDS.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
</select>
</span>
</Field>
);
}
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame, layout, layoutName, settings }: {
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; frame?: Framing["frame"]; 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; onSave: (data: Record<string, unknown>) => Promise<unknown>; hidden?: React.ReactNode; extra?: React.ReactNode;
/** A home page section's layout (only its fields are offered) and its layout and background controls. */ /** A home page section's layout (only its fields are offered) and its layout and background controls. */
layout?: string; settings?: React.ReactNode; layout?: string; layoutName?: string; settings?: React.ReactNode;
}) { }) {
const [value, setValue] = useState(initial); const [value, setValue] = useState(initial);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -68,7 +82,7 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, fr
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span> <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand-text" aria-hidden><Icon className="h-[18px] w-[18px]" /></span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-2 font-semibold text-gray-900">{title}{hidden}</span> <span className="flex flex-wrap items-center gap-2 font-semibold text-gray-900">{title}{hidden}</span>
<span className="block truncate text-xs text-gray-500">{layout && `${VARIANT_NAMES[layout] ?? layout} · `}{line ?? "Nothing written yet"}</span> <span className="block truncate text-xs text-gray-500">{layout && `${layoutName ?? VARIANT_NAMES[layout] ?? layout} · `}{line ?? "Nothing written yet"}</span>
</span> </span>
{open ? <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" aria-hidden /> : <ChevronRight className="h-4 w-4 shrink-0 text-gray-400" aria-hidden />} {open ? <ChevronDown className="h-4 w-4 shrink-0 text-gray-400" aria-hidden /> : <ChevronRight className="h-4 w-4 shrink-0 text-gray-400" aria-hidden />}
<span className="sr-only">{open ? "Close" : "Edit"}</span> <span className="sr-only">{open ? "Close" : "Edit"}</span>
@@ -196,16 +210,7 @@ export default function EditPage() {
</select> </select>
</Field> </Field>
{/* The top of the page draws its own background (photo, colour or plain). */} {/* The top of the page draws its own background (photo, colour or plain). */}
{type !== "hero" && ( {type !== "hero" && <BackgroundField name={spec.name} value={background} busy={layouts.busy} onChange={(b) => saveDesign({ home: withBackground(home, type, b) })} />}
<Field label="Background" hint="From your church's colours. A layout with a photo or band keeps its own.">
<span className="flex items-center gap-2">
<span className="h-9 w-9 shrink-0 rounded border border-gray-300" style={{ background: BACKGROUNDS.find((b) => b.id === background)?.swatch }} aria-hidden />
<select aria-label={`${spec.name}: background`} className={inputClass} value={background} disabled={layouts.busy} onChange={(ev) => saveDesign({ home: withBackground(home, type, ev.target.value) })}>
{BACKGROUNDS.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
</select>
</span>
</Field>
)}
</div> </div>
); );
return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} frame={(key, n) => frameFor(saved, type, key, n)} return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} frame={(key, n) => frameFor(saved, type, key, n)}
@@ -226,8 +231,25 @@ export default function EditPage() {
{page.sections.map((s, i) => { {page.sections.map((s, i) => {
const spec = BLOCK_FIELDS[s.type]; const spec = BLOCK_FIELDS[s.type];
if (!spec) return null; if (!spec) return null;
// A block's layout and background are its own (saved on it straight away, like hiding it).
const layout = blockLayout(s.type, s.variant);
const options = BLOCK_LAYOUTS[s.type] ?? [];
const name = `${spec.name} block ${i + 1}`;
const settings = (
<div className="grid gap-4 rounded-lg bg-gray-50 p-3 sm:grid-cols-2">
{options.length > 1 && (
<Field label="Layout">
<select aria-label={`${name}: layout`} className={inputClass} value={layout} disabled={blocks.busy} onChange={(ev) => blockCall(`/blocks/${s.id}`, "PUT", { variant: ev.target.value })}>
{options.map((l) => <option key={l.id} value={l.id}>{l.name}</option>)}
</select>
</Field>
)}
<BackgroundField name={name} value={s.background ?? ""} busy={blocks.busy} onChange={(b) => blockCall(`/blocks/${s.id}`, "PUT", { background: b || null })} />
</div>
);
return ( return (
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data} frame={(key, i) => frameFor(design.data?.design, s.type, key, i)} <SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data} layout={layout} layoutName={options.find((l) => l.id === layout)?.name} settings={settings}
frame={(key, n) => frameFor(design.data?.design && { ...design.data.design, variants: { ...design.data.design.variants, [s.type]: layout ?? "" } }, s.type, key, n)}
hidden={s.hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Hidden</span>} 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 } }))} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
extra={<> extra={<>
@@ -430,27 +430,55 @@ function Invitation(p: SectionProps) {
); );
} }
// ─── Blocks on the other pages ────────────────────────────────────────────────── // ─── Blocks on the other pages, each in its layouts (backend variants.ts BLOCK_VARIANTS) ──
// Text: Standard · Centred
function TextBlock(p: SectionProps) { function TextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string }; const d = p.section.data as { heading: string | null; body: string };
return <Section p={p}><div className="cc-wrap"><div className="cc-text">{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /></div></div></Section>; return <Section p={p}><div className="cc-wrap"><div className={cx("cc-text", p.section.variant === "centred" && "text-center")}>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /></div></div></Section>;
} }
// Image and text: Photo on the left · Photo on the right · Photo above
function ImageTextBlock(p: SectionProps) { function ImageTextBlock(p: SectionProps) {
const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData }; const d = p.section.data as { heading: string | null; body: string; imageId: string | null; button: ButtonData };
const image = media(p.site, d.imageId, p.section.data);
const round = p.template === "community" && "rounded-[2rem]";
const words = <>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /><div className="mt-6"><Button button={d.button} /></div></>;
if (p.section.variant === "image-above") {
return (
<Section p={p}>
<div className="cc-wrap">
<Img image={image} ratio="aspect-[16/9]" sizes="(min-width: 1280px) 1200px, 100vw" className={cx(round)} />
<div className="cc-text mt-10">{words}</div>
</div>
</Section>
);
}
return ( return (
<Section p={p}> <Section p={p}>
<div className="cc-wrap grid items-center gap-10 md:grid-cols-2"> <div className="cc-wrap grid items-center gap-10 md:grid-cols-2">
<Img image={media(p.site, d.imageId, p.section.data)} className={cx(p.template === "community" && "rounded-[2rem]")} /> <Img image={image} className={cx(round, p.section.variant === "image-right" && "md:order-2")} />
<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>{words}</div>
</div> </div>
</Section> </Section>
); );
} }
// Quote: Centred · With a line
function QuoteBlock(p: SectionProps) { function QuoteBlock(p: SectionProps) {
const d = p.section.data as { quote: string; by: string | null }; const d = p.section.data as { quote: string; by: string | null };
if (p.section.variant === "line") {
return (
<Section p={p}>
<div className="cc-wrap">
<figure className="cc-text border-l-4 border-accent pl-6">
<blockquote className="font-heading text-2xl leading-snug sm:text-3xl">“{d.quote}”</blockquote>
{str(d.by) && <figcaption className="cc-muted mt-4">{d.by}</figcaption>}
</figure>
</div>
</Section>
);
}
return ( return (
<Section p={p}> <Section p={p}>
<figure className="cc-wrap text-center"> <figure className="cc-wrap text-center">
@@ -461,8 +489,9 @@ function QuoteBlock(p: SectionProps) {
); );
} }
// Call to action: Centred · Banner (the invitation's, without a photo)
function CtaBlock(p: SectionProps) { function CtaBlock(p: SectionProps) {
return <Invitation {...p} section={{ ...p.section, variant: "centred", data: { ...p.section.data, imageId: null } }} />; return <Invitation {...p} section={{ ...p.section, variant: p.section.variant === "banner" ? "banner" : "centred", data: { ...p.section.data, imageId: null } }} />;
} }
const SECTIONS: Record<string, (p: SectionProps) => React.ReactNode> = { const SECTIONS: Record<string, (p: SectionProps) => React.ReactNode> = {
+9 -2
View File
@@ -11,7 +11,7 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released | | What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------| |------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.9.0** | `events@3.9.0` | 2026-12-01 | | Cross Events | `crosscode-platform` (`apps/events`) | **3.9.0** | `events@3.9.0` | 2026-12-01 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.10.0** | `website@1.10.0` | 2026-12-01 | | Church Website | `crosscode-platform` (`apps/website`) | **1.11.0** | `website@1.11.0` | 2026-12-01 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.10.0** | `accounts@1.10.0` | 2026-12-01 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.10.0** | `accounts@1.10.0` | 2026-12-01 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.7.0** | `agent@1.7.0` | 2026-11-30 | | Server agent | `crosscode-platform` (`apps/agent`) | **1.7.0** | `agent@1.7.0` | 2026-11-30 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.24.0** | `contracts@1.24.0` | 2026-11-30 | | Contracts | `crosscode-platform` (`packages/contracts`) | **1.24.0** | `contracts@1.24.0` | 2026-11-30 |
@@ -31,7 +31,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0, Events 3.8.0 and Website 1.8.0) | | `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0, Events 3.8.0 and Website 1.8.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) | | `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.4.0 (fonts, `ChurchFooter`, `ColourField`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0, 0.4.0 with Accounts 1.10.0 and Website 1.9.0) | | `@crosscode/ui` | `packages/ui` | 0.4.0 (fonts, `ChurchFooter`, `ColourField`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0, 0.4.0 with Accounts 1.10.0 and Website 1.9.0) |
| Website | `apps/website` | 1.10.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28, 1.8.0 on 2026-11-30, 1.9.0 and 1.10.0 on 2026-12-01; tagged as `website@…`; see "Deployed / rolled out" for where it runs) | | Website | `apps/website` | 1.11.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28, 1.8.0 on 2026-11-30, 1.9.0 to 1.11.0 on 2026-12-01; tagged as `website@…`; see "Deployed / rolled out" for where it runs) |
| App | `apps/app` | 0.0.0 on main (a placeholder); 0.1.0 on the branch `feat/app-scaffold`, being built from 2026-12-01 (phase 6; not released, merged and tagged `app@1.0.0` when the plan is built) | | App | `apps/app` | 0.0.0 on main (a placeholder); 0.1.0 on the branch `feat/app-scaffold`, being built from 2026-12-01 (phase 6; not released, merged and tagged `app@1.0.0` when the plan is built) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -39,6 +39,13 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for ## What each latest release was for
- **Website 1.11.0 (2026-12-01):** the other pages' blocks get layouts (text, image and text,
quote, call to action) and their own backgrounds in the church's colours, and the hero's Video
layout gets a video: MP4 uploads up to 20 MB, where it was filmed taken out. **Migration**
(`Section.background`, nullable). No contracts change, works with any Accounts. On a FastPanel
site, the site's upload size limit must allow 20 MB. Checked: the Website backend tests (152),
the frontend's typecheck and lint, the admin, variants and templates e2e suites. Not deployed.
- **Website 1.10.0 (2026-12-01):** the home page's editor (Pages → Home) sets each section's - **Website 1.10.0 (2026-12-01):** the home page's editor (Pages → Home) sets each section's
layout, background, order and whether it shows (still under Template and style too), and a layout, background, order and whether it shows (still under Template and style too), and a
section offers only the photos its layout shows, a slot for each (1 for Photo, Video and Split, section offers only the photos its layout shows, a slot for each (1 for Photo, Video and Split,
+2 -2
View File
@@ -363,7 +363,7 @@
}, },
"apps/website/backend": { "apps/website/backend": {
"name": "@crosscode/website-backend", "name": "@crosscode/website-backend",
"version": "1.10.0", "version": "1.11.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/auth-client": "*", "@crosscode/auth-client": "*",
@@ -393,7 +393,7 @@
}, },
"apps/website/frontend": { "apps/website/frontend": {
"name": "@crosscode/website-frontend", "name": "@crosscode/website-frontend",
"version": "1.10.0", "version": "1.11.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/seo": "*", "@crosscode/seo": "*",