Builds the markers, data block and stand-in host for the CMS host injection

The pages carry the CMS markers (data block, list regions, JSON-LD price,
inline price); PackagesProvider reads the host's data block after hydration
and asks the API only when there is none; the site address comes from the
block. A stand-in for the host (config/hostInjector.ts, --cms-data in the
preview server) and browser tests check the behaviour with different data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:21:08 +01:00
co-authored by Claude Sonnet 5.5
parent 16027f5688
commit bf21b6f690
26 changed files with 1207 additions and 70 deletions
@@ -0,0 +1,24 @@
import packages, { banner, topBanner } from '@/content/packages';
import { bakedCmsData, CMS_DATA_ID, scriptJson } from '@/lib/cmsData';
import { siteUrl } from '@/seo';
// The data block of the page, in the root document: <!--CMS:DATA--> followed
// by the JSON of the packages and banners the build baked. The CMS host
// replaces the pair with the current data; the browser reads it after
// hydration (PackagesProvider) and the address from it before (client.tsx).
// Hidden and never hydrated: the host's block differs from the baked one.
export default function CmsDataIsland() {
const json = scriptJson(bakedCmsData(siteUrl, packages, banner, topBanner));
return (
<div
hidden
data-cms-island
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html:
'<!--CMS:DATA-->' +
`<script type="application/json" id="${CMS_DATA_ID}">${json}</script>`,
}}
/>
);
}
@@ -0,0 +1,51 @@
import { renderToString } from 'react-dom/server';
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { renderWithProviders } from '@/test/renderWithProviders';
import CmsDataIsland from './CmsDataIsland';
import CmsRegion from './CmsRegion';
describe('CmsRegion', () => {
it('is plain HTML between two markers on the server', () => {
const html = renderToString(
<CmsRegion name="OFFERINGS-HTML" html="<ul><li>x</li></ul>">
<p>gestijld</p>
</CmsRegion>,
);
expect(html).toContain(
'<!--CMS:OFFERINGS-HTML--><ul><li>x</li></ul><!--/CMS:OFFERINGS-HTML-->',
);
expect(html).not.toContain('gestijld');
});
it('shows the styled content once it runs in the browser', async () => {
await renderWithProviders(
<CmsRegion name="OFFERINGS-HTML" html="<ul></ul>">
<p>gestijld</p>
</CmsRegion>,
);
expect(screen.getByText('gestijld')).toBeInTheDocument();
});
});
describe('CmsDataIsland', () => {
it('writes the marker and the baked block, hidden, with the build as source', () => {
const html = renderToString(<CmsDataIsland />);
expect(html).toMatch(
/<div hidden="" data-cms-island="true"><!--CMS:DATA--><script type="application\/json" id="cms-data">\{/,
);
const json = /id="cms-data">(.*?)<\/script>/.exec(html)?.[1] ?? '';
const data = JSON.parse(json) as {
source: string;
siteUrl: string;
offerings: unknown[];
banners: object;
};
expect(data.source).toBe('build');
expect(data.siteUrl).toBe('https://andreaslop.nl');
expect(data.offerings.length).toBeGreaterThan(0);
expect(Object.keys(data.banners)).toEqual(['top', 'bottom']);
// Nothing in it can end the script element
expect(json).not.toMatch(/[<>&]/);
});
});
@@ -0,0 +1,32 @@
import type { ReactNode } from 'react';
import useHydrated from '@/hooks/useHydrated';
import { regionMarkers } from '@/lib/cmsHtml';
type CmsRegionProps = {
// Marker name, for example "OFFERINGS-HTML": <!--CMS:OFFERINGS-HTML-->
name: string;
// The plain HTML of the data the page was built with (lib/cmsHtml); the
// CMS host replaces it with the same markup from the current data
html: string;
// What the visitor gets once the page has hydrated: the styled
// components, built from the current data
children: ReactNode;
};
// A part of the page that the CMS host may rewrite before it sends the HTML
// (packages, banners). Until hydration it is plain HTML between two marker
// comments, which React leaves alone (a host that wrote different data would
// otherwise cause a hydration mismatch). After hydration the styled
// components replace it. React cannot write comments, so the markers go in
// through dangerouslySetInnerHTML; the html is escaped by lib/cmsHtml and
// never contains anything but what that escapes.
export default function CmsRegion({ name, html, children }: CmsRegionProps) {
if (useHydrated()) return <>{children}</>;
return (
<div
data-cms-region={name}
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: regionMarkers(name, html) }}
/>
);
}
@@ -56,7 +56,16 @@ export default function PackageBlock({
color="accent.deep"
mt={4}
>
{pkg ? formatPrice(pkg.price) : onRequest.price}
{pkg ? (
// CMS data: the host rewrites the text of this span in the
// HTML it sends, so a different text is not a hydration
// error
<span data-cms-price={pkg.id} suppressHydrationWarning>
{formatPrice(pkg.price)}
</span>
) : (
onRequest.price
)}
</Text>
{pkg ? (
<Box as="ul" role="list" listStyle="none" m={0} p={0} mt={5}>
@@ -191,3 +191,67 @@ describe('PackagesProvider', () => {
expect(signals.every((signal) => signal.aborted)).toBe(true);
});
});
describe('the data block of the CMS host', () => {
const putBlock = (json: string) => {
const script = document.createElement('script');
script.type = 'application/json';
script.id = 'cms-data';
script.textContent = json;
document.body.append(script);
return () => script.remove();
};
it('is shown without asking the API', async () => {
const remove = putBlock(
JSON.stringify({
offerings: card('€ 333'),
banners: { top: { text: 'Van de host' }, bottom: null },
}),
);
try {
const load = fake({ offerings: card('€ 999') });
await show(load);
await waitFor(() =>
expect(screen.getByText('Newborn 333')).toBeInTheDocument(),
);
expect(screen.getByTestId('top')).toHaveTextContent('Van de host');
expect(screen.getByTestId('banner')).toHaveTextContent(
'geen banner',
);
expect(load).not.toHaveBeenCalled();
} finally {
remove();
}
});
it('is not trusted when it is the one the build baked: the API is asked', async () => {
const remove = putBlock(
JSON.stringify({ source: 'build', offerings: card('€ 111') }),
);
try {
const load = fake({ offerings: card('€ 222') });
await show(load);
await waitFor(() =>
expect(screen.getByText('Newborn 222')).toBeInTheDocument(),
);
expect(load).toHaveBeenCalled();
} finally {
remove();
}
});
it('keeps the baked data for a block that cannot be read', async () => {
const remove = putBlock('niet json');
try {
await show(fake({ offerings: undefined }));
expect(
screen.getByText(
`${bakedPackages[0].name} ${bakedPackages[0].price}`,
),
).toBeInTheDocument();
} finally {
remove();
}
});
});
@@ -9,6 +9,8 @@ import type {
PricingPackage,
PricingTopBanner,
} from '@/content/types';
import useHydrated from '@/hooks/useHydrated';
import { hostCmsData, liveFromData } from '@/lib/cmsData';
import { mapBanner, mapOfferings, mapTopBanner } from '@/lib/offerings';
// The shoot packages and the announcement banner the pages show. The build
@@ -81,8 +83,19 @@ export default function PackagesProvider({
load = loadFromApi,
}: PackagesProviderProps) {
const [live, setLive] = useState<Live>(baked);
// The data block the CMS host wrote into the page, read in the first render
// after hydration (not before: the HTML the server rendered used the baked
// data, and hydration must see the same). Without a block (preview, tests,
// a host that does not inject) the page asks the CMS instead, below.
const hydrated = useHydrated();
const fromBlock = useMemo(
() => (hydrated ? liveFromData(hostCmsData(document)) : null),
[hydrated],
);
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);
@@ -130,7 +143,10 @@ export default function PackagesProvider({
};
}, [load]);
const value = useMemo(() => live, [live]);
const value = useMemo(
() => (fromBlock ? { ...live, ...fromBlock } : live),
[live, fromBlock],
);
return (
<LiveContext.Provider value={value}>{children}</LiveContext.Provider>
);
@@ -2,13 +2,36 @@ import { jsonLdScript } from '@/seo';
type StructuredDataProps = {
data: unknown;
// The package whose price is in this data: marks the block for the CMS
// host, which keeps offers.price current (<!--CMS:OFFER-JSON-LD-->)
offerSlug?: string;
};
// One object of structured data as an ld+json script in the page. This is
// the only place the shoot pages use dangerouslySetInnerHTML, and only with
// jsonLdScript's output: it escapes <, > and &, so content can never close
// the script element (SECURITY-04, SECURITY-11).
export default function StructuredData({ data }: StructuredDataProps) {
export default function StructuredData({
data,
offerSlug,
}: StructuredDataProps) {
if (offerSlug !== undefined) {
// The marker has to sit directly before the script, and React cannot
// write comments, so both go in through one hidden wrapper. The slug is
// checked: it comes from our own routes, never from the CMS.
const slug = /^[a-z0-9-]+$/.test(offerSlug) ? offerSlug : '';
return (
<div
hidden
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html:
`<!--CMS:OFFER-JSON-LD slug="${slug}"-->` +
`<script type="application/ld+json">${jsonLdScript(data)}</script>`,
}}
/>
);
}
return (
<script
type="application/ld+json"
+49 -32
View File
@@ -1,4 +1,5 @@
import { Box, Flex } from '@chakra-ui/react';
import CmsRegion from '@/components/CmsRegion/CmsRegion';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import PageSection from '@/components/PageSection/PageSection';
import Reveal from '@/components/Reveal/Reveal';
@@ -9,6 +10,7 @@ import type {
PricingPackage,
PricingTopBanner,
} from '@/content/types';
import { bannerHtml, offeringsHtml } from '@/lib/cmsHtml';
import { visiblePackages } from '@/lib/visiblePackages';
import PriceBanner from './PriceBanner';
import PriceCard from './PriceCard';
@@ -77,44 +79,59 @@ export default function Pricing({
lead={content.lead}
/>
</Reveal>
{topBanner && (
<Reveal>
<PriceTopBar banner={topBanner} />
</Reveal>
)}
{/* Packages and banners are CMS data: the CMS host may rewrite
them in the HTML it sends (CmsRegion), so they are plain
HTML until the page has hydrated */}
<CmsRegion
name="BANNER-TOP-HTML"
html={bannerHtml(topBanner ?? null)}
>
{topBanner && (
<Reveal>
<PriceTopBar banner={topBanner} />
</Reveal>
)}
</CmsRegion>
{/* Wrapping flex, not a grid: a grid leaves the last row at
the left. Every card is exactly a third of the row minus
the gaps, so the cards of a full row line up and an
incomplete last row is centred. */}
<Flex
direction={{ base: 'column', lg: 'row' }}
wrap={{ base: 'nowrap', lg: 'wrap' }}
justify="center"
gap="gridGap"
maxW={{ base: '460px', lg: 'none' }}
mx="auto"
<CmsRegion name="OFFERINGS-HTML" html={offeringsHtml(shown)}>
<Flex
direction={{ base: 'column', lg: 'row' }}
wrap={{ base: 'nowrap', lg: 'wrap' }}
justify="center"
gap="gridGap"
maxW={{ base: '460px', lg: 'none' }}
mx="auto"
>
{shown.map((pkg, index) => (
<Reveal
key={pkg.id}
delay={index * STAGGER}
w={{
base: '100%',
lg: 'calc((100% - 2 * {spacing.gridGap}) / 3)',
}}
>
<PriceCard pkg={pkg} />
</Reveal>
))}
</Flex>
</CmsRegion>
<CmsRegion
name="BANNER-BOTTOM-HTML"
html={bannerHtml(banner ?? null)}
>
{shown.map((pkg, index) => (
<Reveal
key={pkg.id}
delay={index * STAGGER}
w={{
base: '100%',
lg: 'calc((100% - 2 * {spacing.gridGap}) / 3)',
}}
>
<PriceCard pkg={pkg} />
{banner && (
<Reveal>
<PriceBanner
banner={banner}
decoration={content.decorations[0]}
/>
</Reveal>
))}
</Flex>
{banner && (
<Reveal>
<PriceBanner
banner={banner}
decoration={content.decorations[0]}
/>
</Reveal>
)}
)}
</CmsRegion>
</Box>
</PageSection>
);