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:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user