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();
|
||||
});
|
||||
|
||||
|
||||
@@ -101,17 +101,15 @@ export interface PricingPackage {
|
||||
featured?: boolean;
|
||||
}
|
||||
|
||||
// The one optional banner under the price cards (an offering with
|
||||
// layout=banner in the CMS). It is not a bookable package: it is not in the
|
||||
// form's choices and not in the package count. The price is free text. Only
|
||||
// the title is required; the banner hides what is empty.
|
||||
// The one optional announcement banner under the price cards (GET
|
||||
// /api/v1/offerings/banner in the CMS). It is not a bookable package: it is
|
||||
// not in the form's choices and not in the package count. Only the title is
|
||||
// required; the banner hides what is empty. The link is a https address or a
|
||||
// path on this site.
|
||||
export interface PricingBanner {
|
||||
title: string;
|
||||
description?: string;
|
||||
priceText?: string;
|
||||
priceNote?: string;
|
||||
features: string[];
|
||||
ctaLabel?: string;
|
||||
text?: string;
|
||||
link?: { label: string; url: string };
|
||||
}
|
||||
|
||||
// The kinds of shoot Andrea offers. The ids are stable: they go into URLs
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
isSafeBannerUrl,
|
||||
mapBanner,
|
||||
mapOfferings,
|
||||
parsePriceText,
|
||||
} from './offerings';
|
||||
|
||||
const card = (over: Record<string, unknown> = {}) => ({
|
||||
id: 'x',
|
||||
slug: 'newborn',
|
||||
title: 'Newborn',
|
||||
description: 'Mooie shoot',
|
||||
price: '€ 185',
|
||||
priceNote: 'incl. galerij',
|
||||
features: ['1-2 uur fotografie', 'Online galerij'],
|
||||
ctaLabel: 'Boek',
|
||||
featured: false,
|
||||
displayOrder: 2,
|
||||
categoryId: null,
|
||||
category: null,
|
||||
layout: 'card',
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('parsePriceText', () => {
|
||||
it.each([
|
||||
['€ 175', 175],
|
||||
['€ 1.250', 1250],
|
||||
['175,-', 175],
|
||||
['€ 175,00', 175],
|
||||
['€\u00a0185', 185],
|
||||
])('leest %s als %i', (text, euros) => {
|
||||
expect(parsePriceText(text)).toBe(euros);
|
||||
});
|
||||
|
||||
it.each(['', 'op aanvraag', '€ 12,50', '€ 0', '175 of 185', null, 12])(
|
||||
'geeft geen prijs voor %j',
|
||||
(text) => {
|
||||
expect(parsePriceText(text)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('geeft terug wat formatteren als hele euros oplevert', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.integer({ min: 1, max: 99_999 }), (euros) => {
|
||||
const grouped = euros.toLocaleString('nl-NL');
|
||||
expect(parsePriceText(`€ ${grouped}`)).toBe(euros);
|
||||
expect(parsePriceText(`€ ${euros}`)).toBe(euros);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapOfferings', () => {
|
||||
it('maakt pakketten in volgorde van displayOrder', () => {
|
||||
const result = mapOfferings([
|
||||
card({ slug: 'gezin', title: 'Gezin', displayOrder: 3 }),
|
||||
card({
|
||||
slug: 'zwangerschap',
|
||||
title: 'Zwangerschap',
|
||||
displayOrder: 1,
|
||||
}),
|
||||
card(),
|
||||
]);
|
||||
expect(result?.packages.map((p) => p.id)).toEqual([
|
||||
'zwangerschap',
|
||||
'newborn',
|
||||
'gezin',
|
||||
]);
|
||||
expect(result?.packages[1]).toMatchObject({
|
||||
name: 'Newborn',
|
||||
price: 185,
|
||||
priceNote: 'incl. galerij',
|
||||
ctaLabel: 'Boek',
|
||||
});
|
||||
});
|
||||
|
||||
it('slaat ongeldige kaarten over en behoudt de rest', () => {
|
||||
const result = mapOfferings([
|
||||
card({ slug: 'Slecht Id' }),
|
||||
card({ slug: 'a', price: 'op aanvraag' }),
|
||||
card({ slug: 'b', title: ' ' }),
|
||||
card({ slug: 'c', features: [] }),
|
||||
card({ slug: 'd', features: ['ok', ''] }),
|
||||
card({ slug: 'newborn' }),
|
||||
card({ slug: 'newborn', title: 'Dubbel' }),
|
||||
]);
|
||||
expect(result?.packages.map((p) => p.id)).toEqual(['newborn']);
|
||||
expect(result?.packages[0].name).toBe('Newborn');
|
||||
});
|
||||
|
||||
it('verwerpt een antwoord zonder geldig pakket', () => {
|
||||
expect(mapOfferings([])).toBeNull();
|
||||
expect(mapOfferings([card({ price: '' })])).toBeNull();
|
||||
expect(mapOfferings({ items: [] })).toBeNull();
|
||||
expect(mapOfferings(null)).toBeNull();
|
||||
expect(mapOfferings('fout')).toBeNull();
|
||||
});
|
||||
|
||||
it('geeft nooit een pakket met lege of ongeldige prijs terug, wat er ook komt', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(fc.jsonValue()), (answer) => {
|
||||
const result = mapOfferings(answer);
|
||||
for (const pkg of result?.packages ?? []) {
|
||||
expect(Number.isInteger(pkg.price)).toBe(true);
|
||||
expect(pkg.price).toBeGreaterThan(0);
|
||||
expect(pkg.features.length).toBeGreaterThan(0);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapBanner', () => {
|
||||
it('neemt titel, tekst en een volledige link', () => {
|
||||
expect(
|
||||
mapBanner({
|
||||
title: 'Kerstactie',
|
||||
text: 'Alleen in december',
|
||||
linkLabel: 'Boek nu',
|
||||
linkUrl: '/contact',
|
||||
}),
|
||||
).toEqual({
|
||||
title: 'Kerstactie',
|
||||
text: 'Alleen in december',
|
||||
link: { label: 'Boek nu', url: '/contact' },
|
||||
});
|
||||
});
|
||||
|
||||
it('laat lege velden en een halve of onveilige link weg', () => {
|
||||
expect(
|
||||
mapBanner({ title: 'T', text: '', linkLabel: null, linkUrl: null }),
|
||||
).toEqual({ title: 'T', text: undefined, link: undefined });
|
||||
expect(
|
||||
mapBanner({ title: 'T', linkLabel: 'Hier', linkUrl: null })?.link,
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
mapBanner({
|
||||
title: 'T',
|
||||
linkLabel: 'Hier',
|
||||
linkUrl: 'javascript:x',
|
||||
})?.link,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('geeft null zonder titel of zonder object', () => {
|
||||
expect(mapBanner({ title: ' ' })).toBeNull();
|
||||
expect(mapBanner(null)).toBeNull();
|
||||
expect(mapBanner('x')).toBeNull();
|
||||
expect(mapBanner([{ title: 'T' }])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSafeBannerUrl', () => {
|
||||
it.each(['https://example.nl/x', '/contact', '/#contact', '/a?b=1'])(
|
||||
'staat %s toe',
|
||||
(url) => expect(isSafeBannerUrl(url)).toBe(true),
|
||||
);
|
||||
it.each([
|
||||
'http://example.nl',
|
||||
'//evil.nl',
|
||||
'javascript:alert(1)',
|
||||
'mailto:a@b.nl',
|
||||
'contact',
|
||||
`/${String.fromCharCode(92)}evil`,
|
||||
'https://',
|
||||
'',
|
||||
])('weigert %s', (url) => expect(isSafeBannerUrl(url)).toBe(false));
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
// Turns the answer of GET /api/v1/offerings (the CMS) into what the site
|
||||
// shows: the shoot packages (cards) and the announcement banner. Pure functions, so
|
||||
// they are tested without a network. The build step (fetchOfferings.ts) uses
|
||||
// them; the site itself never calls the API (prices are in the HTML).
|
||||
//
|
||||
// Rule of the design: a bad answer never breaks the build and never leads to
|
||||
// an empty or wrong price. Anything that is not clearly valid is dropped, and
|
||||
// when no valid card is left the whole answer is rejected (null), so the
|
||||
// caller keeps the last known list (the snapshot).
|
||||
|
||||
export interface OfferingPackage {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number; // whole euros
|
||||
features: string[];
|
||||
priceNote?: string;
|
||||
description?: string;
|
||||
ctaLabel?: string;
|
||||
featured?: boolean;
|
||||
}
|
||||
|
||||
// The announcement banner (GET /api/v1/offerings/banner). Only the title is
|
||||
// required; the link is both parts or nothing.
|
||||
export interface OfferingBanner {
|
||||
title: string;
|
||||
text?: string;
|
||||
link?: { label: string; url: string };
|
||||
}
|
||||
|
||||
export interface SiteOfferings {
|
||||
packages: OfferingPackage[];
|
||||
banner: OfferingBanner | null;
|
||||
}
|
||||
|
||||
const SLUG = /^[a-z0-9-]+$/;
|
||||
|
||||
// "€ 175", "€ 1.250", "175,-", "€ 175,00" → whole euros. Anything else
|
||||
// ("op aanvraag", "€ 12,50", "€ 0") has no usable price and gives null.
|
||||
export function parsePriceText(text: unknown): number | null {
|
||||
if (typeof text !== 'string') return null;
|
||||
const match = /^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$/.exec(
|
||||
text.trim(),
|
||||
);
|
||||
if (!match) return null;
|
||||
const euros = Number(match[1].replace(/\./g, ''));
|
||||
return Number.isInteger(euros) && euros > 0 ? euros : null;
|
||||
}
|
||||
|
||||
const asText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
||||
|
||||
function asFeatures(value: unknown): string[] | null {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const features = value.map(asText);
|
||||
return features.length > 0 && features.every((f) => f !== undefined)
|
||||
? (features as string[])
|
||||
: null;
|
||||
}
|
||||
|
||||
interface RawOffering {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const isObject = (value: unknown): value is RawOffering =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
function toPackage(raw: RawOffering): OfferingPackage | null {
|
||||
const id = asText(raw.slug);
|
||||
const name = asText(raw.title);
|
||||
const price = parsePriceText(raw.price);
|
||||
const features = asFeatures(raw.features);
|
||||
if (!id || !SLUG.test(id) || !name || price === null || !features) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
price,
|
||||
features,
|
||||
priceNote: asText(raw.priceNote),
|
||||
description: asText(raw.description),
|
||||
ctaLabel: asText(raw.ctaLabel),
|
||||
featured: raw.featured === true ? true : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// A link target the banner may use: https, or a path on this site with one
|
||||
// leading slash (never '//', http, javascript: or mailto:)
|
||||
export function isSafeBannerUrl(url: string): boolean {
|
||||
if (url.startsWith('https://')) {
|
||||
try {
|
||||
return new URL(url).protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return (
|
||||
url.startsWith('/') &&
|
||||
!url.startsWith('//') &&
|
||||
!url.includes(String.fromCharCode(92))
|
||||
);
|
||||
}
|
||||
|
||||
// The 200 answer of /api/v1/offerings/banner, or null when it is not usable
|
||||
// (no title, or a link that is half given or unsafe is left out)
|
||||
export function mapBanner(answer: unknown): OfferingBanner | null {
|
||||
if (!isObject(answer)) return null;
|
||||
const title = asText(answer.title);
|
||||
if (!title) return null;
|
||||
const label = asText(answer.linkLabel);
|
||||
const url = asText(answer.linkUrl);
|
||||
return {
|
||||
title,
|
||||
text: asText(answer.text),
|
||||
link: label && url && isSafeBannerUrl(url) ? { label, url } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const orderOf = (raw: RawOffering) =>
|
||||
typeof raw.displayOrder === 'number' ? raw.displayOrder : 0;
|
||||
|
||||
// null: the answer cannot be used (not a list, or no valid card)
|
||||
export function mapOfferings(
|
||||
answer: unknown,
|
||||
): { packages: OfferingPackage[] } | null {
|
||||
if (!Array.isArray(answer)) return null;
|
||||
const rows = answer
|
||||
.filter(isObject)
|
||||
.map((raw, index) => ({ raw, index }))
|
||||
.sort((a, b) => orderOf(a.raw) - orderOf(b.raw) || a.index - b.index)
|
||||
.map(({ raw }) => raw);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const packages: OfferingPackage[] = [];
|
||||
for (const raw of rows) {
|
||||
const pkg = toPackage(raw);
|
||||
if (!pkg || seen.has(pkg.id)) continue;
|
||||
seen.add(pkg.id);
|
||||
packages.push(pkg);
|
||||
}
|
||||
return packages.length > 0 ? { packages } : null;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
|
||||
import { createRootRoute, HeadContent, Scripts } from '@tanstack/react-router';
|
||||
import { ChakraProvider } from '@chakra-ui/react';
|
||||
import AppShell from '../components/AppShell';
|
||||
import PackagesProvider from '../components/PackagesProvider/PackagesProvider';
|
||||
import NoScriptStyles from '../components/NoScript/NoScriptStyles';
|
||||
import ErrorPage from '../components/StatusPage/ErrorPage';
|
||||
import NotFound from '../components/StatusPage/NotFound';
|
||||
@@ -42,12 +43,12 @@ const RootDocument = ({ children }: { children: ReactNode }) => (
|
||||
);
|
||||
|
||||
const RootLayout = () => (
|
||||
<>
|
||||
<PackagesProvider>
|
||||
<AppShell />
|
||||
<Suspense>
|
||||
<RouterDevtools />
|
||||
</Suspense>
|
||||
</>
|
||||
</PackagesProvider>
|
||||
);
|
||||
|
||||
export const Route = createRootRoute({
|
||||
|
||||
@@ -10,7 +10,7 @@ import PageIntro from '../components/PageIntro/PageIntro';
|
||||
import PageSection from '../components/PageSection/PageSection';
|
||||
import Reveal from '../components/Reveal/Reveal';
|
||||
import contactContent from '../content/contactContent';
|
||||
import packages from '../content/packages';
|
||||
import { usePackages } from '../components/PackagesProvider/PackagesProvider';
|
||||
import siteContent from '../content/siteContent';
|
||||
import { withReplyTime } from '../lib/withReplyTime';
|
||||
import useHydrated from '../hooks/useHydrated';
|
||||
@@ -50,6 +50,7 @@ export const Route = createFileRoute('/contact')({
|
||||
// form (BR-CP-01..04). The card is in the page twice, one per layout, so the
|
||||
// reading order always matches what is shown.
|
||||
function Contact() {
|
||||
const packages = usePackages();
|
||||
const { pakket: searched } = Route.useSearch();
|
||||
// The search only counts after hydration, so the prerendered HTML and the
|
||||
// first browser render agree (BR-HYD-10)
|
||||
|
||||
@@ -9,7 +9,10 @@ import IntroGallery from '../components/home/IntroGallery/IntroGallery';
|
||||
import heroContent from '../content/heroContent';
|
||||
import homeContent from '../content/homeContent';
|
||||
import instagramContent from '../content/instagramContent';
|
||||
import packages, { banner } from '../content/packages';
|
||||
import {
|
||||
useBanner,
|
||||
usePackages,
|
||||
} from '../components/PackagesProvider/PackagesProvider';
|
||||
import testimonials from '../content/testimonials';
|
||||
import siteContent from '../content/siteContent';
|
||||
import { visibleSocials } from '../lib/visibleSocials';
|
||||
@@ -29,6 +32,8 @@ export const Route = createFileRoute('/')({
|
||||
|
||||
// The homepage: the hero, then the sections in the order of LAYOUT.md
|
||||
function Index() {
|
||||
const packages = usePackages();
|
||||
const banner = useBanner();
|
||||
const { pakket: searched } = Route.useSearch();
|
||||
// The search only counts after hydration, so the prerendered HTML and the
|
||||
// first browser render agree (BR-HYD-10)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useMemo } from 'react';
|
||||
import { usePackages } from '../../components/PackagesProvider/PackagesProvider';
|
||||
import type { ShootPageSources } from '../../lib/shootPageView';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
|
||||
// The sources of a shoot page with the packages as they are now (baked, or
|
||||
// live once the browser got the CMS answer)
|
||||
export function useShootPageSources(): ShootPageSources {
|
||||
const packages = usePackages();
|
||||
return useMemo(() => ({ ...shootPageSources, packages }), [packages]);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import gezinPage from '../../content/shootPages/gezin';
|
||||
import siteContent from '../../content/siteContent';
|
||||
import { shootPageView } from '../../lib/shootPageView';
|
||||
import { pageHead, shootPageGraph } from '../../seo';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
import { useShootPageSources } from './-useShootPageSources';
|
||||
|
||||
export const Route = createFileRoute('/soorten-fotoshoots/gezin')({
|
||||
head: () => pageHead('/soorten-fotoshoots/gezin'),
|
||||
@@ -17,7 +17,8 @@ export const Route = createFileRoute('/soorten-fotoshoots/gezin')({
|
||||
// part of the main bundle, the component is split off, so the page texts
|
||||
// only load with this page.
|
||||
function GezinPage() {
|
||||
const view = shootPageView('gezin', gezinPage, shootPageSources);
|
||||
const sources = useShootPageSources();
|
||||
const view = shootPageView('gezin', gezinPage, sources);
|
||||
if (view === undefined) return <NotFound />;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -5,7 +5,7 @@ import PageIntro from '../../components/PageIntro/PageIntro';
|
||||
import RichParagraph from '../../components/RichParagraph/RichParagraph';
|
||||
import ShootList from '../../components/shoots/ShootList/ShootList';
|
||||
import StructuredData from '../../components/StructuredData/StructuredData';
|
||||
import packages from '../../content/packages';
|
||||
import { usePackages } from '../../components/PackagesProvider/PackagesProvider';
|
||||
import portfolioContent from '../../content/portfolioContent';
|
||||
import shootTypes from '../../content/shootTypes';
|
||||
import shootTypesPageContent from '../../content/shootTypesPageContent';
|
||||
@@ -23,6 +23,7 @@ export const Route = createFileRoute('/soorten-fotoshoots/')({
|
||||
// The shoot types page: the page head, the shoots one by one and a closing
|
||||
// call to action, in the order of LAYOUT.md
|
||||
function PhotoshootTypes() {
|
||||
const packages = usePackages();
|
||||
const { head, closing } = shootTypesPageContent;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -6,7 +6,7 @@ import loveshootPage from '../../content/shootPages/loveshoot';
|
||||
import siteContent from '../../content/siteContent';
|
||||
import { shootPageView } from '../../lib/shootPageView';
|
||||
import { pageHead, shootPageGraph } from '../../seo';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
import { useShootPageSources } from './-useShootPageSources';
|
||||
|
||||
export const Route = createFileRoute('/soorten-fotoshoots/loveshoot')({
|
||||
head: () => pageHead('/soorten-fotoshoots/loveshoot'),
|
||||
@@ -17,7 +17,8 @@ export const Route = createFileRoute('/soorten-fotoshoots/loveshoot')({
|
||||
// part of the main bundle, the component is split off, so the page texts
|
||||
// only load with this page.
|
||||
function LoveshootPage() {
|
||||
const view = shootPageView('loveshoot', loveshootPage, shootPageSources);
|
||||
const sources = useShootPageSources();
|
||||
const view = shootPageView('loveshoot', loveshootPage, sources);
|
||||
if (view === undefined) return <NotFound />;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -6,7 +6,7 @@ import newbornPage from '../../content/shootPages/newborn';
|
||||
import siteContent from '../../content/siteContent';
|
||||
import { shootPageView } from '../../lib/shootPageView';
|
||||
import { pageHead, shootPageGraph } from '../../seo';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
import { useShootPageSources } from './-useShootPageSources';
|
||||
|
||||
export const Route = createFileRoute('/soorten-fotoshoots/newborn')({
|
||||
head: () => pageHead('/soorten-fotoshoots/newborn'),
|
||||
@@ -17,7 +17,8 @@ export const Route = createFileRoute('/soorten-fotoshoots/newborn')({
|
||||
// part of the main bundle, the component is split off, so the page texts
|
||||
// only load with this page.
|
||||
function NewbornPage() {
|
||||
const view = shootPageView('newborn', newbornPage, shootPageSources);
|
||||
const sources = useShootPageSources();
|
||||
const view = shootPageView('newborn', newbornPage, sources);
|
||||
if (view === undefined) return <NotFound />;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -6,7 +6,7 @@ import portretPage from '../../content/shootPages/portret';
|
||||
import siteContent from '../../content/siteContent';
|
||||
import { shootPageView } from '../../lib/shootPageView';
|
||||
import { pageHead, shootPageGraph } from '../../seo';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
import { useShootPageSources } from './-useShootPageSources';
|
||||
|
||||
export const Route = createFileRoute('/soorten-fotoshoots/portret')({
|
||||
head: () => pageHead('/soorten-fotoshoots/portret'),
|
||||
@@ -17,7 +17,8 @@ export const Route = createFileRoute('/soorten-fotoshoots/portret')({
|
||||
// part of the main bundle, the component is split off, so the page texts
|
||||
// only load with this page.
|
||||
function PortretPage() {
|
||||
const view = shootPageView('portret', portretPage, shootPageSources);
|
||||
const sources = useShootPageSources();
|
||||
const view = shootPageView('portret', portretPage, sources);
|
||||
if (view === undefined) return <NotFound />;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -6,7 +6,7 @@ import zwangerschapPage from '../../content/shootPages/zwangerschap';
|
||||
import siteContent from '../../content/siteContent';
|
||||
import { shootPageView } from '../../lib/shootPageView';
|
||||
import { pageHead, shootPageGraph } from '../../seo';
|
||||
import { shootPageSources } from './-shootPageSources';
|
||||
import { useShootPageSources } from './-useShootPageSources';
|
||||
|
||||
export const Route = createFileRoute('/soorten-fotoshoots/zwangerschap')({
|
||||
head: () => pageHead('/soorten-fotoshoots/zwangerschap'),
|
||||
@@ -17,11 +17,8 @@ export const Route = createFileRoute('/soorten-fotoshoots/zwangerschap')({
|
||||
// part of the main bundle, the component is split off, so the page texts
|
||||
// only load with this page.
|
||||
function ZwangerschapPage() {
|
||||
const view = shootPageView(
|
||||
'zwangerschap',
|
||||
zwangerschapPage,
|
||||
shootPageSources,
|
||||
);
|
||||
const sources = useShootPageSources();
|
||||
const view = shootPageView('zwangerschap', zwangerschapPage, sources);
|
||||
if (view === undefined) return <NotFound />;
|
||||
return (
|
||||
<>
|
||||
|
||||
Reference in New Issue
Block a user