Hero from the CMS: markers HERO-HTML and HERO-PRELOAD, hero key in the data block, picture per ratio, baked fallback

The prerendered hero is plain HTML between the markers (first photo, h1, buttons), the slider takes over after hydration with the hero of the host block, the API or the build. The head preload is added to the finished HTML. Hero texts move into nl.json. The stand-in host and the e2e tests cover the hero.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 16:48:00 +01:00
co-authored by Claude Sonnet 5.5
parent 13f78c48cd
commit ad0b114828
31 changed files with 863 additions and 134 deletions
+2 -1
View File
@@ -28,6 +28,7 @@ import {
externalizeInlineScripts,
findExecutableInlineScripts,
} from './inlineScripts.ts';
import { injectHeroPreload } from './heroPreload.ts';
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
export type ViolationCode =
@@ -179,7 +180,7 @@ export function planExternalization(
let result;
try {
result = scripts.externalize(html);
result = scripts.externalize(injectHeroPreload(html));
} catch (error) {
if (!(error instanceof ScriptError)) throw error;
add(file, error.code, detailOf(error));
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { injectHeroPreload } from './heroPreload.ts';
const page = (body: string, head = '<title>t</title>') =>
`<html><head>${head}</head><body>${body}</body></html>`;
describe('injectHeroPreload', () => {
it('writes the preload of the first photo between markers before </head>', () => {
const out = injectHeroPreload(
page(
'<img class="cms-hero-image" src="/assets/hero-8-abc.jpg" width="1" height="1" alt="">',
),
);
expect(out).toContain(
'<title>t</title><!--CMS:HERO-PRELOAD--><link rel="preload" as="image" href="/assets/hero-8-abc.jpg" fetchpriority="high"><!--/CMS:HERO-PRELOAD--></head>',
);
});
it('finds the image when src comes before class', () => {
const out = injectHeroPreload(
page('<img src="/a.jpg" alt="" class="cms-hero-image">'),
);
expect(out).toContain('href="/a.jpg"');
});
it('leaves a page without a hero, without a head and a done page alone', () => {
const plain = page('<img src="/a.jpg" alt="">');
expect(injectHeroPreload(plain)).toBe(plain);
const noHead = '<img class="cms-hero-image" src="/a.jpg">';
expect(injectHeroPreload(noHead)).toBe(noHead);
const once = injectHeroPreload(
page('<img class="cms-hero-image" src="/a.jpg" alt="">'),
);
expect(injectHeroPreload(once)).toBe(once);
});
});
+45
View File
@@ -0,0 +1,45 @@
import { heroPreloadHtml } from '../src/lib/heroHtml.ts';
// The preload link of the hero in the head of a prerendered page, between the
// markers the CMS host rewrites (<!--CMS:HERO-PRELOAD-->). React cannot write
// a comment into the head, so the build step adds it to the finished HTML,
// from the baked first photo of the page. Pages without a hero stay as they
// are, and so does a page that already has the markers (running twice is fine).
const MARK = '<!--CMS:HERO-PRELOAD-->';
const HERO_IMAGE =
/<img\b[^>]*\bclass="cms-hero-image"[^>]*\bsrc="([^"]+)"|<img\b[^>]*\bsrc="([^"]+)"[^>]*\bclass="cms-hero-image"/;
export function injectHeroPreload(html: string): string {
if (html.includes(MARK)) return html;
const found = HERO_IMAGE.exec(html);
const src = found?.[1] ?? found?.[2];
const end = html.indexOf('</head>');
if (src === undefined || end === -1) return html;
// The src is already escaped in the HTML; the link is built from the same
// text, so it is written back unchanged
const link = heroPreloadHtml({
display: 'single',
title: '',
buttons: [],
slides: [
{
id: 'baked',
alt: '',
decorative: false,
image: {
width: 1,
height: 1,
focus: null,
src: '',
variants: [],
},
},
],
}).replace('href=""', `href="${src}"`);
return (
html.slice(0, end) +
`${MARK}${link}<!--/CMS:HERO-PRELOAD-->` +
html.slice(end)
);
}
+39
View File
@@ -54,6 +54,45 @@ describe('injectCms regions', () => {
});
});
describe('injectCms hero', () => {
const hero = {
title: 'Titel',
slides: [
{
id: 'a',
alt: 'Alt',
decorative: false,
image: { width: 10, height: 8, src: '/m/a.webp' },
},
],
};
const regions =
'<!--CMS:HERO-PRELOAD-->old<!--/CMS:HERO-PRELOAD--><!--CMS:HERO-HTML-->old<!--/CMS:HERO-HTML-->';
it('writes the hero and its preload and puts the hero in the data block', () => {
const out = run(
page(
regions +
'<!--CMS:DATA--><script type="application/json" id="cms-data">{}</script>',
),
{ ...live([]), hero },
);
expect(out).toContain('<h1 class="cms-hero-title">');
expect(out).toContain(
'<link rel="preload" as="image" href="/m/a.webp"',
);
expect(out).not.toContain('old');
expect(out).toContain('"hero":{"title":"Titel"');
});
it('keeps the baked hero when there is no usable one', () => {
for (const data of [live([]), { ...live([]), hero: { title: 'x' } }]) {
const out = run(page(regions), data);
expect(out).toBe(page(regions));
}
});
});
describe('injectCms data block', () => {
const baked =
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"source":"build"}</script>';
+14 -5
View File
@@ -9,6 +9,8 @@
// matches that code.
import { bannerHtml, offeringsHtml } from '../src/lib/cmsHtml.ts';
import { scriptJson } from '../src/lib/cmsData.ts';
import { mapHero } from '../src/lib/hero.ts';
import { heroHtml, heroPreloadHtml } from '../src/lib/heroHtml.ts';
import { formatPrice } from '../src/lib/formatPrice.ts';
import { mapBanner, mapOfferings, mapTopBanner } from '../src/lib/offerings.ts';
@@ -16,6 +18,8 @@ export interface LiveData {
// The answers as the public API gives them
offerings: unknown;
banners: { top: unknown; bottom: unknown };
// The answer of GET /api/v1/hero; absent or unusable leaves the baked hero
hero?: unknown;
}
export interface InjectOptions {
@@ -33,7 +37,7 @@ const jsonLd = (value: unknown) =>
.replace(/&/g, '\\u0026');
const REGION =
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->[\s\S]*?<!--\/CMS:\1-->/g;
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->[\s\S]*?<!--\/CMS:\1-->/g;
const DATA_BLOCK =
/<!--CMS:DATA-->(?:<script type="application\/json" id="cms-data">[\s\S]*?<\/script>)?/g;
const OFFER_JSON_LD =
@@ -64,19 +68,23 @@ export function injectCms(html: string, options: InjectOptions): string {
const { data } = options;
const mapped = mapOfferings(data.offerings);
const packages = mapped ? mapped.packages : [];
const hero = mapHero(data.hero);
const prices: Price = new Map(packages.map((pkg) => [pkg.id, pkg.price]));
const regions: Record<string, string> = {
'OFFERINGS-HTML': offeringsHtml(packages),
'BANNER-TOP-HTML': bannerHtml(mapTopBanner(data.banners.top)),
'BANNER-BOTTOM-HTML': bannerHtml(mapBanner(data.banners.bottom)),
'HERO-HTML': heroHtml(hero),
'HERO-PRELOAD': heroPreloadHtml(hero),
};
const siteUrl = options.publicBaseUrl ?? options.authoredBaseUrl;
let out = html
.replace(
REGION,
(_match, name: string) =>
`<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
.replace(REGION, (match, name: string) =>
// No usable hero: the baked one stays (fail open)
name.startsWith('HERO') && !hero
? match
: `<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
)
.replace(
DATA_BLOCK,
@@ -86,6 +94,7 @@ export function injectCms(html: string, options: InjectOptions): string {
...(siteUrl ? { siteUrl } : {}),
offerings: data.offerings,
banners: data.banners,
...(data.hero === undefined ? {} : { hero: data.hero }),
})}</script>`,
)
.replace(OFFER_JSON_LD, (match, slug: string, json: string) => {
+1 -1
View File
@@ -11,7 +11,7 @@
import { readFileSync, writeFileSync } from 'node:fs';
const REGION =
/(<!--CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)[\s\S]*?(<!--\/CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->)/g;
/(<!--CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->)[\s\S]*?(<!--\/CMS:(?:OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML|HERO-HTML|HERO-PRELOAD)-->)/g;
const DATA_BLOCK =
/(?:<!--CMS:DATA-->)?<script type="application\/json" id="cms-data">[\s\S]*?<\/script>|<!--CMS:DATA-->/g;
const OFFER_MARKER = /<!--CMS:OFFER-JSON-LD slug="[a-z0-9-]+"-->/g;
+1
View File
@@ -672,6 +672,7 @@ describe('startPreviewServer', () => {
// Live pakketten: geen gegevens, zonder 404
expect((await ask(port, '/api/v1/offerings')).status).toBe(204);
expect((await ask(port, '/api/v1/offerings/banner')).status).toBe(204);
expect((await ask(port, '/api/v1/hero')).status).toBe(204);
// Al het andere blijft zoals het was
expect((await ask(port, '/api/v1/andere')).status).toBe(404);
expect((await ask(port, '/api/v1/contact-messages')).status).toBe(404);
+3 -1
View File
@@ -227,7 +227,9 @@ export function contactStubResponse(
// asks once per page load)
if (
method === 'GET' &&
(path === '/api/v1/offerings' || path === '/api/v1/offerings/banner')
(path === '/api/v1/offerings' ||
path === '/api/v1/offerings/banner' ||
path === '/api/v1/hero')
) {
return { status: 204, body: '' };
}
+7 -1
View File
@@ -155,7 +155,13 @@ describe.each(priorityPages)('prioriteitsfoto van %s', (path) => {
for (const node of body.querySelectorAll('noscript')) node.remove();
const prioritized = [
...body.querySelectorAll('img[fetchpriority="high"][src]'),
].filter((image) => !image.closest('picture'));
// The hero photo sits in a <picture> but has no <source> for the
// baked page, so its preload is the plain one (config/heroPreload)
].filter(
(image) =>
!image.closest('picture') ||
image.classList.contains('cms-hero-image'),
);
expect(prioritized.length).toBeGreaterThan(0);
for (const image of prioritized) {
const links = preloads(document).filter(
+85
View File
@@ -74,6 +74,8 @@ describe('markers in de gebouwde pagina', () => {
'OFFERINGS-HTML',
'BANNER-TOP-HTML',
'BANNER-BOTTOM-HTML',
'HERO-HTML',
'HERO-PRELOAD',
]) {
expect(home.split(`<!--CMS:${marker}-->`)).toHaveLength(2);
expect(home.split(`<!--/CMS:${marker}-->`)).toHaveLength(2);
@@ -337,3 +339,86 @@ describe('zonder host die injecteert', () => {
expect(messages).toEqual([]);
});
});
const hostHero = (extra: Record<string, unknown> = {}) => ({
display: 'slideshow',
title: 'Nieuwe titel',
tagline: 'Nieuw label',
buttons: [{ label: 'Boek nu', target: '#contact' }],
slides: ['een', 'twee'].map((name) => ({
id: name,
alt: `Alt ${name}`,
decorative: false,
image: {
width: 100,
height: 80,
focus: { x: 0.25, y: 0.75 },
src: '/favicon.png',
variants: [],
},
})),
...extra,
});
describe('de hero van de host', () => {
it('schrijft de eerste foto, de titel en de preload in de HTML', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
const home = await html('/');
const region = home.slice(
home.indexOf('<!--CMS:HERO-HTML-->'),
home.indexOf('<!--/CMS:HERO-HTML-->'),
);
expect(region).toContain('Nieuwe titel');
expect(region).toContain('alt="Alt een"');
expect(region).not.toContain('Alt twee');
expect(region).toContain('style="object-position:25% 75%"');
expect(region).toContain('href="#contact"');
expect(home).toContain(
'<!--CMS:HERO-PRELOAD--><link rel="preload" as="image" href="/favicon.png" fetchpriority="high"><!--/CMS:HERO-PRELOAD-->',
);
});
it('toont na hydratatie de slides van de host, zonder API-verzoek', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS, hero: hostHero() });
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/hero')) {
requested.push(request.url());
}
});
},
});
await waitForHydration(page);
await eventually(() =>
page.locator('[aria-roledescription="carousel"] h1').textContent(),
).toContain('Nieuwe titel');
expect(
await page
.locator('[aria-roledescription="carousel"] img')
.first()
.getAttribute('alt'),
).toBe('Alt een');
expect(requested).toEqual([]);
expect(messages).toEqual([]);
});
it('laat de gebakken hero staan als de data niet bruikbaar is', async () => {
inject({
offerings: FIVE,
banners: NO_BANNERS,
hero: hostHero({ slides: [] }),
});
const home = await html('/');
// The data block still holds what the host sent; the region keeps the
// baked hero
const region = home.slice(
home.indexOf('<!--CMS:HERO-HTML-->'),
home.indexOf('<!--/CMS:HERO-HTML-->'),
);
expect(region).not.toContain('Nieuwe titel');
expect(region).toContain('Andrea Slop');
expect(home).toContain('<!--CMS:HERO-PRELOAD--><link');
});
});
+2 -1
View File
@@ -128,7 +128,8 @@ describe.each(widths)('zonder JavaScript op %i px', (width) => {
.count(),
).resolves.toBe(0);
}
const hero = page.locator('[aria-roledescription="carousel"]');
// De platte hero (tussen de CMS-markers), geen carrousel
const hero = page.locator('[data-cms-region="HERO-HTML"]');
await expect(
hero.locator('img:visible').count(),
).resolves.toBeGreaterThan(0);
+1 -1
View File
@@ -41,7 +41,7 @@ describe('Hero', () => {
[...container.querySelectorAll('img')].map((img) =>
img.getAttribute('src'),
);
const slide = (i: number) => heroContent.slides[i].src;
const slide = (i: number) => heroContent.slides[i].image.src;
const last = heroContent.slides.length - 1;
expect(sources()).toEqual([slide(0)]);
+187 -46
View File
@@ -7,36 +7,154 @@ import {
Image,
VisuallyHidden,
} from '@chakra-ui/react';
import LinkButton from '../LinkButton';
import CmsRegion from '../CmsRegion/CmsRegion';
import HeroArrows from './HeroArrows';
import HeroButton from './HeroButton';
import HeroPauseButton from './HeroPauseButton';
import HeroSocials from './HeroSocials';
import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider';
import type { HeroContent, SocialLink } from '@/content/types';
import useHero from './useHero';
import type { SocialLink } from '@/content/types';
import useHydrated from '@/hooks/useHydrated';
import { t } from '@/i18n';
import type { HeroData, HeroSlide } from '@/lib/hero';
import { heroHtml, variantSrcset } from '@/lib/heroHtml';
import { slidesToLoad } from '@/lib/slidesToLoad';
const SLIDE_DURATION = '6s';
const SIZES = '100vw';
const PORTRAIT = '(orientation: portrait)';
function announcementText(announcement: HeroAnnouncement, slide: string) {
switch (announcement) {
case 'slide':
return slide;
case 'paused':
return 'Diavoorstelling gepauzeerd';
return t('hero.paused');
case 'playing':
return 'Diavoorstelling speelt weer af';
return t('hero.playing');
default:
return '';
}
}
// Where the subject of the photo is; the picture is cropped around it
const objectPosition = (slide: HeroSlide): string | undefined => {
const { focus } = slide.image;
return focus
? `${Number((focus.x * 100).toFixed(2))}% ${Number((focus.y * 100).toFixed(2))}%`
: undefined;
};
type HeroProps = {
content: HeroContent;
content: HeroData;
socials: SocialLink[];
};
// The hero of the homepage. Until hydration it is the plain HTML between the
// CMS markers (what the host may rewrite); after hydration the slider shows
// the data of the host, the API or the build, whichever came first.
export default function Hero({ content, socials }: HeroProps) {
const { title, tagline, cta, slides } = content;
const hero = useHero(content);
return useHydrated() ? (
<HeroSlider content={hero} socials={socials} />
) : (
<HeroPlain content={hero} socials={socials} />
);
}
// The page as the browser first gets it: the first photo with the title and
// the buttons, written by lib/heroHtml and styled by the global CSS of the
// theme (.cms-hero-*). The frame is the same as the slider's, so nothing
// jumps when the slider takes over.
function HeroPlain({ content, socials }: HeroProps) {
return (
<Box
as="section"
aria-label={t('hero.ariaLabel')}
position="relative"
isolation="isolate"
h="100svh"
minH="560px"
overflow="hidden"
bg="ink"
>
<CmsRegion name="HERO-HTML" html={heroHtml(content)}>
{null}
</CmsRegion>
<Box aria-hidden position="absolute" inset={0} bgGradient="scrim" />
<HeroSocials socials={socials} />
</Box>
);
}
// One photo: a picture with a source for portrait screens and, for the
// slides after the first, AVIF as well (the first one is only WebP, because
// the browser preloads exactly that file)
function SlidePicture({
slide,
first,
visible,
scaled,
onLoaded,
}: {
slide: HeroSlide;
first: boolean;
visible: boolean;
scaled: boolean;
onLoaded?: () => void;
}) {
const { image } = slide;
const formats = first ? ['image/webp'] : ['image/avif', 'image/webp'];
const tall = formats.map((type) => ({
type,
srcset: variantSrcset(image.variants, 'tall', type),
}));
const wide = variantSrcset(image.variants, 'wide');
const wideAvif = first
? ''
: variantSrcset(image.variants, 'wide', 'image/avif');
return (
<chakra.picture display="block" w="100%" h="100%">
{tall.map(
({ type, srcset }) =>
srcset && (
<source
key={type}
media={PORTRAIT}
srcSet={srcset}
sizes={SIZES}
type={type}
/>
),
)}
{wideAvif && (
<source srcSet={wideAvif} sizes={SIZES} type="image/avif" />
)}
<Image
src={image.src}
srcSet={wide || undefined}
sizes={wide ? SIZES : undefined}
width={image.width}
height={image.height}
alt={slide.alt}
fetchPriority={first ? 'high' : undefined}
onLoad={onLoaded}
onError={onLoaded}
w="100%"
h="100%"
objectFit="cover"
objectPosition={objectPosition(slide)}
transform={scaled || visible ? 'scale(1)' : 'scale(1.06)'}
transition="transform 9s linear"
/>
</chakra.picture>
);
}
function HeroSlider({ content, socials }: HeroProps) {
const { title, tagline, buttons, slides, display } = content;
const single = display === 'single';
const {
active,
announcement,
@@ -49,7 +167,7 @@ export default function Hero({ content, socials }: HeroProps) {
prev,
advance,
handlers,
} = useHeroSlider(slides.length);
} = useHeroSlider(single ? 1 : slides.length);
// De slides liggen op elkaar in beeld, dus loading="lazy" stelt niets uit.
// Eerst alleen de actieve foto; zodra die binnen en getekend is (twee
// frames later, dus na de eerste paint) ook de volgende en de vorige.
@@ -59,14 +177,14 @@ export default function Hero({ content, socials }: HeroProps) {
requestAnimationFrame(() =>
requestAnimationFrame(() => setFirstPainted(true)),
);
const loaded = firstPainted
? slidesToLoad(active, slides.length)
: [active];
const shown = single ? slides.slice(0, 1) : slides;
const loaded = firstPainted ? slidesToLoad(active, shown.length) : [active];
const current = shown[active];
return (
<Box
as="section"
aria-label="Uitgelicht werk"
aria-label={t('hero.ariaLabel')}
aria-roledescription="carousel"
position="relative"
// Eigen stacking context: de z-indexen hieronder gelden alleen
@@ -81,12 +199,15 @@ export default function Hero({ content, socials }: HeroProps) {
>
{/* Slides: crossfade met een langzame inzoom */}
<Box position="absolute" inset={0}>
{slides.map((slide, i) => (
{shown.map((slide, i) => (
<Box
key={slide.id}
role="group"
aria-roledescription="slide"
aria-label={`${i + 1} van ${slides.length}`}
aria-label={t('hero.slideLabel', {
position: i + 1,
count: shown.length,
})}
aria-hidden={i !== active}
position="absolute"
inset={0}
@@ -96,25 +217,14 @@ export default function Hero({ content, socials }: HeroProps) {
transitionTimingFunction="smooth"
>
{loaded.includes(i) && (
<Image
src={slide.src}
alt={slide.alt}
fetchPriority={i === 0 ? 'high' : undefined}
onLoad={
<SlidePicture
slide={slide}
first={i === 0}
visible={i === active}
scaled={reducedMotion}
onLoaded={
firstPainted ? undefined : onFirstLoaded
}
onError={
firstPainted ? undefined : onFirstLoaded
}
w="100%"
h="100%"
objectFit="cover"
transform={
reducedMotion || i === active
? 'scale(1)'
: 'scale(1.06)'
}
transition="transform 9s linear"
/>
)}
</Box>
@@ -139,29 +249,51 @@ export default function Hero({ content, socials }: HeroProps) {
{/* Tagline en naam samen in één h1: zo staan de zoekwoorden
(wat en waar) in de belangrijkste kop van de pagina */}
<Heading as="h1" mb={9} color="white">
{tagline && (
<>
<chakra.span
display="block"
mb={4}
fontFamily="body"
textStyle="eyebrow"
// Zelfde regelhoogte als lopende tekst, niet die van de kop
lineHeight="1.5"
color="white/80"
>
{tagline}
</chakra.span>{' '}
</>
)}
<chakra.span
display="block"
mb={4}
fontFamily="body"
textStyle="eyebrow"
// Zelfde regelhoogte als lopende tekst, niet die van de kop
lineHeight="1.5"
color="white/80"
textStyle="display"
// Een nieuwe regel in de titel is een regelafbreking
whiteSpace="pre-line"
>
{tagline}
</chakra.span>{' '}
<chakra.span display="block" textStyle="display">
{title}
</chakra.span>
</Heading>
<LinkButton to={cta.to} variant="light">
{cta.label}
</LinkButton>
{buttons.length > 0 && (
<Box
display="flex"
flexWrap="wrap"
justifyContent="center"
gap={4}
>
{buttons.map((button) => (
<HeroButton
key={`${button.label}|${button.target}`}
label={button.label}
target={button.target}
/>
))}
</Box>
)}
</Container>
{slides.length > 1 && <HeroArrows onPrev={prev} onNext={next} />}
{shown.length > 1 && <HeroArrows onPrev={prev} onNext={next} />}
<HeroSocials socials={socials} />
{autoplay && (
{autoplay && shown.length > 1 && (
<HeroPauseButton stopped={stopped} onToggle={toggleStopped} />
)}
@@ -175,13 +307,22 @@ export default function Hero({ content, socials }: HeroProps) {
>
{announcementText(
announcement,
`Foto ${active + 1} van ${slides.length}: ${slides[active].alt}`,
t(
current.alt
? 'hero.announcement'
: 'hero.announcementPlain',
{
position: active + 1,
count: shown.length,
alt: current.alt,
},
),
)}
</VisuallyHidden>
{/* Voortgangsbalk: als de animatie klaar is, schuift de slider door.
Door de key start hij opnieuw bij elke slidewissel. */}
{autoplay && (
{autoplay && shown.length > 1 && (
<Box
key={active}
aria-hidden
+3 -2
View File
@@ -1,4 +1,5 @@
import { chakra, useRecipe } from '@chakra-ui/react';
import { t } from '@/i18n';
import { Icon } from '@iconify/react/offline';
import leftOutlined from '@iconify-icons/ant-design/left-outlined';
import rightOutlined from '@iconify-icons/ant-design/right-outlined';
@@ -14,7 +15,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
<>
<ArrowButton
side="left"
aria-label="Vorige foto"
aria-label={t('hero.prev')}
data-testid="hero-prev-button"
data-requires-js
onClick={onPrev}
@@ -23,7 +24,7 @@ export default function HeroArrows({ onPrev, onNext }: HeroArrowsProps) {
</ArrowButton>
<ArrowButton
side="right"
aria-label="Volgende foto"
aria-label={t('hero.next')}
data-testid="hero-next-button"
data-requires-js
onClick={onNext}
+26
View File
@@ -0,0 +1,26 @@
import { chakra, useRecipe } from '@chakra-ui/react';
import LinkButton from '../LinkButton';
// A button of the hero: a path of the site goes through the router, an anchor
// or an https address is a plain link in the same style.
export default function HeroButton({
label,
target,
}: {
label: string;
target: string;
}) {
const recipe = useRecipe({ key: 'linkButton' });
if (target.startsWith('/')) {
return (
<LinkButton to={target} variant="light">
{label}
</LinkButton>
);
}
return (
<chakra.a href={target} css={recipe({ variant: 'light' })}>
{label}
</chakra.a>
);
}
+2 -5
View File
@@ -1,4 +1,5 @@
import { chakra, useRecipe } from '@chakra-ui/react';
import { t } from '@/i18n';
import { Icon } from '@iconify/react/offline';
import caretRightOutlined from '@iconify-icons/ant-design/caret-right-outlined';
import pauseOutlined from '@iconify-icons/ant-design/pause-outlined';
@@ -19,11 +20,7 @@ export default function HeroPauseButton({
return (
<chakra.button
type="button"
aria-label={
stopped
? 'Diavoorstelling afspelen'
: 'Diavoorstelling pauzeren'
}
aria-label={stopped ? t('hero.play') : t('hero.pause')}
data-testid="hero-pause-button"
data-requires-js
onClick={onToggle}
+23 -13
View File
@@ -4,23 +4,33 @@ import siteContent from '@/content/siteContent';
import { serverHtml } from '@/test/hydrate';
import Hero from './Hero';
// Controls that do nothing without JavaScript carry the marker the head CSS
// hides (BR-NJS-01, BR-NJS-03)
// The prerendered hero is the plain HTML between the CMS markers: the first
// photo, the title and the buttons. The slider controls only exist after
// hydration, so a visitor without JavaScript never sees a dead control.
describe('Hero in the prerendered HTML', () => {
it('marks the arrows, the pause button and the progress bar', async () => {
it('is the first photo between the markers, without slider controls', async () => {
const html = await serverHtml(
<Hero content={heroContent} socials={siteContent.socials} />,
);
expect(html).toContain('<!--CMS:HERO-HTML-->');
expect(html).toContain('<!--/CMS:HERO-HTML-->');
const doc = new DOMParser().parseFromString(html, 'text/html');
const marked = (testId: string) =>
doc
.querySelector(`[data-testid="${testId}"]`)
?.hasAttribute('data-requires-js');
expect(marked('hero-prev-button')).toBe(true);
expect(marked('hero-next-button')).toBe(true);
expect(marked('hero-pause-button')).toBe(true);
expect(marked('hero-progress')).toBe(true);
expect(doc.querySelectorAll('[data-requires-js]')).toHaveLength(4);
const images = doc.querySelectorAll('img.cms-hero-image');
expect(images).toHaveLength(1);
expect(images[0].getAttribute('src')).toBe(
heroContent.slides[0].image.src,
);
expect(images[0].getAttribute('fetchpriority')).toBe('high');
expect(doc.querySelector('h1.cms-hero-title')?.textContent).toContain(
heroContent.title,
);
for (const id of [
'hero-prev-button',
'hero-next-button',
'hero-pause-button',
'hero-progress',
]) {
expect(doc.querySelector(`[data-testid="${id}"]`)).toBeNull();
}
});
});
+102
View File
@@ -0,0 +1,102 @@
import { screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import heroContent from '@/content/heroContent';
import { renderWithProviders } from '@/test/renderWithProviders';
import type { LoadJson } from '@/components/PackagesProvider/PackagesProvider';
import useHero from './useHero';
const answer = (title: string) => ({
title,
slides: [
{
id: 'a',
alt: 'Alt',
decorative: false,
image: { width: 10, height: 8, src: '/m/a.webp' },
},
],
});
function Title({ load }: { load: LoadJson }) {
return <p data-testid="title">{useHero(heroContent, load).title}</p>;
}
const block = (data: unknown) => {
const script = document.createElement('script');
script.type = 'application/json';
script.id = 'cms-data';
script.textContent = JSON.stringify(data);
document.body.append(script);
};
afterEach(() => {
document.getElementById('cms-data')?.remove();
vi.useRealTimers();
});
describe('useHero', () => {
it('takes the hero of the data block and asks nothing', async () => {
block({ hero: answer('Van de host') });
const load = vi.fn<LoadJson>();
await renderWithProviders(<Title load={load} />);
await waitFor(() =>
expect(screen.getByTestId('title')).toHaveTextContent(
'Van de host',
),
);
expect(load).not.toHaveBeenCalled();
});
it('keeps the baked hero when the block has no usable one', async () => {
block({ hero: { title: 'x' } });
await renderWithProviders(<Title load={vi.fn<LoadJson>()} />);
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
});
it('asks the API without a block and shows a usable answer', async () => {
const load = vi.fn<LoadJson>().mockResolvedValue(answer('Van de API'));
await renderWithProviders(<Title load={load} />);
await waitFor(() =>
expect(screen.getByTestId('title')).toHaveTextContent('Van de API'),
);
expect(load.mock.calls[0][0]).toBe('/api/v1/hero');
});
it('keeps the baked hero on a 204, an error or an unusable answer', async () => {
for (const load of [
vi.fn<LoadJson>().mockResolvedValue(undefined),
vi.fn<LoadJson>().mockRejectedValue(new Error('status 500')),
vi.fn<LoadJson>().mockResolvedValue({ title: 'x' }),
]) {
const { unmount } = await renderWithProviders(
<Title load={load} />,
);
await waitFor(() => expect(load).toHaveBeenCalled());
await Promise.resolve();
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
unmount();
}
});
it('gives up after the time-out', async () => {
vi.useFakeTimers();
const load = vi.fn<LoadJson>(
(_path, signal) =>
new Promise((_resolve, reject) =>
signal.addEventListener('abort', () =>
reject(new Error('aborted')),
),
),
);
await renderWithProviders(<Title load={load} />);
await vi.advanceTimersByTimeAsync(8001);
expect(load.mock.calls[0][1].aborted).toBe(true);
expect(screen.getByTestId('title')).toHaveTextContent(
heroContent.title,
);
});
});
+49
View File
@@ -0,0 +1,49 @@
import { useEffect, useMemo, useState } from 'react';
import {
loadFromApi,
type LoadJson,
} from '@/components/PackagesProvider/PackagesProvider';
import useHydrated from '@/hooks/useHydrated';
import { hostCmsData } from '@/lib/cmsData';
import { mapHero, type HeroData } from '@/lib/hero';
const HERO_PATH = '/api/v1/hero';
const TIMEOUT_MS = 8000;
// The hero to show: the one in the data block the CMS host wrote, else the
// one the API gives, else the baked one. Failing safe is the rule: a missing
// block, a network error, a 204, a time-out or an answer that cannot be used
// leaves the baked hero on screen. The block is only read after hydration,
// so the first render equals the prerendered HTML.
export default function useHero(
baked: HeroData,
load: LoadJson = loadFromApi,
): HeroData {
const hydrated = useHydrated();
const fromBlock = useMemo(() => {
const block = hydrated ? hostCmsData(document) : null;
return block?.hero === undefined ? null : mapHero(block.hero);
}, [hydrated]);
const [fetched, setFetched] = useState<HeroData | null>(null);
useEffect(() => {
// The host sent the data: nothing to ask
if (hostCmsData(document)) return;
const controller = new AbortController();
const { signal } = controller;
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
load(HERO_PATH, signal)
.then((answer) => {
const mapped = mapHero(answer);
if (mapped && !signal.aborted) setFetched(mapped);
})
.catch(() => undefined)
.finally(() => clearTimeout(timer));
return () => {
clearTimeout(timer);
controller.abort();
};
}, [load]);
return fromBlock ?? fetched ?? baked;
}
@@ -33,7 +33,7 @@ const TIMEOUT_MS = 8000;
// The JSON answer; undefined for 204; throws for anything else
export type LoadJson = (path: string, signal: AbortSignal) => Promise<unknown>;
const loadFromApi: LoadJson = async (path, signal) => {
export const loadFromApi: LoadJson = async (path, signal) => {
const response = await fetch(path, {
signal,
headers: { Accept: 'application/json' },
+99 -26
View File
@@ -1,4 +1,5 @@
import type { HeroContent } from './types';
import { t } from '../i18n/index.ts';
import type { HeroData, HeroSlide } from '../lib/hero.ts';
// Images
import hero1 from '../assets/hero-1.jpg';
@@ -10,32 +11,104 @@ import hero6 from '../assets/hero-6.jpg';
import hero7 from '../assets/hero-7.jpg';
import hero8 from '../assets/hero-8.jpg';
// Statische content tot de CMS-API er is. Daarna komt dit object uit de API.
const heroContent: HeroContent = {
title: 'Andrea Slop',
tagline: 'Lifestyle fotograaf · Huizen',
cta: { label: 'Lees meer', to: '/over-mij' },
// The hero the build bakes into the page: what the visitor sees until the CMS
// host (or the API) gives another one, and again when that fails. The same
// shape as what the CMS gives (lib/hero), so one component shows both. The
// photos have no wide/tall variants: the plain file is used everywhere.
// focus: where the subject is (0..1), used as object-position.
const slide = (
id: string,
src: string,
alt: string,
width: number,
height: number,
x: number,
y: number,
): HeroSlide => ({
id,
alt,
decorative: false,
image: { width, height, focus: { x, y }, src, variants: [] },
});
const heroContent: HeroData = {
display: 'slideshow',
title: t('hero.baked.title'),
tagline: t('hero.baked.tagline'),
buttons: [{ label: t('hero.baked.button'), target: '/over-mij' }],
slides: [
{ id: 'hero-8', src: hero8, alt: 'Zwangerschapsfoto in de duinen' },
{ id: 'hero-7', src: hero7, alt: 'Knusse newbornfoto met de familie' },
{
id: 'hero-1',
src: hero1,
alt: 'Lifestyle fotografie',
},
{
id: 'hero-2',
src: hero2,
alt: 'Zwangerschapsshoot in de buitenlucht',
},
{
id: 'hero-3',
src: hero3,
alt: 'Newbornshoot van een pasgeboren baby',
},
{ id: 'hero-4', src: hero4, alt: 'Spontaan portret buiten' },
{ id: 'hero-5', src: hero5, alt: 'Natuurlijke lifestylefoto' },
{ id: 'hero-6', src: hero6, alt: 'Portret in de natuur' },
slide(
'hero-8',
hero8,
t('hero.baked.alt.hero8'),
1600,
1067,
0.5,
0.55,
),
slide(
'hero-7',
hero7,
t('hero.baked.alt.hero7'),
1600,
1067,
0.45,
0.5,
),
slide(
'hero-1',
hero1,
t('hero.baked.alt.hero1'),
2560,
1702,
0.55,
0.6,
),
slide(
'hero-2',
hero2,
t('hero.baked.alt.hero2'),
1600,
1067,
0.45,
0.45,
),
slide(
'hero-3',
hero3,
t('hero.baked.alt.hero3'),
1600,
1067,
0.45,
0.4,
),
slide(
'hero-4',
hero4,
t('hero.baked.alt.hero4'),
2048,
1362,
0.45,
0.35,
),
slide(
'hero-5',
hero5,
t('hero.baked.alt.hero5'),
1600,
1067,
0.5,
0.55,
),
slide(
'hero-6',
hero6,
t('hero.baked.alt.hero6'),
2048,
1362,
0.5,
0.35,
),
],
};
-20
View File
@@ -363,23 +363,3 @@ export interface ShootPageContent {
offer: { eyebrow: string; title: string };
closing: { title: string; lead: RichText; buttonLabel: string };
}
export interface HeroSlide {
id: string;
src: string;
alt: string;
}
export interface HeroCta {
label: string;
to: string;
}
export interface HeroContent {
title: string;
// Klein label in hoofdletters boven de titel: wat en waar, voor bezoekers
// en zoekmachines (bv. "Lifestyle fotograaf · Huizen")
tagline: string;
cta: HeroCta;
slides: HeroSlide[];
}
+1
View File
@@ -88,6 +88,7 @@ describe('nl.json', () => {
expect(Object.keys(nl)).toEqual([
'common',
'site',
'hero',
'home',
'about',
'contact',
+27
View File
@@ -121,6 +121,33 @@
"instagramHandle": "@andreaslopfotografie"
}
},
"hero": {
"ariaLabel": "Uitgelicht werk",
"slideLabel": "{position} van {count}",
"announcement": "Foto {position} van {count}: {alt}",
"announcementPlain": "Foto {position} van {count}",
"paused": "Diavoorstelling gepauzeerd",
"playing": "Diavoorstelling speelt weer af",
"play": "Diavoorstelling afspelen",
"pause": "Diavoorstelling pauzeren",
"prev": "Vorige foto",
"next": "Volgende foto",
"baked": {
"title": "Andrea Slop",
"tagline": "Lifestyle fotograaf · Huizen",
"button": "Lees meer",
"alt": {
"hero8": "Zwangerschapsfoto in de duinen",
"hero7": "Knusse newbornfoto met de familie",
"hero1": "Lifestyle fotografie",
"hero2": "Zwangerschapsshoot in de buitenlucht",
"hero3": "Newbornshoot van een pasgeboren baby",
"hero4": "Spontaan portret buiten",
"hero5": "Natuurlijke lifestylefoto",
"hero6": "Portret in de natuur"
}
}
},
"home": {
"intro": {
"title": "Lifestyle fotografie",
+7
View File
@@ -43,6 +43,13 @@ describe('parseCmsData', () => {
});
});
it('passes the hero answer on unchecked', () => {
expect(
parseCmsData(JSON.stringify({ hero: { title: 'T' } }))?.hero,
).toEqual({ title: 'T' });
expect(parseCmsData('{}')?.hero).toBeUndefined();
});
it('falls back to production for an address that is not an origin', () => {
expect(
parseCmsData(JSON.stringify({ siteUrl: 'ftp://x' }))?.siteUrl,
+4
View File
@@ -25,6 +25,9 @@ export interface CmsData {
offerings?: unknown;
// undefined: not in the block; null: no active banner
banners?: { top?: unknown; bottom?: unknown };
// The answer of GET /api/v1/hero, not yet checked (lib/hero mapHero);
// undefined: not in the block
hero?: unknown;
}
const isObject = (value: unknown): value is Record<string, unknown> =>
@@ -50,6 +53,7 @@ export function parseCmsData(text: string | null | undefined): CmsData | null {
: undefined,
offerings: Array.isArray(raw.offerings) ? raw.offerings : undefined,
banners,
hero: raw.hero,
};
}
+11 -6
View File
@@ -19,9 +19,14 @@ const PORTRAIT = '(orientation: portrait)';
const LANDSCAPE = '(orientation: landscape)';
const SIZES = '100vw';
const srcsetOf = (variants: HeroImageVariant[], ratio: string): string =>
// The srcset of one ratio and format ("tall" or "wide"; WebP unless said)
export const variantSrcset = (
variants: HeroImageVariant[],
ratio: string,
type = 'image/webp',
): string =>
variants
.filter((v) => v.ratio === ratio && v.type === 'image/webp')
.filter((v) => v.ratio === ratio && v.type === type)
.sort((a, b) => a.width - b.width)
.map((v) => `${escapeHtml(v.url)} ${v.width}w`)
.join(', ');
@@ -37,8 +42,8 @@ const focusStyle = (slide: HeroSlide): string => {
function pictureHtml(slide: HeroSlide): string {
const { image } = slide;
const tall = srcsetOf(image.variants, 'tall');
const wide = srcsetOf(image.variants, 'wide');
const tall = variantSrcset(image.variants, 'tall');
const wide = variantSrcset(image.variants, 'wide');
const source = tall
? `<source media="${PORTRAIT}" srcset="${tall}" sizes="${SIZES}" type="image/webp">`
: '';
@@ -83,8 +88,8 @@ export function heroHtml(hero: HeroData | null): string {
export function heroPreloadHtml(hero: HeroData | null): string {
if (!hero) return '';
const { image } = hero.slides[0];
const tall = srcsetOf(image.variants, 'tall');
const wide = srcsetOf(image.variants, 'wide');
const tall = variantSrcset(image.variants, 'tall');
const wide = variantSrcset(image.variants, 'wide');
const link = (target: string, media: string): string =>
`<link rel="preload" as="image" ${target}` +
`${media ? ` media="${media}"` : ''} fetchpriority="high">`;
+71
View File
@@ -28,6 +28,77 @@ const config = defineConfig({
'[tabindex="-1"]:focus': {
outline: 'none',
},
// The hero as the page first shows it: the plain HTML between the CMS
// markers (lib/heroHtml, components/Hero). Looks like the slider's first
// frame: the photo fills the hero, title and buttons are centred over
// it, the scrim (a later sibling) sits between them.
'[data-cms-region="HERO-HTML"]': {
position: 'absolute',
inset: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
color: 'white',
pt: 'header',
px: 'gutter',
},
'.cms-hero-picture': {
position: 'absolute',
inset: 0,
zIndex: 0,
display: 'block',
},
'.cms-hero-image': {
display: 'block',
width: '100%',
height: '100%',
objectFit: 'cover',
},
'.cms-hero-title': {
position: 'relative',
zIndex: 1,
margin: 0,
marginBottom: 9,
fontFamily: 'heading',
// Same as the Heading component the slider uses
fontWeight: '500',
letterSpacing: '0.2px',
color: 'white',
},
'.cms-hero-tagline': {
display: 'block',
marginBottom: 4,
fontFamily: 'body',
textStyle: 'eyebrow',
lineHeight: '1.5',
color: 'white/80',
},
'.cms-hero-name': { display: 'block', textStyle: 'display' },
'.cms-hero-buttons': {
position: 'relative',
zIndex: 1,
margin: 0,
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
gap: 4,
},
'.cms-hero-button': {
display: 'inline-flex',
alignItems: 'center',
gap: 3,
px: '2.4rem',
py: '1.05rem',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: 'white/70',
color: 'white',
textStyle: 'eyebrow',
fontWeight: '400',
textDecoration: 'none',
},
// The plain HTML between the CMS markers (components/CmsRegion): what
// the CMS host writes, shown until the styled cards take over after
// hydration. Looks like the cards (white, hairline border, centred),