From f5f778f0d754816a4ac43316527b640f38cb4213 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 1 Dec 2026 09:57:02 +0200 Subject: [PATCH] website 1.11.0: layouts and backgrounds for the blocks; a video for the top of the page - Blocks get layouts (BLOCK_VARIANTS: text standard/centred; image and text photo left, right or above; quote centred/with a line; call to action centred/banner), stored on Section.variant and checked against the type; an unknown one draws as the default, as every block looked before. The demo's image-text block id is now image-left. - Each block has its own background (Section.background, migration 20261201000000_block_background), in the published source only when set, put back by Discard and Restore, drawn as the homepage's (data-bg). - MP4 uploads up to 20 MB for the hero's Video layout: QuickTime refused, metadata boxes (udta, meta, uuid) blanked into free boxes of the same size so where it was filmed is gone and the frame offsets hold; size read from tkhd. GET /media lists mime. - Admin: a block's Layout and Background when open; the hero's Video field (only videos; photo fields only photos); the media library shows and takes videos. An upload over the limit says so instead of "That request isn't valid." - Tests: backend (152, three new); e2e for block layouts and a video upload. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++ apps/website/CHANGELOG.md | 34 +++++++ apps/website/WHATS-NEW.md | 12 +++ apps/website/backend/package.json | 2 +- .../migration.sql | 2 + apps/website/backend/prisma/schema.prisma | 6 +- apps/website/backend/src/admin/content.ts | 20 +++- apps/website/backend/src/admin/media.ts | 93 ++++++++++++++++++- apps/website/backend/src/admin/routes.ts | 6 +- apps/website/backend/src/app.ts | 2 + apps/website/backend/src/demo/demoChurch.ts | 2 +- apps/website/backend/src/site/snapshot.ts | 11 ++- apps/website/backend/src/site/variants.ts | 23 +++++ apps/website/backend/src/site/workingCopy.ts | 2 +- apps/website/backend/tests/editing.test.ts | 40 ++++++++ apps/website/backend/tests/media.test.ts | 69 ++++++++++++++ .../website/backend/tests/support/memoryDb.ts | 2 +- apps/website/e2e/admin.spec.ts | 74 ++++++++++++++- apps/website/frontend/package.json | 2 +- apps/website/frontend/src/admin/fields.tsx | 5 +- apps/website/frontend/src/admin/framing.tsx | 2 + apps/website/frontend/src/admin/layouts.ts | 14 +++ apps/website/frontend/src/admin/media.tsx | 60 ++++++++---- .../frontend/src/app/admin/media/page.tsx | 10 +- .../src/app/admin/pages/[id]/page.tsx | 54 +++++++---- .../frontend/src/site/sections/index.tsx | 39 +++++++- docs/VERSIONS.md | 11 ++- package-lock.json | 4 +- 28 files changed, 543 insertions(+), 69 deletions(-) create mode 100644 apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index a34c2ef..3b278cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ 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 The home page laid out from its editor, and photos that match the layout (Joshua, 2026-12-01). diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index ab14bc9..4949204 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -1,5 +1,39 @@ # 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 No migration, no new environment settings, no backend change. diff --git a/apps/website/WHATS-NEW.md b/apps/website/WHATS-NEW.md index 0257eb7..f6f87a2 100644 --- a/apps/website/WHATS-NEW.md +++ b/apps/website/WHATS-NEW.md @@ -3,6 +3,18 @@ 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.11.0 + +- **Layouts and backgrounds for the blocks on your other pages.** Open a block in **Pages** to + choose how it looks: text standard or centred; a photo on the left, on the right or above the + text; a quote centred or with a line beside it; a call to action centred or as a banner in your + colour. Each block can also have its own background in your church's colours, like the home + page's sections. +- **A video for the top of your home page.** Choose the **Video** layout and upload a short MP4 + clip (up to 20 MB; 10 to 20 seconds is plenty). It plays muted, on a loop, over your still + photo; phones and visitors who prefer less motion see the still photo. Like photos, the place a + video was filmed is taken out of it when you upload it. + ## 1.10.0 - **Lay out your home page while you edit it.** In **Pages → Home**, open a section to choose its diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index c3d5840..cf9fd1e 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -1,6 +1,6 @@ { "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", "private": true, "type": "module", diff --git a/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql b/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql new file mode 100644 index 0000000..0d92976 --- /dev/null +++ b/apps/website/backend/prisma/migrations/20261201000000_block_background/migration.sql @@ -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; diff --git a/apps/website/backend/prisma/schema.prisma b/apps/website/backend/prisma/schema.prisma index 9d1f853..70748df 100644 --- a/apps/website/backend/prisma/schema.prisma +++ b/apps/website/backend/prisma/schema.prisma @@ -81,7 +81,8 @@ model Page { } /// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant` -/// is one of that type's ids. Content is never tied to a template (§2). +/// is one of that type's ids (a homepage section's is on the design; a block's, BLOCK_VARIANTS, here). +/// Content is never tied to a template (§2). model Section { id String @id @default(uuid()) pageId String @@ -90,6 +91,9 @@ model Section { variant String? position Int @default(0) hidden Boolean @default(false) + /// A block's own background (variants.ts SECTION_BACKGROUNDS), or null to follow the style. + /// Homepage sections keep theirs on the design's home entries instead. + background String? data Json updatedAt DateTime @updatedAt updatedBy String? diff --git a/apps/website/backend/src/admin/content.ts b/apps/website/backend/src/admin/content.ts index 2a86191..8f63441 100644 --- a/apps/website/backend/src/admin/content.ts +++ b/apps/website/backend/src/admin/content.ts @@ -13,7 +13,7 @@ import { Prisma } from '../generated/prisma/client.js'; import { ApiError } from '../http.js'; import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js'; import { cleanDesign } from '../site/snapshot.js'; -import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_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 }; @@ -182,7 +182,8 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo return getPage(ctx, pageId); } -const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() }); +/** A block's change: its data, its layout (one of its type's BLOCK_VARIANTS), whether it shows, its own background (null follows the style). */ +const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional(), background: z.enum(SECTION_BACKGROUNDS).nullable().optional() }); /** The blocks of any other page: add, change, move, remove. */ export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) { @@ -203,7 +204,20 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod const patch = check(blockPatch, body); await notChangedSince(ctx, s, body, by); const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data); - await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } }); + const layouts = (BLOCK_VARIANTS as Record)[s.type] ?? []; + if (patch.variant && !layouts.includes(patch.variant)) { + throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` }); + } + await ctx.db.section.update({ + where: { id: sectionId }, + data: { + ...(data !== undefined ? { data: data as never } : {}), + ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), + ...(patch.variant !== undefined ? { variant: patch.variant } : {}), + ...(patch.background !== undefined ? { background: patch.background } : {}), + updatedBy: by.id, + }, + }); await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } }); return getPage(ctx, pageId); } diff --git a/apps/website/backend/src/admin/media.ts b/apps/website/backend/src/admin/media.ts index 8210f00..3391676 100644 --- a/apps/website/backend/src/admin/media.ts +++ b/apps/website/backend/src/admin/media.ts @@ -21,11 +21,21 @@ import { audit } from '../lib/audit.js'; import { mediaUrl } from '../site/snapshot.js'; export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; +/** + * A video for the top of the page's Video layout: a short muted loop, so 20 MB is plenty, and it + * stays under the installers' nginx `client_max_body_size 25m`. + */ +export const MAX_VIDEO_BYTES = 20 * 1024 * 1024; +/** The most the upload route reads, photo or video. */ +export const MAX_BODY_BYTES = Math.max(MAX_UPLOAD_BYTES, MAX_VIDEO_BYTES); type Kind = { ext: string; mime: string }; /** What the bytes are, whatever the name says. */ export function sniff(b: Buffer): Kind | null { + // An ISO media file (MP4): its first box is `ftyp`. QuickTime (.mov, brand `qt `) is left out: + // browsers other than Safari often can't play it. + if (b.length > 12 && b.toString('ascii', 4, 8) === 'ftyp') return b.toString('ascii', 8, 12) === 'qt ' ? { ext: 'mov', mime: 'video/quicktime' } : { ext: 'mp4', mime: 'video/mp4' }; if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' }; if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' }; if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' }; @@ -78,9 +88,10 @@ export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defa export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.'); - if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.'); const kind = sniff(body); - if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.'); + if (kind?.mime.startsWith('video/')) return uploadVideo(ctx, body, kind, alt, by); + if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.'); + if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP, or a video as MP4.'); const s = await storage(ctx); if (s.usedBytes + body.length > s.limitBytes) { throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.'); @@ -102,6 +113,84 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) { return { ...row, url: mediaUrl(row.filename) }; } +/** + * A video (MP4), kept as uploaded apart from its metadata (cleanVideo), with no other sizes: the + * site plays it as it is. Counted towards storage like a photo. + */ +async function uploadVideo(ctx: Ctx, body: Buffer, kind: Kind, alt: string, by: string) { + if (kind.ext !== 'mp4') throw new ApiError(415, 'NOT_MP4', 'That video is a QuickTime (.mov) file, which most browsers can\'t play. Save or export it as MP4 and try again.'); + if (body.length > MAX_VIDEO_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That video is larger than 20 MB. Use a shorter clip (10 to 20 seconds is plenty for a loop), or make it smaller, and try again.'); + const clean = cleanVideo(body); + if (!clean) throw new ApiError(415, 'NOT_A_VIDEO', 'That video can\'t be read. Save it again as MP4 and try again.'); + const s = await storage(ctx); + if (s.usedBytes + clean.bytes.length > s.limitBytes) { + throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.'); + } + const now = ctx.now(); + const filename = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.mp4`; + const dir = uploadDir(ctx); + await fs.mkdir(path.join(dir, path.dirname(filename)), { recursive: true }); + await fs.writeFile(path.join(dir, filename), clean.bytes); + const row = await ctx.db.mediaAsset.create({ + data: { filename, mime: kind.mime, bytes: clean.bytes.length, width: clean.width, height: clean.height, alt: alt.trim().slice(0, 500), sizes: [] as never, uploadedBy: by }, + }); + return { ...row, url: mediaUrl(row.filename) }; +} + +/** Boxes that hold a video's own boxes, which are searched for metadata. */ +const VIDEO_CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'edts']); +/** Boxes that hold metadata: where and when it was filmed (`©xyz`, Apple's location keys), the camera, XMP. */ +const VIDEO_METADATA = new Set(['udta', 'meta', 'uuid']); + +/** + * An MP4 without its metadata, as photos lose theirs (a phone video can carry the place it was + * filmed): every metadata box is turned into a `free` box of the same size, filled with zeros, so + * nothing moves and the offsets to the frames stay right. Also reads the picture's size from the + * first video track (`tkhd`). Null when the boxes don't add up or there's no `moov` (not a video). + */ +export function cleanVideo(input: Buffer): { bytes: Buffer; width: number | null; height: number | null } | null { + const b = Buffer.from(input); + let moov = false; + let width: number | null = null; + let height: number | null = null; + const walk = (start: number, end: number, depth: number): boolean => { + let i = start; + while (i < end) { + if (end - i < 8) return false; + let size = b.readUInt32BE(i); + const type = b.toString('latin1', i + 4, i + 8); + let header = 8; + if (size === 1) { + if (end - i < 16) return false; + const big = b.readBigUInt64BE(i + 8); + if (big > BigInt(end - i)) return false; + size = Number(big); + header = 16; + } else if (size === 0) size = end - i; + if (size < header || i + size > end) return false; + if (depth === 0 && type === 'moov') moov = true; + if (VIDEO_METADATA.has(type)) { + b.write('free', i + 4, 'latin1'); + b.fill(0, i + header, i + size); + } else if (VIDEO_CONTAINERS.has(type)) { + if (!walk(i + header, i + size, depth + 1)) return false; + } else if (type === 'tkhd' && width === null) { + const v1 = b[i + header] === 1; + const at = i + header + (v1 ? 88 : 76); + if (at + 8 <= i + size) { + const w = b.readUInt32BE(at) >>> 16; + const h = b.readUInt32BE(at + 4) >>> 16; + if (w > 0 && h > 0) [width, height] = [w, h]; + } + } + i += size; + } + return true; + }; + if (!walk(0, b.length, 0) || !moov) return null; + return { bytes: b, width, height }; +} + export const MAX_WIDTH = 2400; export const WIDTHS = [480, 960, 1600] as const; diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index 0fd5a65..19683d6 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js'; import { publishOn, syncLink } from '../feed/feed.js'; import { connectTo, disconnectFrom } from '../links/connect.js'; import { linkedProducts } from '../links/store.js'; -import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js'; +import { deleteMedia, MAX_BODY_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js'; import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js'; import { maintenanceRouter } from './maintenance.js'; @@ -97,10 +97,10 @@ export function adminRouter(ctx: Ctx) { // ─── Media library and storage ─── r.get('/media', handle(async () => { const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]); - return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) }; + return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), mime: m.mime, alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) }; })); r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; })); - r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) => + r.post('/media', editor, express.raw({ type: () => true, limit: MAX_BODY_BYTES + 1 }), handle((req) => upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id))); // Get more storage: it costs the church, so an Owner or Admin asks (decision 12). r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req)))); diff --git a/apps/website/backend/src/app.ts b/apps/website/backend/src/app.ts index ba9c51d..6550bf7 100644 --- a/apps/website/backend/src/app.ts +++ b/apps/website/backend/src/app.ts @@ -108,6 +108,8 @@ export function createApp(ctx: Ctx) { if (err instanceof ApiError) return sendError(res, err); const e = err as { type?: string; status?: number }; if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.')); + // Only an upload is ever this large (express.raw's limit on POST /media). + if (e?.type === 'entity.too.large') return sendError(res, new ApiError(413, 'TOO_LARGE', 'That file is too large: photos can be up to 15 MB and videos up to 20 MB. Make it smaller and try again.')); // A missing upload (express.static), or another known client error. if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid.")); return sendError(res, err); diff --git a/apps/website/backend/src/demo/demoChurch.ts b/apps/website/backend/src/demo/demoChurch.ts index a4ea3b9..3b8908e 100644 --- a/apps/website/backend/src/demo/demoChurch.ts +++ b/apps/website/backend/src/demo/demoChurch.ts @@ -333,7 +333,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe { kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [ { type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } }, - { type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, + { type: 'image-text', variant: 'image-left', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, { type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } }, ], }, diff --git a/apps/website/backend/src/site/snapshot.ts b/apps/website/backend/src/site/snapshot.ts index 946c08e..fe5b765 100644 --- a/apps/website/backend/src/site/snapshot.ts +++ b/apps/website/backend/src/site/snapshot.ts @@ -11,7 +11,7 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { audit } from '../lib/audit.js'; import { parseSectionData } from './sections.js'; -import { defaultDesign, isVariant, SECTION_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; @@ -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 }; -/** `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; background?: SectionBackground }; export type SnapshotPage = { @@ -106,7 +106,8 @@ export type Source = { pages: { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; position: number; imageId: string | null; - sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[]; + /** `background` only when a block has one, so versions published before it compare equal. */ + sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; background?: string; data: unknown }[]; }[]; ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[]; leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[]; @@ -133,7 +134,7 @@ export function toSource(w: Awaited>): Source pages: w.pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, - sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })), + sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })), })), ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })), leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })), @@ -189,7 +190,7 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot { const data = parseSectionData(x.type, x.data); if (!data) continue; collect(data); - sections.push({ type: x.type, variant: x.variant, data }); + sections.push({ type: x.type, variant: blockVariant(x.type, x.variant), data, ...(isSectionBackground(x.background) ? { background: x.background } : {}) }); } } return { diff --git a/apps/website/backend/src/site/variants.ts b/apps/website/backend/src/site/variants.ts index 62d97c3..96c183c 100644 --- a/apps/website/backend/src/site/variants.ts +++ b/apps/website/backend/src/site/variants.ts @@ -114,6 +114,29 @@ export function headerIsTransparent(template: WebsiteTemplate, header: string, h export const SECTION_BACKGROUNDS = ['light', 'tint', 'accent', 'brand', 'dark'] as const; export type SectionBackground = (typeof SECTION_BACKGROUNDS)[number]; +export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v); + +/** + * The layouts of the other pages' blocks, the default first. Stored on the block's own row + * (`Section.variant`); like the homepage's, **an id never changes or goes away** once released, + * and one that isn't listed (an older row's) is drawn as the default. + */ +export const BLOCK_VARIANTS = { + text: ['standard', 'centred'], + 'image-text': ['image-left', 'image-right', 'image-above'], + quote: ['centred', 'line'], + cta: ['centred', 'banner'], +} as const; + +export type BlockVariantType = keyof typeof BLOCK_VARIANTS; + +/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */ +export function blockVariant(type: string, variant: string | null | undefined): string | null { + const list = (BLOCK_VARIANTS as Record)[type]; + if (!list) return variant ?? null; + return variant && list.includes(variant) ? variant : list[0]!; +} + /** A homepage entry: the section, whether it shows, and its own background when it has one. */ export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground }; diff --git a/apps/website/backend/src/site/workingCopy.ts b/apps/website/backend/src/site/workingCopy.ts index 21c2846..a4c49b6 100644 --- a/apps/website/backend/src/site/workingCopy.ts +++ b/apps/website/backend/src/site/workingCopy.ts @@ -98,7 +98,7 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) { const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp }; await db.page.upsert({ where: { id }, create: { id, ...data }, update: data }); await db.section.deleteMany({ where: { pageId: id } }); - for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } }); + for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, background: x.background ?? null, data: x.data as never, ...stamp } }); return; } if (what === 'ministry') { diff --git a/apps/website/backend/tests/editing.test.ts b/apps/website/backend/tests/editing.test.ts index c4d3e8e..b6ee216 100644 --- a/apps/website/backend/tests/editing.test.ts +++ b/apps/website/backend/tests/editing.test.ts @@ -4,6 +4,7 @@ import request from 'supertest'; import { hashToken } from '../src/lib/crypto.js'; import { previewContent, siteContent } from '../src/site/content.js'; import { publish } from '../src/site/snapshot.js'; +import { changes, discard } from '../src/site/workingCopy.js'; import { harness, SITE } from './support/harness.js'; async function site() { @@ -85,3 +86,42 @@ describe('an address that changed (§6)', () => { assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' }); }); }); + +describe("a block's layout and background", () => { + it('saves one of its own layouts and a background from the church\'s colours, previews them, and discards them', async () => { + const { ctx, db, as } = await site(); + const page = await db.page.create({ data: { kind: 'custom', slug: 'join', title: 'Join us' } }); + const block = await db.section.create({ data: { pageId: page.id, type: 'cta', data: { heading: 'Come along', text: null, button: null } } }); + await db.section.create({ data: { pageId: page.id, type: 'text', variant: 'something-old', data: { heading: null, body: 'Hi' } } }); + await publish(ctx, { id: 'x', role: 'system' }); + + // Drawn with its type's default until it has a layout; an id it doesn't know is drawn so too. + const shown = async () => { + const c = await previewContent(ctx); + assert.ok(c.mode === 'published'); + return c.snapshot.pages.find((p) => p.slug === 'join')!.sections.map((s) => ({ type: s.type, variant: s.variant, background: s.background })); + }; + assert.deepEqual(await shown(), [{ type: 'cta', variant: 'centred', background: undefined }, { type: 'text', variant: 'standard', background: undefined }]); + + const put = (b: object) => as('ann')('put', `/pages/${page.id}/blocks/${block.id}`, b); + assert.equal((await put({ variant: 'banner' })).status, 200); + assert.equal((await put({ background: 'dark' })).status, 200); + const wrong = await put({ variant: 'image-left' }); + assert.equal(wrong.status, 400); + assert.match(wrong.body.error.message, /isn't a layout of this block/); + assert.equal((await put({ background: 'pink' })).status, 400); + assert.deepEqual((await shown())[0], { type: 'cta', variant: 'banner', background: 'dark' }); + + // A change like any other: listed, and discarded back to what's published. + const pending = (await changes(ctx)).find((c) => c.key === `page:${page.id}`); + assert.ok(pending); + await discard(ctx, `page:${page.id}`, { id: 'x', role: 'editor' }); + const back = await db.section.findUnique({ where: { id: block.id } }); + assert.equal(back?.background, null); + assert.equal(back?.variant, null); + // Back to null follows the style again. + assert.equal((await put({ background: 'tint' })).status, 200); + assert.equal((await put({ background: null })).status, 200); + assert.equal((await shown())[0]!.background, undefined); + }); +}); diff --git a/apps/website/backend/tests/media.test.ts b/apps/website/backend/tests/media.test.ts index b8538b6..8c07d31 100644 --- a/apps/website/backend/tests/media.test.ts +++ b/apps/website/backend/tests/media.test.ts @@ -5,6 +5,7 @@ import os from 'node:os'; import path from 'node:path'; import request from 'supertest'; import { hashToken } from '../src/lib/crypto.js'; +import { cleanVideo } from '../src/admin/media.js'; import { parseSectionData } from '../src/site/sections.js'; import { harness, SITE } from './support/harness.js'; @@ -56,3 +57,71 @@ describe('framing a photo in its frame', () => { assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null); }); }); + +/** An MP4 box: its size, its type, then what's in it. */ +const box = (type: string, ...parts: Buffer[]) => { + const body = Buffer.concat(parts); + const head = Buffer.alloc(8); + head.writeUInt32BE(8 + body.length, 0); + head.write(type, 4, 'latin1'); + return Buffer.concat([head, body]); +}; +/** A version 0 track header for a picture `w` by `h` (16.16 fixed point at its end). */ +const tkhd = (w: number, h: number) => { + const b = Buffer.alloc(84); + b.writeUInt32BE(w << 16, 76); + b.writeUInt32BE(h << 16, 80); + return box('tkhd', b); +}; +const PLACE = '+52.3676+004.9041/'; +/** A small MP4 filmed somewhere: where in `udta` (©xyz) and Apple's `meta`, as phones save them. */ +function mp4(brand = 'isom') { + return Buffer.concat([ + box('ftyp', Buffer.from(`${brand}\0\0\0\0isommp42`, 'latin1')), + box('moov', + box('mvhd', Buffer.alloc(100)), + box('trak', tkhd(640, 360), box('mdia', box('mdhd', Buffer.alloc(24)))), + box('udta', box('©xyz', Buffer.from(PLACE, 'latin1'))), + box('meta', Buffer.from(`com.apple.quicktime.location.ISO6709${PLACE}`, 'latin1'))), + box('mdat', Buffer.from('frames go here')), + ]); +} + +describe('a video for the top of the page', () => { + it('takes away where it was filmed without moving anything, and reads its size', () => { + const v = mp4(); + const clean = cleanVideo(v)!; + assert.equal(clean.bytes.length, v.length); + assert.equal(clean.bytes.includes(Buffer.from(PLACE)), false); + assert.equal(clean.bytes.includes(Buffer.from('com.apple.quicktime.location')), false); + assert.ok(clean.bytes.includes(Buffer.from('frames go here'))); + // The frames sit where they did, so the offsets to them still hold. + assert.equal(clean.bytes.indexOf('mdat'), v.indexOf('mdat')); + assert.deepEqual([clean.width, clean.height], [640, 360]); + // The upload itself isn't changed. + assert.ok(v.includes(Buffer.from(PLACE))); + // Boxes that don't add up, or no moov: not a video. + assert.equal(cleanVideo(Buffer.concat([v.subarray(0, 40), Buffer.from([0, 0, 1, 0])])), null); + assert.equal(cleanVideo(box('ftyp', Buffer.from('isom\0\0\0\0', 'latin1'))), null); + }); + + it('uploads an MP4 to the library, and refuses QuickTime and one too large', async () => { + const { app, db, uploads } = await site(); + const post = (b: Buffer) => request(app).post('/api/v1/admin/media?alt=People%20arriving').set('Cookie', 'ccw_session=ann').set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(b); + const ok = await post(mp4()); + assert.equal(ok.status, 200, JSON.stringify(ok.body)); + assert.equal(ok.body.mime, 'video/mp4'); + assert.match(ok.body.url, /\.mp4$/); + const row = await db.mediaAsset.findUnique({ where: { id: ok.body.id } }); + assert.deepEqual([row?.width, row?.height, row?.alt], [640, 360, 'People arriving']); + const saved = await fs.readFile(path.join(uploads, String(row!.filename))); + assert.equal(saved.includes(Buffer.from(PLACE)), false); + + const mov = await post(mp4('qt ')); + assert.equal(mov.status, 415); + assert.match(mov.body.error.message, /MP4/); + const big = await post(Buffer.concat([mp4(), Buffer.alloc(20 * 1024 * 1024)])); + assert.equal(big.status, 413); + assert.match(big.body.error.message, /20 MB/); + }); +}); diff --git a/apps/website/backend/tests/support/memoryDb.ts b/apps/website/backend/tests/support/memoryDb.ts index 3f41e11..3e0dc9f 100644 --- a/apps/website/backend/tests/support/memoryDb.ts +++ b/apps/website/backend/tests/support/memoryDb.ts @@ -13,7 +13,7 @@ const DEFAULTS: Record Row> = { leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }), messageSeries: () => ({ summary: null, imageId: null }), page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }), - section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }), + section: () => ({ variant: null, background: null, position: 0, hidden: false, updatedBy: null }), message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }), simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }), mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }), diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts index 578ab00..268456e 100644 --- a/apps/website/e2e/admin.spec.ts +++ b/apps/website/e2e/admin.spec.ts @@ -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 page.getByLabel("Welcome: background").selectOption("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. 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("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); +}); diff --git a/apps/website/frontend/package.json b/apps/website/frontend/package.json index 57a6faa..d36b638 100644 --- a/apps/website/frontend/package.json +++ b/apps/website/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-frontend", - "version": "1.10.0", + "version": "1.11.0", "private": true, "description": "Church Website: the church's public site in its template, and the admin", "scripts": { diff --git a/apps/website/frontend/src/admin/fields.tsx b/apps/website/frontend/src/admin/fields.tsx index 698c8af..af1dd30 100644 --- a/apps/website/frontend/src/admin/fields.tsx +++ b/apps/website/frontend/src/admin/fields.tsx @@ -17,7 +17,7 @@ import { Btn, Field, inputClass } from "./ui"; type Spec = { layouts?: string[] } & ( | { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number } | { key: string; kind: "number"; label: string; min: number; max: number } - | { key: string; kind: "image"; label: string } + | { key: string; kind: "image" | "video"; label: string } | { key: string; kind: "images"; label: string; max: number; count?: Record; labels?: Record } | { key: string; kind: "button"; label: string } | { key: string; kind: "group"; label: string; fields: Spec[] }); @@ -29,6 +29,7 @@ export const SECTION_FIELDS: Record = hero: { name: "Top of the page (hero)", fields: [ { key: "headline", kind: "text", label: "Headline", max: 120 }, { key: "subline", kind: "textarea", label: "Under the headline", max: 300 }, + { key: "videoId", kind: "video", label: "Video (plays muted, on a loop)", layouts: ["video"] }, // As site/sections/Hero.tsx draws them: Photo, Video (its still) and Split one, Collage three. { key: "images", kind: "images", label: "Photos", max: 3, count: { photo: 1, video: 1, split: 1, collage: 3, text: 0 }, labels: { photo: "Photo", video: "Still photo (shown before the video plays, and on phones)", split: "Photo (beside the headline)", collage: "Photos (three, for the collage)" } }, @@ -83,6 +84,8 @@ export function DataForm({ fields, value, onChange, errors, prefix = "", frame, return