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 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 09:57:02 +02:00
co-authored by Claude Opus 5.5
parent a38468ba47
commit f5f778f0d7
28 changed files with 543 additions and 69 deletions
+17 -3
View File
@@ -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<string, readonly string[]>)[s.type] ?? [];
if (patch.variant && !layouts.includes(patch.variant)) {
throw new ApiError(400, 'VALIDATION', `"${patch.variant}" isn't a layout of this block.`, { variant: `One of ${layouts.join(', ')}` });
}
await ctx.db.section.update({
where: { id: sectionId },
data: {
...(data !== undefined ? { data: data as never } : {}),
...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}),
...(patch.variant !== undefined ? { variant: patch.variant } : {}),
...(patch.background !== undefined ? { background: patch.background } : {}),
updatedBy: by.id,
},
});
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
+91 -2
View File
@@ -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;
+3 -3
View File
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { 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))));
+2
View File
@@ -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);
+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: [
{ 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' } } },
],
},
+6 -5
View File
@@ -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<string, unknown>; 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<ReturnType<typeof readWorkingCopy>>): Source
pages: w.pages.map((p) => ({
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
position: p.position, imageId: p.imageId,
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, ...(x.background ? { background: x.background } : {}), data: x.data })),
})),
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })),
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })),
@@ -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 {
+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 type SectionBackground = (typeof SECTION_BACKGROUNDS)[number];
export const isSectionBackground = (v: unknown): v is SectionBackground => (SECTION_BACKGROUNDS as readonly unknown[]).includes(v);
/**
* The layouts of the other pages' blocks, the default first. Stored on the block's own row
* (`Section.variant`); like the homepage's, **an id never changes or goes away** once released,
* and one that isn't listed (an older row's) is drawn as the default.
*/
export const BLOCK_VARIANTS = {
text: ['standard', 'centred'],
'image-text': ['image-left', 'image-right', 'image-above'],
quote: ['centred', 'line'],
cta: ['centred', 'banner'],
} as const;
export type BlockVariantType = keyof typeof BLOCK_VARIANTS;
/** A block's layout as drawn: its own when it's one of its type's, else the type's default (null for an unknown type). */
export function blockVariant(type: string, variant: string | null | undefined): string | null {
const list = (BLOCK_VARIANTS as Record<string, readonly string[]>)[type];
if (!list) return variant ?? null;
return variant && list.includes(variant) ? variant : list[0]!;
}
/** A homepage entry: the section, whether it shows, and its own background when it has one. */
export type HomeEntry = { section: SectionType; hidden: boolean; background?: SectionBackground };
+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 };
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') {