Files
AndreaSlopFotografie/web/src/components/Hero/Hero.tsx
T
SluijsensandClaude Sonnet 5.5 8050072ce5
Continuous Integration / check (pull_request) Successful in 1m57s
Continuous Integration / build-test (pull_request) Skipped
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / lighthouse (pull_request) Successful in 9m0s
Continuous Integration / deploy-production (pull_request) Skipped
Hero: slow zoom on the first photo without replacing the plain HTML
The plain HTML is painted at scale 1.06 and the slider zooms it out to 1
after hydration, like the other photos: same first frame (no CLS), and the
LCP does not wait for hydration. Assumptions 15 and 16 recorded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 10:31:22 +01:00

309 lines
11 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
import HeroArrows from './HeroArrows';
import HeroPauseButton from './HeroPauseButton';
import HeroSocials from './HeroSocials';
import useHeroSlider, { type HeroAnnouncement } from './useHeroSlider';
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';
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 t('hero.paused');
case 'playing':
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: HeroData;
socials: SocialLink[];
};
// 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, regionHero } = useHero(content);
return (
<HeroFrame
content={hero}
regionHtml={heroHtml(regionHero)}
socials={socials}
hydrated={useHydrated()}
/>
);
}
// 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,
visible,
scaled,
}: {
slide: HeroSlide;
visible: boolean;
scaled: boolean;
}) {
const { image } = slide;
const tall = ['image/avif', 'image/webp'].map((type) => ({
type,
srcset: variantSrcset(image.variants, 'tall', type),
}));
const wide = variantSrcset(image.variants, 'wide');
const wideAvif = 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}
w="100%"
h="100%"
objectFit="cover"
objectPosition={objectPosition(slide)}
transform={scaled || visible ? 'scale(1)' : 'scale(1.06)'}
transition="transform 9s linear"
/>
</chakra.picture>
);
}
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,
reducedMotion,
autoplay,
paused,
stopped,
toggleStopped,
next,
prev,
advance,
handlers,
} = useHeroSlider(shown.length);
const section = useRef<HTMLElement>(null);
// De slides liggen op elkaar in beeld, dus loading="lazy" stelt niets uit.
// 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);
// 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, and it zooms (data-zoom, see .cms-hero-image) while it is the
// active one
useEffect(() => {
const picture = section.current?.querySelector('.cms-hero-picture');
if (active === 0) {
picture?.removeAttribute('aria-hidden');
picture?.setAttribute('data-zoom', '');
} else {
picture?.setAttribute('aria-hidden', 'true');
picture?.removeAttribute('data-zoom');
}
}, [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={hydrated ? 'carousel' : undefined}
suppressHydrationWarning
position="relative"
// Eigen stacking context: de z-indexen hieronder gelden alleen
// binnen de hero en botsen niet met de navigatiebalk.
isolation="isolate"
h="100svh"
minH="560px"
overflow="hidden"
bg="ink"
touchAction="pan-y"
{...(hydrated ? handlers : {})}
>
{/* 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" />
{hydrated && shown.length > 1 && (
<HeroArrows onPrev={prev} onNext={next} />
)}
<HeroSocials socials={socials} />
{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. */}
{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. */}
{hydrated && autoplay && shown.length > 1 && (
<Box
key={active}
aria-hidden
data-testid="hero-progress"
data-requires-js
data-state={paused ? 'paused' : 'running'}
position="absolute"
left={0}
bottom={0}
zIndex={2}
h="2px"
bg="white"
animationName="expand-width"
animationDuration={SLIDE_DURATION}
animationTimingFunction="linear"
animationFillMode="forwards"
animationPlayState={paused ? 'paused' : 'running'}
css={{ '--width': '100%' }}
onAnimationEnd={advance}
/>
)}
</Box>
);
}