Hero uit het CMS, verschuivingsfix, productie alleen vanaf release-branch #18

Merged
Sluijsens merged 8 commits from feature/hero-module into master 2026-11-17 12:58:07 +01:00
11 changed files with 364 additions and 0 deletions
Showing only changes of commit 72dd381cf9 - Show all commits
@@ -0,0 +1,66 @@
import { describe, expect, it } from 'vitest';
import { parseHero } from '../parseHero';
// The seed of the SLP Software hero in the CMS (scripts/hero-sls.json of the CMS repository).
const seed = {
display: 'single',
title: 'Websites,\napps\n& meer.',
tagline: null,
lead: 'Bij SLP Software kun je terecht.',
buttons: [
{ label: 'Bekijk pakketten', target: '#pakketten' },
{ label: 'Plan een gesprek', target: '#contact' },
],
slides: [],
};
describe('parseHero', () => {
it('reads the seed hero of the CMS', () => {
expect(parseHero(seed)).toEqual({
title: 'Websites,\napps\n& meer.',
lead: 'Bij SLP Software kun je terecht.',
buttons: seed.buttons,
});
});
it('returns null (baked hero) without a usable hero', () => {
for (const value of [null, undefined, 'x', 5, [], {}, { title: '' }, { title: ' \n ' }, { title: 7 }]) {
expect(parseHero(value)).toBeNull();
}
});
it('ignores tagline and slides: a text-only site', () => {
const hero = parseHero({ ...seed, tagline: 'Label', slides: [{ id: 'x' }] });
expect(hero).not.toBeNull();
expect(hero).not.toHaveProperty('tagline');
expect(hero).not.toHaveProperty('slides');
});
it('turns an empty lead into null and trims texts', () => {
expect(parseHero({ ...seed, lead: ' ' })?.lead).toBeNull();
expect(parseHero({ ...seed, lead: null })?.lead).toBeNull();
expect(parseHero({ ...seed, lead: ' Hallo ' })?.lead).toBe('Hallo');
});
it('skips buttons with an unsafe target or an empty label, never repairs them', () => {
const hero = parseHero({
...seed,
buttons: [
{ label: 'Slecht', target: 'javascript:alert(1)' },
{ label: ' ', target: '#contact' },
{ label: 'Goed', target: '/over' },
null,
'x',
],
});
expect(hero?.buttons).toEqual([{ label: 'Goed', target: '/over' }]);
});
it('keeps at most two buttons and accepts zero or a missing list', () => {
const three = [1, 2, 3].map((n) => ({ label: `B${n}`, target: `#b${n}` }));
expect(parseHero({ ...seed, buttons: three })?.buttons).toHaveLength(2);
expect(parseHero({ ...seed, buttons: [] })?.buttons).toEqual([]);
expect(parseHero({ title: 'x' })?.buttons).toEqual([]);
expect(parseHero({ title: 'x', buttons: 'nope' })?.buttons).toEqual([]);
});
});
@@ -0,0 +1,33 @@
import { afterEach, describe, expect, it } from 'vitest';
import { readHeroFromDocument } from '../readHero';
function setBlock(text: string | null) {
document.body.innerHTML = text === null ? '' : '<script type="application/json" id="cms-data"></script>';
if (text !== null) {
document.getElementById('cms-data')!.textContent = text;
}
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('readHeroFromDocument', () => {
it('reads the hero key of the data block', () => {
setBlock(JSON.stringify({ siteUrl: 'https://x', offerings: [], hero: { title: 'A\nB', buttons: [] } }));
expect(readHeroFromDocument(document)).toEqual({ title: 'A\nB', lead: null, buttons: [] });
});
it.each([
['no block', null],
['an empty block', ''],
['the baked block', '{}'],
['hero null', '{"hero":null}'],
['invalid JSON', '{"hero": '],
['a block that is not an object', '"hero"'],
['a hero without title', '{"hero":{"title":" "}}'],
])('returns null for %s (baked hero stays)', (_name, text) => {
setBlock(text);
expect(readHeroFromDocument(document)).toBeNull();
});
});
@@ -0,0 +1,64 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { isSafeTarget } from '../target';
describe('isSafeTarget', () => {
it.each([
'#pakketten',
'#contact',
'#a-b_c1',
'/',
'/over-mij',
'/a?b=1&c=2',
'https://example.com',
'https://example.com/x?y=1#z',
])('accepts %s', (target) => {
expect(isSafeTarget(target)).toBe(true);
});
it.each([
'',
'#',
'# x',
'#a b',
'#a.b',
'//evil.example/x',
'/\\evil',
'/a b',
'javascript:alert(1)',
'JAVASCRIPT:alert(1)',
'data:text/html,x',
'http://example.com',
'https://',
'https://user:pw@example.com',
'https://user@example.com',
'ftp://example.com',
'mailto:a@b.nl',
'pakketten',
'https://exa mple.com',
'/a\nb',
])('refuses %j', (target) => {
expect(isSafeTarget(target)).toBe(false);
});
it('refuses anything that is not a string', () => {
for (const value of [null, undefined, 1, {}, [], true]) {
expect(isSafeTarget(value)).toBe(false);
}
});
it('property: whatever is accepted has one of the three allowed forms and no unsafe characters', () => {
fc.assert(
fc.property(fc.string(), (value) => {
if (!isSafeTarget(value)) return true;
const allowedForm =
/^#[A-Za-z0-9_-]+$/.test(value) ||
(value.startsWith('/') && !value.startsWith('//')) ||
value.startsWith('https://');
// eslint-disable-next-line no-control-regex
return allowedForm && !/[\u0000- \u007f\\]/.test(value);
}),
{ numRuns: 500 },
);
});
});
@@ -0,0 +1,47 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { headingFromLines, titleLines } from '../title';
describe('titleLines', () => {
it('splits on line breaks and trims', () => {
expect(titleLines('Websites,\napps\n& meer.')).toEqual(['Websites,', 'apps', '& meer.']);
expect(titleLines(' a \r\n b\r c ')).toEqual(['a', 'b', 'c']);
});
it('drops empty lines', () => {
expect(titleLines('\n\na\n\n b \n')).toEqual(['a', 'b']);
expect(titleLines(' \n ')).toEqual([]);
});
it('property: no line is empty, has line breaks or has outer spaces', () => {
fc.assert(
fc.property(fc.string(), (title) =>
titleLines(title).every(
(line) => line !== '' && line === line.trim() && !/[\r\n]/.test(line),
),
),
);
});
});
describe('headingFromLines (screen-reader and search-engine heading)', () => {
it('puts the brand prefix before the lines joined with single spaces (the seed title)', () => {
expect(headingFromLines(['Websites,', 'apps', '& meer.'], 'SLP Software:')).toBe(
'SLP Software: Websites, apps & meer.',
);
});
it('works without a prefix and with a single line', () => {
expect(headingFromLines(['Alleen'])).toBe('Alleen');
expect(headingFromLines(['Alleen'], ' ')).toBe('Alleen');
});
it('property: the heading is the prefix, a space and the lines joined by spaces', () => {
fc.assert(
fc.property(
fc.array(fc.string({ minLength: 1 }), { minLength: 1 }),
(lines) => headingFromLines(lines, 'SLP Software:') === `SLP Software: ${lines.join(' ')}`,
),
);
});
});
+6
View File
@@ -0,0 +1,6 @@
export { CMS_DATA_ID, readHeroFromDocument } from './readHero';
export { parseHero } from './parseHero';
export { isSafeTarget } from './target';
export { headingFromLines, titleLines } from './title';
export { useCmsHero } from './useCmsHero';
export type { CmsHero, CmsHeroButton } from './types';
+41
View File
@@ -0,0 +1,41 @@
import { isSafeTarget } from './target';
import { titleLines } from './title';
import type { CmsHero, CmsHeroButton } from './types';
const MAX_BUTTONS = 2;
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
/**
* Turns the untrusted `hero` value of the data block (or the API) into a `CmsHero`, or null when nothing usable is
* there: no object, no title, or a title without any text. Fail-open: null means "show the baked hero". Buttons with
* an empty label or an unsafe target are skipped (never repaired); at most two are kept.
*/
export function parseHero(value: unknown): CmsHero | null {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return null;
}
const raw = value as Record<string, unknown>;
const title = typeof raw.title === 'string' ? titleLines(raw.title).join('\n') : '';
if (title === '') {
return null;
}
const buttons: CmsHeroButton[] = [];
if (Array.isArray(raw.buttons)) {
for (const item of raw.buttons) {
if (buttons.length >= MAX_BUTTONS) break;
if (item === null || typeof item !== 'object') continue;
const { label, target } = item as Record<string, unknown>;
const cleanLabel = text(label);
if (cleanLabel !== '' && isSafeTarget(target)) {
buttons.push({ label: cleanLabel, target });
}
}
}
return { title, lead: text(raw.lead) || null, buttons };
}
+25
View File
@@ -0,0 +1,25 @@
import { parseHero } from './parseHero';
import type { CmsHero } from './types';
/** Id of the data block the CMS host writes into the page (`<script type="application/json" id="cms-data">`). */
export const CMS_DATA_ID = 'cms-data';
/**
* Reads the hero from the `#cms-data` block of the page. Returns null without a block, with a block that is not
* valid JSON, without a `hero` key (or `null`), or with a hero that is not usable: the site then keeps its baked hero.
*/
export function readHeroFromDocument(doc: Pick<Document, 'getElementById'>): CmsHero | null {
try {
const block = doc.getElementById(CMS_DATA_ID);
if (!block?.textContent) {
return null;
}
const data: unknown = JSON.parse(block.textContent);
if (data === null || typeof data !== 'object') {
return null;
}
return parseHero((data as Record<string, unknown>).hero);
} catch {
return null;
}
}
+31
View File
@@ -0,0 +1,31 @@
const ANCHOR = /^#[A-Za-z0-9_-]+$/;
// Control characters, whitespace and backslashes never belong in a target.
// eslint-disable-next-line no-control-regex
const FORBIDDEN = /[\u0000- \u007f\\]/;
/**
* Whether a button target may be used as a link: exactly `#anchor`, a path of the own site (`/path`, not `//host`),
* or an absolute `https://` address with a host and no credentials. Everything else (`javascript:`, `http:`, `data:`,
* protocol-relative addresses, whitespace, backslashes) is refused. The CMS validates the same on saving; this is the
* second check at the point of use.
*/
export function isSafeTarget(target: unknown): target is string {
if (typeof target !== 'string' || target === '' || FORBIDDEN.test(target)) {
return false;
}
if (target.startsWith('#')) {
return ANCHOR.test(target);
}
if (target.startsWith('/')) {
return !target.startsWith('//');
}
if (target.startsWith('https://')) {
try {
const url = new URL(target);
return url.protocol === 'https:' && url.hostname !== '' && url.username === '' && url.password === '';
} catch {
return false;
}
}
return false;
}
+17
View File
@@ -0,0 +1,17 @@
/** The lines of a title: split on line breaks, trimmed, empty lines dropped. */
export function titleLines(title: string): string[] {
return title
.split(/\r\n|\r|\n/)
.map((line) => line.trim())
.filter((line) => line !== '');
}
/**
* The text for screen readers and search engines (the sr-only part of the `h1`): the brand prefix, a space and the
* title lines joined with single spaces. Without a prefix only the joined lines.
*/
export function headingFromLines(lines: readonly string[], prefix = ''): string {
const joined = lines.join(' ');
const start = prefix.trim();
return start === '' ? joined : `${start} ${joined}`;
}
+19
View File
@@ -0,0 +1,19 @@
/** A button of the hero: a label and a checked target (`#anchor`, `/path` or `https://...`). */
export interface CmsHeroButton {
label: string;
target: string;
}
/**
* The hero as the CMS host writes it under `hero` in the `#cms-data` block (and as `GET /api/v1/hero` answers it),
* reduced to what a text-only site uses. Images (`slides`) and `tagline` are not part of the SLP Software hero and
* are left out here. Always the result of `parseHero`: texts are trimmed, buttons are checked.
*/
export interface CmsHero {
/** The title with its line breaks (`\n`), as entered in the CMS. */
title: string;
/** Optional paragraph under the title; null when empty. */
lead: string | null;
/** Zero to two buttons whose target passed `isSafeTarget`. */
buttons: CmsHeroButton[];
}
+15
View File
@@ -0,0 +1,15 @@
import { useState } from 'react';
import { readHeroFromDocument } from './readHero';
import type { CmsHero } from './types';
/**
* The CMS hero of this page load, or null (render the baked hero). The data block is in the first HTML, so it is
* read once, synchronously, in the first render: no flash of baked text before the CMS text. Without a document
* (the build-time prerender) it is always null, so the prerender keeps the baked hero.
*/
export function useCmsHero(): CmsHero | null {
const [hero] = useState<CmsHero | null>(() =>
typeof document === 'undefined' ? null : readHeroFromDocument(document),
);
return hero;
}