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` |
| 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`) |
| 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`) |
+135 -182
View File
@@ -1,15 +1,6 @@
import { useState } from 'react';
import {
Box,
chakra,
Container,
Heading,
Image,
VisuallyHidden,
} from '@chakra-ui/react';
import CmsRegion from '../CmsRegion/CmsRegion';
import { useEffect, useRef, useState } from 'react';
import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
import HeroArrows from './HeroArrows';
import HeroButton from './HeroButton';
import HeroPauseButton from './HeroPauseButton';
import HeroSocials from './HeroSocials';
import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider';
@@ -17,6 +8,7 @@ import useHero from './useHero';
import type { SocialLink } from '@/content/types';
import useHydrated from '@/hooks/useHydrated';
import { t } from '@/i18n';
import { regionMarkers } from '@/lib/cmsHtml';
import type { HeroData, HeroSlide } from '@/lib/hero';
import { heroHtml, variantSrcset } from '@/lib/heroHtml';
import { slidesToLoad } from '@/lib/slidesToLoad';
@@ -51,69 +43,44 @@ type HeroProps = {
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.
// The hero of the homepage. The plain HTML between the CMS markers (first
// photo, title, buttons, styled by .cms-hero-* in the theme) is what the
// 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) {
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) {
const { hero, regionHero } = useHero(content);
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>
<HeroFrame
content={hero}
regionHtml={heroHtml(regionHero)}
socials={socials}
hydrated={useHydrated()}
/>
);
}
// 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)
// One photo after the first: a picture with a source for portrait screens
// and AVIF where there is one (the first photo 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) => ({
const tall = ['image/avif', 'image/webp'].map((type) => ({
type,
srcset: variantSrcset(image.variants, 'tall', type),
}));
const wide = variantSrcset(image.variants, 'wide');
const wideAvif = first
? ''
: variantSrcset(image.variants, 'wide', 'image/avif');
const wideAvif = variantSrcset(image.variants, 'wide', 'image/avif');
return (
<chakra.picture display="block" w="100%" h="100%">
{tall.map(
@@ -138,9 +105,6 @@ function SlidePicture({
width={image.width}
height={image.height}
alt={slide.alt}
fetchPriority={first ? 'high' : undefined}
onLoad={onLoaded}
onError={onLoaded}
w="100%"
h="100%"
objectFit="cover"
@@ -152,9 +116,11 @@ function SlidePicture({
);
}
function HeroSlider({ content, socials }: HeroProps) {
const { title, tagline, buttons, slides, display } = content;
const single = display === 'single';
type FrameProps = HeroProps & { regionHtml: string; hydrated: boolean };
function HeroFrame({ content, socials, regionHtml, hydrated }: FrameProps) {
const { slides, display } = content;
const shown = display === 'single' ? slides.slice(0, 1) : slides;
const {
active,
announcement,
@@ -167,25 +133,54 @@ function HeroSlider({ content, socials }: HeroProps) {
prev,
advance,
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.
// 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.
// Verder weg laden we pas als de slider in de buurt komt (BR-HERO-01).
const [firstPainted, setFirstPainted] = useState(false);
const onFirstLoaded = () =>
requestAnimationFrame(() =>
requestAnimationFrame(() => setFirstPainted(true)),
);
const shown = single ? slides.slice(0, 1) : slides;
// 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(() => setFirstPainted(true)),
);
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 current = shown[active];
return (
<Box
as="section"
ref={section}
aria-label={t('hero.ariaLabel')}
aria-roledescription="carousel"
aria-roledescription={hydrated ? 'carousel' : undefined}
suppressHydrationWarning
position="relative"
// Eigen stacking context: de z-indexen hieronder gelden alleen
// binnen de hero en botsen niet met de navigatiebalk.
@@ -195,134 +190,92 @@ function HeroSlider({ content, socials }: HeroProps) {
overflow="hidden"
bg="ink"
touchAction="pan-y"
{...handlers}
{...(hydrated ? handlers : {})}
>
{/* Slides: crossfade met een langzame inzoom */}
<Box position="absolute" inset={0}>
{shown.map((slide, i) => (
<Box
key={slide.id}
role="group"
aria-roledescription="slide"
aria-label={t('hero.slideLabel', {
position: i + 1,
count: shown.length,
})}
aria-hidden={i !== active}
position="absolute"
inset={0}
opacity={i === active ? 1 : 0}
transitionProperty="opacity"
transitionDuration="fade"
transitionTimingFunction="smooth"
>
{loaded.includes(i) && (
<SlidePicture
slide={slide}
first={i === 0}
visible={i === active}
scaled={reducedMotion}
onLoaded={
firstPainted ? undefined : onFirstLoaded
}
/>
)}
</Box>
))}
</Box>
{/* Eerste foto, titel en knoppen: gewone HTML tussen de CMS-markers.
Dezelfde tekst als bij het prerenderen, dus React laat hem staan. */}
<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
key={slide.id}
role="group"
aria-roledescription="slide"
aria-label={t('hero.slideLabel', {
position: i + 1,
count: shown.length,
})}
aria-hidden={i !== active}
position="absolute"
inset={0}
opacity={i === active ? 1 : 0}
transitionProperty="opacity"
transitionDuration="fade"
transitionTimingFunction="smooth"
>
{loaded.includes(i) && (
<SlidePicture
slide={slide}
visible={i === active}
scaled={reducedMotion}
/>
)}
</Box>
),
)}
</Box>
)}
{/* Scrim */}
<Box aria-hidden position="absolute" inset={0} bgGradient="scrim" />
<Container
position="relative"
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} />}
{hydrated && shown.length > 1 && (
<HeroArrows onPrev={prev} onNext={next} />
)}
<HeroSocials socials={socials} />
{autoplay && shown.length > 1 && (
{hydrated && autoplay && shown.length > 1 && (
<HeroPauseButton stopped={stopped} onToggle={toggleStopped} />
)}
{/* Meldt een wissel of pauze door de bezoeker; staat er altijd, want een
live-gebied moet al bestaan voordat de tekst verandert. Leeg na
een automatische wissel, zodat er geen oude melding blijft. */}
<VisuallyHidden
aria-live="polite"
aria-atomic="true"
data-testid="hero-announcement"
>
{announcementText(
announcement,
t(
current.alt
? 'hero.announcement'
: 'hero.announcementPlain',
{
position: active + 1,
count: shown.length,
alt: current.alt,
},
),
)}
</VisuallyHidden>
{hydrated && (
<VisuallyHidden
aria-live="polite"
aria-atomic="true"
data-testid="hero-announcement"
>
{announcementText(
announcement,
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 && shown.length > 1 && (
{hydrated && autoplay && shown.length > 1 && (
<Box
key={active}
aria-hidden
+1 -1
View File
@@ -18,7 +18,7 @@ const answer = (title: string) => ({
});
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) => {
+9 -2
View File
@@ -18,7 +18,7 @@ const TIMEOUT_MS = 8000;
export default function useHero(
baked: HeroData,
load: LoadJson = loadFromApi,
): HeroData {
): { hero: HeroData; regionHero: HeroData } {
const hydrated = useHydrated();
const fromBlock = useMemo(() => {
const block = hydrated ? hostCmsData(document) : null;
@@ -45,5 +45,12 @@ export default function useHero(
};
}, [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,
};
}