Updates the packages and the banner live in the browser
The build still bakes the current packages and the active banner into the HTML. After hydration the page asks /api/v1/offerings and /api/v1/offerings/banner once and replaces what differs; errors and time-outs keep what was baked, and a 204 from the banner route hides the banner. The banner is now the OfferingBanner contract (title, text, optional link) instead of layout=banner. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import { act, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import bakedPackages from '@/content/packages';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import PackagesProvider, {
|
||||
useBanner,
|
||||
usePackages,
|
||||
type LoadJson,
|
||||
} from './PackagesProvider';
|
||||
|
||||
function Shown() {
|
||||
const banner = useBanner();
|
||||
return (
|
||||
<>
|
||||
<ul>
|
||||
{usePackages().map((pkg) => (
|
||||
<li key={pkg.id}>{`${pkg.name} ${pkg.price}`}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p data-testid="banner">{banner ? banner.title : 'geen banner'}</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const card = (price: string) => [
|
||||
{
|
||||
slug: 'newborn',
|
||||
title: 'Newborn',
|
||||
price,
|
||||
features: ['a'],
|
||||
displayOrder: 0,
|
||||
},
|
||||
];
|
||||
|
||||
// A fake CMS: one answer per path; a value, undefined (204) or an Error to
|
||||
// throw
|
||||
type Answers = { offerings?: unknown; banner?: unknown };
|
||||
const fake = (answers: Answers): LoadJson =>
|
||||
vi.fn(async (path: string) => {
|
||||
const answer = path.endsWith('/banner')
|
||||
? answers.banner
|
||||
: answers.offerings;
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
});
|
||||
|
||||
const show = async (load: LoadJson) => {
|
||||
const view = await renderWithProviders(
|
||||
<PackagesProvider load={load}>
|
||||
<Shown />
|
||||
</PackagesProvider>,
|
||||
);
|
||||
// Let both calls settle
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
return view;
|
||||
};
|
||||
|
||||
const items = () => screen.getAllByRole('listitem');
|
||||
|
||||
describe('PackagesProvider', () => {
|
||||
it('starts with the baked packages, also without a provider', async () => {
|
||||
await renderWithProviders(<Shown />);
|
||||
expect(items()).toHaveLength(bakedPackages.length);
|
||||
expect(screen.getByTestId('banner')).toHaveTextContent('geen banner');
|
||||
});
|
||||
|
||||
it('replaces the packages when the CMS answer differs', async () => {
|
||||
await show(fake({ offerings: card('€ 200'), banner: undefined }));
|
||||
await waitFor(() => expect(items()).toHaveLength(1));
|
||||
expect(screen.getByText('Newborn 200')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the baked packages when the answer is the same', async () => {
|
||||
const same = bakedPackages.map((pkg, index) => ({
|
||||
slug: pkg.id,
|
||||
title: pkg.name,
|
||||
price: `€ ${pkg.price}`,
|
||||
features: pkg.features,
|
||||
displayOrder: index,
|
||||
}));
|
||||
await show(fake({ offerings: same }));
|
||||
expect(items()).toHaveLength(bakedPackages.length);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a network error', new Error('offline')],
|
||||
['a bad status', new Error('status 404')],
|
||||
['an empty list', []],
|
||||
['no list', { error: 'x' }],
|
||||
['an unusable price', card('op aanvraag')],
|
||||
['a 204 without body', undefined],
|
||||
])('stays with the baked packages on %s', async (_name, answer) => {
|
||||
await show(fake({ offerings: answer }));
|
||||
expect(items()).toHaveLength(bakedPackages.length);
|
||||
});
|
||||
|
||||
it('shows the active banner from the CMS', async () => {
|
||||
await show(
|
||||
fake({
|
||||
offerings: undefined,
|
||||
banner: {
|
||||
title: 'Kerstactie',
|
||||
text: 't',
|
||||
linkLabel: null,
|
||||
linkUrl: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('banner')).toHaveTextContent(
|
||||
'Kerstactie',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a network error', new Error('offline')],
|
||||
['an answer without title', { title: '' }],
|
||||
['a 204 (no active banner)', undefined],
|
||||
])('shows no banner on %s', async (_name, answer) => {
|
||||
await show(fake({ banner: answer }));
|
||||
expect(screen.getByTestId('banner')).toHaveTextContent('geen banner');
|
||||
});
|
||||
|
||||
it('passes an abort signal and aborts on unmount', async () => {
|
||||
const signals: AbortSignal[] = [];
|
||||
const load: LoadJson = (_path, signal) => {
|
||||
signals.push(signal);
|
||||
return new Promise(() => undefined);
|
||||
};
|
||||
const view = await renderWithProviders(
|
||||
<PackagesProvider load={load}>
|
||||
<Shown />
|
||||
</PackagesProvider>,
|
||||
);
|
||||
expect(signals).toHaveLength(2);
|
||||
expect(signals.every((signal) => !signal.aborted)).toBe(true);
|
||||
view.unmount();
|
||||
expect(signals.every((signal) => signal.aborted)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import bakedPackages, { banner as bakedBanner } from '@/content/packages';
|
||||
import type { PricingBanner, PricingPackage } from '@/content/types';
|
||||
import { mapBanner, mapOfferings } from '@/lib/offerings';
|
||||
|
||||
// The shoot packages and the announcement banner the pages show. The build
|
||||
// bakes the current ones into the HTML (prices for search engines, no layout
|
||||
// jump). After hydration the browser asks the CMS once (same origin) and
|
||||
// replaces what differs, so a change shows at once and the nightly rebuild is
|
||||
// only needed for search engines.
|
||||
//
|
||||
// Failing safe is the rule: a network error, a time-out, a bad status or an
|
||||
// answer that cannot be used leaves what was baked on screen. Nothing flashes
|
||||
// and no price ever becomes empty. The one exception is by design: a 204 from
|
||||
// the banner route means "no active banner" and hides a baked banner.
|
||||
|
||||
const OFFERINGS_PATH = '/api/v1/offerings';
|
||||
const BANNER_PATH = '/api/v1/offerings/banner';
|
||||
const TIMEOUT_MS = 8000;
|
||||
|
||||
// The JSON answer; undefined for 204; throws for anything else
|
||||
export type LoadJson = (path: string, signal: AbortSignal) => Promise<unknown>;
|
||||
|
||||
const loadFromApi: LoadJson = async (path, signal) => {
|
||||
const response = await fetch(path, {
|
||||
signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (response.status === 204) return undefined;
|
||||
if (!response.ok) throw new Error(`status ${response.status}`);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
interface Live {
|
||||
packages: PricingPackage[];
|
||||
banner: PricingBanner | null;
|
||||
}
|
||||
|
||||
const baked: Live = { packages: bakedPackages, banner: bakedBanner };
|
||||
|
||||
const LiveContext = createContext<Live>(baked);
|
||||
|
||||
// The packages to show: the baked list, or the live one once it arrived
|
||||
export const usePackages = (): PricingPackage[] =>
|
||||
useContext(LiveContext).packages;
|
||||
|
||||
// The banner to show, if any
|
||||
export const useBanner = (): PricingBanner | null =>
|
||||
useContext(LiveContext).banner;
|
||||
|
||||
const same = (a: unknown, b: unknown) =>
|
||||
JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
type PackagesProviderProps = {
|
||||
children: ReactNode;
|
||||
// Tests replace the network call
|
||||
load?: LoadJson;
|
||||
};
|
||||
|
||||
export default function PackagesProvider({
|
||||
children,
|
||||
load = loadFromApi,
|
||||
}: PackagesProviderProps) {
|
||||
const [live, setLive] = useState<Live>(baked);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
// Only replace on a real difference: no re-render for nothing
|
||||
const update = (change: Partial<Live>) =>
|
||||
setLive((current) => {
|
||||
const next = { ...current, ...change };
|
||||
return same(next, current) ? current : next;
|
||||
});
|
||||
|
||||
const packages = load(OFFERINGS_PATH, signal)
|
||||
.then((answer) => {
|
||||
const mapped = mapOfferings(answer);
|
||||
if (mapped && !signal.aborted) {
|
||||
update({ packages: mapped.packages });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const banner = load(BANNER_PATH, signal)
|
||||
.then((answer) => {
|
||||
if (signal.aborted) return;
|
||||
if (answer === undefined) update({ banner: null });
|
||||
else {
|
||||
const mapped = mapBanner(answer);
|
||||
if (mapped) update({ banner: mapped });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
void Promise.all([packages, banner]).finally(() => clearTimeout(timer));
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const value = useMemo(() => live, [live]);
|
||||
return (
|
||||
<LiveContext.Provider value={value}>{children}</LiveContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
import { Box, chakra, Heading, Text, useRecipe } from '@chakra-ui/react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { Box, Heading, Text, useRecipe } from '@chakra-ui/react';
|
||||
import type { PricingBanner } from '@/content/types';
|
||||
|
||||
type PriceBannerProps = {
|
||||
banner: PricingBanner;
|
||||
};
|
||||
|
||||
// The optional dark band under the price cards (an offering with
|
||||
// layout=banner in the CMS), for an offer or an announcement. It is not a
|
||||
// bookable package: the button only leads to the contact form, without a
|
||||
// chosen package. The price is free text from the CMS ("€ 99 i.p.v. € 150").
|
||||
// Only the title is required; whatever is empty is left out. Without a button
|
||||
// label the button says "Neem contact op".
|
||||
// The optional dark band under the price cards: an announcement from the CMS
|
||||
// (an offer, a notice). It is not a bookable package and cannot be dismissed.
|
||||
// Only the title is required; the text and the button are left out when empty.
|
||||
// The link is a https address or a path on this site (the CMS guarantees
|
||||
// that, mapBanner checks it again), so a plain anchor is enough.
|
||||
export default function PriceBanner({ banner }: PriceBannerProps) {
|
||||
const linkButton = useRecipe({ key: 'linkButton' });
|
||||
|
||||
@@ -27,7 +25,10 @@ export default function PriceBanner({ banner }: PriceBannerProps) {
|
||||
color="white"
|
||||
display="grid"
|
||||
gap={{ base: 6, md: 10 }}
|
||||
gridTemplateColumns={{ base: '1fr', md: '1fr auto' }}
|
||||
gridTemplateColumns={{
|
||||
base: '1fr',
|
||||
md: banner.link ? '1fr auto' : '1fr',
|
||||
}}
|
||||
alignItems="center"
|
||||
>
|
||||
<Box>
|
||||
@@ -36,57 +37,33 @@ export default function PriceBanner({ banner }: PriceBannerProps) {
|
||||
id="price-banner-title"
|
||||
fontSize="1.5rem"
|
||||
color="white"
|
||||
mb={2}
|
||||
mb={banner.text ? 2 : 0}
|
||||
>
|
||||
{banner.title}
|
||||
</Heading>
|
||||
{banner.description && (
|
||||
<Text color="white" opacity={0.85} mb={3}>
|
||||
{banner.description}
|
||||
{banner.text && (
|
||||
<Text color="white" opacity={0.85}>
|
||||
{banner.text}
|
||||
</Text>
|
||||
)}
|
||||
{banner.features.length > 0 && (
|
||||
<chakra.ul
|
||||
listStyleType="none"
|
||||
display="flex"
|
||||
flexWrap="wrap"
|
||||
columnGap={6}
|
||||
rowGap={1}
|
||||
fontSize="sm"
|
||||
opacity={0.85}
|
||||
>
|
||||
{banner.features.map((feature) => (
|
||||
<chakra.li key={feature}>{feature}</chakra.li>
|
||||
))}
|
||||
</chakra.ul>
|
||||
)}
|
||||
</Box>
|
||||
<Box textAlign={{ base: 'start', md: 'center' }}>
|
||||
{banner.priceText && (
|
||||
<Text
|
||||
fontFamily="heading"
|
||||
fontSize="1.75rem"
|
||||
lineHeight="1.1"
|
||||
color="white"
|
||||
>
|
||||
{banner.priceText}
|
||||
</Text>
|
||||
)}
|
||||
{banner.priceNote && (
|
||||
<Text fontSize="sm" opacity={0.85}>
|
||||
{banner.priceNote}
|
||||
</Text>
|
||||
)}
|
||||
{banner.link && (
|
||||
<Box
|
||||
asChild
|
||||
css={linkButton({ variant: 'light', size: 'fit' })}
|
||||
mt={banner.priceText || banner.priceNote ? 4 : 0}
|
||||
justifySelf={{ base: 'start', md: 'center' }}
|
||||
>
|
||||
<Link to="/" hash="contact" data-testid="price-banner-cta">
|
||||
{banner.ctaLabel ?? 'Neem contact op'}
|
||||
</Link>
|
||||
<a
|
||||
href={banner.link.url}
|
||||
data-testid="price-banner-cta"
|
||||
{...(banner.link.url.startsWith('https://')
|
||||
? { rel: 'noopener' }
|
||||
: {})}
|
||||
>
|
||||
{banner.link.label}
|
||||
</a>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,11 +35,8 @@ describe('Pricing', () => {
|
||||
it('shows an optional banner under the cards, not as a package', async () => {
|
||||
const banner = {
|
||||
title: 'Kerstactie',
|
||||
description: 'Alleen in december',
|
||||
priceText: '€ 99 i.p.v. € 150',
|
||||
priceNote: 'tot 31 december',
|
||||
features: ['30 minuten', '10 foto’s'],
|
||||
ctaLabel: 'Boek de actie',
|
||||
text: 'Alleen in december',
|
||||
link: { label: 'Boek de actie', url: '/contact' },
|
||||
};
|
||||
const { container } = await renderWithProviders(
|
||||
<Pricing content={content} packages={packages} banner={banner} />,
|
||||
@@ -47,13 +44,12 @@ describe('Pricing', () => {
|
||||
const section = screen.getByRole('region', { name: 'Prijzen' });
|
||||
const shown = within(section).getByTestId('price-banner');
|
||||
expect(
|
||||
within(shown).getByText('€ 99 i.p.v. € 150'),
|
||||
within(shown).getByText('Alleen in december'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
within(shown).getByRole('link', { name: 'Boek de actie' }),
|
||||
).toHaveAttribute('href', '/#contact');
|
||||
// The cards are still the three packages: no card and no booking
|
||||
// link with a package for the banner
|
||||
).toHaveAttribute('href', '/contact');
|
||||
// The cards are still the three packages: no card for the banner
|
||||
expect(
|
||||
within(section).queryByTestId('price-card-kerstactie'),
|
||||
).not.toBeInTheDocument();
|
||||
@@ -63,24 +59,38 @@ describe('Pricing', () => {
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
it('hides every empty field of the banner', async () => {
|
||||
it('marks an external link and hides every empty field', async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<Pricing
|
||||
content={content}
|
||||
packages={packages}
|
||||
banner={{ title: 'Past er niets bij?', features: [] }}
|
||||
banner={{
|
||||
title: 'Nieuws',
|
||||
link: { label: 'Lees meer', url: 'https://example.nl/x' },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
const shown = screen.getByTestId('price-banner');
|
||||
expect(shown.querySelectorAll('p')).toHaveLength(0);
|
||||
expect(
|
||||
within(shown).getByRole('link', { name: 'Lees meer' }),
|
||||
).toHaveAttribute('rel', 'noopener');
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
it('shows only the title without text and link', async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<Pricing
|
||||
content={content}
|
||||
packages={packages}
|
||||
banner={{ title: 'Past er niets bij?' }}
|
||||
/>,
|
||||
);
|
||||
const shown = screen.getByTestId('price-banner');
|
||||
expect(
|
||||
within(shown).getByRole('heading', { level: 3 }),
|
||||
).toHaveTextContent('Past er niets bij?');
|
||||
expect(shown.querySelectorAll('ul, li')).toHaveLength(0);
|
||||
// Only the heading and the button have text
|
||||
expect(shown.querySelectorAll('p')).toHaveLength(0);
|
||||
expect(
|
||||
within(shown).getByRole('link', { name: 'Neem contact op' }),
|
||||
).toBeInTheDocument();
|
||||
expect(within(shown).queryByRole('link')).not.toBeInTheDocument();
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user