Hero uit het CMS met ingebakken terugval #21

Merged
Sluijsens merged 7 commits from feature/hero-module into master 2026-11-17 10:26:39 +01:00
4 changed files with 146 additions and 185 deletions
Showing only changes of commit 3d7bb2d4a6 - Show all commits
@@ -14,3 +14,4 @@ Written while Bryan was away; he decides later. Each point: question, assumption
| 8 | Without a host block the site asks `/api/v1/hero` (8 s time-out) | Yes, like packages and banners | Remove the call: baked only | `web/src/components/Hero/useHero.ts` | | 8 | Without a host block the site asks `/api/v1/hero` (8 s time-out) | Yes, like packages and banners | Remove the call: baked only | `web/src/components/Hero/useHero.ts` |
| 9 | Style of the plain hero before hydration | Matches the slider's first frame (checked by screenshot at 1280 and 390 px) | Adjust CSS | `.cms-hero-*` in `web/src/theme.ts` | | 9 | Style of the plain hero before hydration | Matches the slider's first frame (checked by screenshot at 1280 and 390 px) | Adjust CSS | `.cms-hero-*` in `web/src/theme.ts` |
| 10 | AVIF for slides 2..n only | As agreed with the CMS session | Add AVIF to the first photo and its preload (then two fetches) | `Hero.tsx` (`SlidePicture`) | | 10 | AVIF for slides 2..n only | As agreed with the CMS session | Add AVIF to the first photo and its preload (then two fetches) | `Hero.tsx` (`SlidePicture`) |
| 11 | The first photo, title and buttons stay the plain HTML after hydration (never replaced); the slider adds the other photos on top | Yes: replacing the nodes at hydration risks a late LCP. Side effect: the first photo has no slow zoom and is not in a role=group slide | Go back to a full slider render (one component), accepting the DOM replacement | `Hero.tsx` (`HeroFrame`), `useHero.ts` (`regionHero`) |
+87 -134
View File
@@ -1,15 +1,6 @@
import { useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
Box,
chakra,
Container,
Heading,
Image,
VisuallyHidden,
} from '@chakra-ui/react';
import CmsRegion from '../CmsRegion/CmsRegion';
import HeroArrows from './HeroArrows'; import HeroArrows from './HeroArrows';
import HeroButton from './HeroButton';
import HeroPauseButton from './HeroPauseButton'; import HeroPauseButton from './HeroPauseButton';
import HeroSocials from './HeroSocials'; import HeroSocials from './HeroSocials';
import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider'; import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider';
@@ -17,6 +8,7 @@ import useHero from './useHero';
import type { SocialLink } from '@/content/types'; import type { SocialLink } from '@/content/types';
import useHydrated from '@/hooks/useHydrated'; import useHydrated from '@/hooks/useHydrated';
import { t } from '@/i18n'; import { t } from '@/i18n';
import { regionMarkers } from '@/lib/cmsHtml';
import type { HeroData, HeroSlide } from '@/lib/hero'; import type { HeroData, HeroSlide } from '@/lib/hero';
import { heroHtml, variantSrcset } from '@/lib/heroHtml'; import { heroHtml, variantSrcset } from '@/lib/heroHtml';
import { slidesToLoad } from '@/lib/slidesToLoad'; import { slidesToLoad } from '@/lib/slidesToLoad';
@@ -51,69 +43,44 @@ type HeroProps = {
socials: SocialLink[]; socials: SocialLink[];
}; };
// The hero of the homepage. Until hydration it is the plain HTML between the // The hero of the homepage. The plain HTML between the CMS markers (first
// CMS markers (what the host may rewrite); after hydration the slider shows // photo, title, buttons, styled by .cms-hero-* in the theme) is what the
// the data of the host, the API or the build, whichever came first. // browser paints first and it is never replaced: React leaves it alone, so the
// photo the browser already has stays the largest paint of the page (replacing
// it at hydration made the LCP wait for the hydration). After hydration the
// slider is laid around it: the other photos on top of the first, the arrows,
// the pause button and so on, from the hero of the host, the API or the build.
export default function Hero({ content, socials }: HeroProps) { export default function Hero({ content, socials }: HeroProps) {
const hero = useHero(content); const { hero, regionHero } = 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 ( return (
<Box <HeroFrame
as="section" content={hero}
aria-label={t('hero.ariaLabel')} regionHtml={heroHtml(regionHero)}
position="relative" socials={socials}
isolation="isolate" hydrated={useHydrated()}
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 // One photo after the first: a picture with a source for portrait screens
// slides after the first, AVIF as well (the first one is only WebP, because // and AVIF where there is one (the first photo is only WebP, because the
// the browser preloads exactly that file) // browser preloads exactly that file)
function SlidePicture({ function SlidePicture({
slide, slide,
first,
visible, visible,
scaled, scaled,
onLoaded,
}: { }: {
slide: HeroSlide; slide: HeroSlide;
first: boolean;
visible: boolean; visible: boolean;
scaled: boolean; scaled: boolean;
onLoaded?: () => void;
}) { }) {
const { image } = slide; const { image } = slide;
const formats = first ? ['image/webp'] : ['image/avif', 'image/webp']; const tall = ['image/avif', 'image/webp'].map((type) => ({
const tall = formats.map((type) => ({
type, type,
srcset: variantSrcset(image.variants, 'tall', type), srcset: variantSrcset(image.variants, 'tall', type),
})); }));
const wide = variantSrcset(image.variants, 'wide'); const wide = variantSrcset(image.variants, 'wide');
const wideAvif = first const wideAvif = variantSrcset(image.variants, 'wide', 'image/avif');
? ''
: variantSrcset(image.variants, 'wide', 'image/avif');
return ( return (
<chakra.picture display="block" w="100%" h="100%"> <chakra.picture display="block" w="100%" h="100%">
{tall.map( {tall.map(
@@ -138,9 +105,6 @@ function SlidePicture({
width={image.width} width={image.width}
height={image.height} height={image.height}
alt={slide.alt} alt={slide.alt}
fetchPriority={first ? 'high' : undefined}
onLoad={onLoaded}
onError={onLoaded}
w="100%" w="100%"
h="100%" h="100%"
objectFit="cover" objectFit="cover"
@@ -152,9 +116,11 @@ function SlidePicture({
); );
} }
function HeroSlider({ content, socials }: HeroProps) { type FrameProps = HeroProps & { regionHtml: string; hydrated: boolean };
const { title, tagline, buttons, slides, display } = content;
const single = display === 'single'; function HeroFrame({ content, socials, regionHtml, hydrated }: FrameProps) {
const { slides, display } = content;
const shown = display === 'single' ? slides.slice(0, 1) : slides;
const { const {
active, active,
announcement, announcement,
@@ -167,25 +133,54 @@ function HeroSlider({ content, socials }: HeroProps) {
prev, prev,
advance, advance,
handlers, handlers,
} = useHeroSlider(single ? 1 : slides.length); } = useHeroSlider(shown.length);
const section = useRef<HTMLElement>(null);
// De slides liggen op elkaar in beeld, dus loading="lazy" stelt niets uit. // 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 // Eerst alleen de eerste foto; zodra die binnen en getekend is (twee
// frames later, dus na de eerste paint) ook de volgende en de vorige. // frames later, dus na de eerste paint) ook de volgende en de vorige.
// Verder weg laden we pas als de slider in de buurt komt (BR-HERO-01). // Verder weg laden we pas als de slider in de buurt komt (BR-HERO-01).
const [firstPainted, setFirstPainted] = useState(false); const [firstPainted, setFirstPainted] = useState(false);
const onFirstLoaded = () =>
// The first photo is part of the plain HTML, so React has no onLoad on it:
// listen to it here
useEffect(() => {
const image =
section.current?.querySelector<HTMLImageElement>('.cms-hero-image');
if (!image || firstPainted) return;
const painted = () =>
requestAnimationFrame(() => requestAnimationFrame(() =>
requestAnimationFrame(() => setFirstPainted(true)), requestAnimationFrame(() => setFirstPainted(true)),
); );
const shown = single ? slides.slice(0, 1) : slides; if (image.complete && image.naturalWidth > 0) {
painted();
return;
}
image.addEventListener('load', painted);
image.addEventListener('error', painted);
return () => {
image.removeEventListener('load', painted);
image.removeEventListener('error', painted);
};
}, [firstPainted]);
// The first photo is hidden from screen readers while another one is on
// top of it
useEffect(() => {
const picture = section.current?.querySelector('.cms-hero-picture');
if (active === 0) picture?.removeAttribute('aria-hidden');
else picture?.setAttribute('aria-hidden', 'true');
}, [active]);
const loaded = firstPainted ? slidesToLoad(active, shown.length) : [active]; const loaded = firstPainted ? slidesToLoad(active, shown.length) : [active];
const current = shown[active]; const current = shown[active];
return ( return (
<Box <Box
as="section" as="section"
ref={section}
aria-label={t('hero.ariaLabel')} aria-label={t('hero.ariaLabel')}
aria-roledescription="carousel" aria-roledescription={hydrated ? 'carousel' : undefined}
suppressHydrationWarning
position="relative" position="relative"
// Eigen stacking context: de z-indexen hieronder gelden alleen // Eigen stacking context: de z-indexen hieronder gelden alleen
// binnen de hero en botsen niet met de navigatiebalk. // binnen de hero en botsen niet met de navigatiebalk.
@@ -195,11 +190,24 @@ function HeroSlider({ content, socials }: HeroProps) {
overflow="hidden" overflow="hidden"
bg="ink" bg="ink"
touchAction="pan-y" touchAction="pan-y"
{...handlers} {...(hydrated ? handlers : {})}
> >
{/* Slides: crossfade met een langzame inzoom */} {/* Eerste foto, titel en knoppen: gewone HTML tussen de CMS-markers.
<Box position="absolute" inset={0}> Dezelfde tekst als bij het prerenderen, dus React laat hem staan. */}
{shown.map((slide, i) => ( <div
data-cms-region="HERO-HTML"
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: regionMarkers('HERO-HTML', regionHtml),
}}
/>
{/* De volgende slides liggen boven de eerste: crossfade met een
langzame inzoom */}
{hydrated && (
<Box position="absolute" inset={0} zIndex={0}>
{shown.map((slide, i) =>
i === 0 ? null : (
<Box <Box
key={slide.id} key={slide.id}
role="group" role="group"
@@ -219,87 +227,31 @@ function HeroSlider({ content, socials }: HeroProps) {
{loaded.includes(i) && ( {loaded.includes(i) && (
<SlidePicture <SlidePicture
slide={slide} slide={slide}
first={i === 0}
visible={i === active} visible={i === active}
scaled={reducedMotion} scaled={reducedMotion}
onLoaded={
firstPainted ? undefined : onFirstLoaded
}
/> />
)} )}
</Box> </Box>
))} ),
)}
</Box> </Box>
)}
{/* Scrim */} {/* Scrim */}
<Box aria-hidden position="absolute" inset={0} bgGradient="scrim" /> <Box aria-hidden position="absolute" inset={0} bgGradient="scrim" />
<Container {hydrated && shown.length > 1 && (
position="relative" <HeroArrows onPrev={prev} onNext={next} />
zIndex={1}
h="100%"
pt="header"
display="flex"
flexDirection="column"
alignItems="center"
justifyContent="center"
textAlign="center"
color="white"
>
{/* 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"
textStyle="display"
// Een nieuwe regel in de titel is een regelafbreking
whiteSpace="pre-line"
>
{title}
</chakra.span>
</Heading>
{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>
{shown.length > 1 && <HeroArrows onPrev={prev} onNext={next} />}
<HeroSocials socials={socials} /> <HeroSocials socials={socials} />
{autoplay && shown.length > 1 && ( {hydrated && autoplay && shown.length > 1 && (
<HeroPauseButton stopped={stopped} onToggle={toggleStopped} /> <HeroPauseButton stopped={stopped} onToggle={toggleStopped} />
)} )}
{/* Meldt een wissel of pauze door de bezoeker; staat er altijd, want een {/* Meldt een wissel of pauze door de bezoeker; staat er altijd, want een
live-gebied moet al bestaan voordat de tekst verandert. Leeg na live-gebied moet al bestaan voordat de tekst verandert. Leeg na
een automatische wissel, zodat er geen oude melding blijft. */} een automatische wissel, zodat er geen oude melding blijft. */}
{hydrated && (
<VisuallyHidden <VisuallyHidden
aria-live="polite" aria-live="polite"
aria-atomic="true" aria-atomic="true"
@@ -319,10 +271,11 @@ function HeroSlider({ content, socials }: HeroProps) {
), ),
)} )}
</VisuallyHidden> </VisuallyHidden>
)}
{/* Voortgangsbalk: als de animatie klaar is, schuift de slider door. {/* Voortgangsbalk: als de animatie klaar is, schuift de slider door.
Door de key start hij opnieuw bij elke slidewissel. */} Door de key start hij opnieuw bij elke slidewissel. */}
{autoplay && shown.length > 1 && ( {hydrated && autoplay && shown.length > 1 && (
<Box <Box
key={active} key={active}
aria-hidden aria-hidden
+1 -1
View File
@@ -18,7 +18,7 @@ const answer = (title: string) => ({
}); });
function Title({ load }: { load: LoadJson }) { function Title({ load }: { load: LoadJson }) {
return <p data-testid="title">{useHero(heroContent, load).title}</p>; return <p data-testid="title">{useHero(heroContent, load).hero.title}</p>;
} }
const block = (data: unknown) => { const block = (data: unknown) => {
+9 -2
View File
@@ -18,7 +18,7 @@ const TIMEOUT_MS = 8000;
export default function useHero( export default function useHero(
baked: HeroData, baked: HeroData,
load: LoadJson = loadFromApi, load: LoadJson = loadFromApi,
): HeroData { ): { hero: HeroData; regionHero: HeroData } {
const hydrated = useHydrated(); const hydrated = useHydrated();
const fromBlock = useMemo(() => { const fromBlock = useMemo(() => {
const block = hydrated ? hostCmsData(document) : null; const block = hydrated ? hostCmsData(document) : null;
@@ -45,5 +45,12 @@ export default function useHero(
}; };
}, [load]); }, [load]);
return fromBlock ?? fetched ?? baked; // regionHero is what the plain HTML region of the page holds: the baked
// hero, or the one the API gave. The block of the host does not count: the
// host wrote that region itself and it must not be written over (that
// would replace the photo the browser has painted).
return {
hero: fromBlock ?? fetched ?? baked,
regionHero: fetched ?? baked,
};
} }