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
+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;
}