From 12319bb841c6864fe81c40f3853e605e68bb13ba Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 11:19:50 +0100 Subject: [PATCH] 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 --- web/config/fetchOfferings.ts | 43 +++++- web/config/previewServer.test.ts | 3 + web/config/previewServer.ts | 15 +- web/e2e/contactForm.e2e.ts | 5 + web/e2e/packagesLive.e2e.ts | 79 ++++++++++ .../PackagesProvider.test.tsx | 144 ++++++++++++++++++ .../PackagesProvider/PackagesProvider.tsx | 107 +++++++++++++ .../components/home/Pricing/PriceBanner.tsx | 75 ++++----- .../components/home/Pricing/Pricing.test.tsx | 44 +++--- web/src/content/types.ts | 16 +- web/{config => src/lib}/offerings.test.ts | 118 +++++++------- web/{config => src/lib}/offerings.ts | 57 ++++--- web/src/routes/__root.tsx | 5 +- web/src/routes/contact.tsx | 3 +- web/src/routes/index.tsx | 7 +- .../-useShootPageSources.ts | 11 ++ web/src/routes/soorten-fotoshoots/gezin.tsx | 5 +- web/src/routes/soorten-fotoshoots/index.tsx | 3 +- .../routes/soorten-fotoshoots/loveshoot.tsx | 5 +- web/src/routes/soorten-fotoshoots/newborn.tsx | 5 +- web/src/routes/soorten-fotoshoots/portret.tsx | 5 +- .../soorten-fotoshoots/zwangerschap.tsx | 9 +- 22 files changed, 584 insertions(+), 180 deletions(-) create mode 100644 web/e2e/packagesLive.e2e.ts create mode 100644 web/src/components/PackagesProvider/PackagesProvider.test.tsx create mode 100644 web/src/components/PackagesProvider/PackagesProvider.tsx rename web/{config => src/lib}/offerings.test.ts (67%) rename web/{config => src/lib}/offerings.ts (70%) create mode 100644 web/src/routes/soorten-fotoshoots/-useShootPageSources.ts diff --git a/web/config/fetchOfferings.ts b/web/config/fetchOfferings.ts index 9d33f7d..28903d7 100644 --- a/web/config/fetchOfferings.ts +++ b/web/config/fetchOfferings.ts @@ -8,7 +8,11 @@ // https://test.andreaslop.nl (the API is same-origin, /api/v1/offerings). import { readFileSync, writeFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { mapOfferings, type SiteOfferings } from './offerings.ts'; +import { + mapBanner, + mapOfferings, + type SiteOfferings, +} from '../src/lib/offerings.ts'; const SNAPSHOT = fileURLToPath( new URL('../src/content/offerings.snapshot.json', import.meta.url), @@ -19,14 +23,17 @@ const GENERATED = fileURLToPath( const TIMEOUT_MS = 10_000; const ATTEMPTS = 2; -async function fetchAnswer(base: string): Promise { - const url = new URL('/api/v1/offerings', base); +// The JSON answer, or undefined for 204 (no content). Other statuses and +// network errors throw. +async function fetchAnswer(base: string, path: string): Promise { + const url = new URL(path, base); for (let attempt = 1; ; attempt++) { try { const response = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), headers: { Accept: 'application/json' }, }); + if (response.status === 204) return undefined; if (!response.ok) throw new Error(`status ${response.status}`); return await response.json(); } catch (error) { @@ -45,13 +52,35 @@ async function main() { console.log('[offerings] no OFFERINGS_URL: using the snapshot'); } else { try { - const mapped = mapOfferings(await fetchAnswer(base)); + const mapped = mapOfferings( + await fetchAnswer(base, '/api/v1/offerings'), + ); if (mapped) { - result = { ...mapped, source: 'cms' }; + result = { + ...snapshot, + packages: mapped.packages, + source: 'cms', + }; console.log( - `[offerings] ${mapped.packages.length} packages` + - `${mapped.banner ? ' and a banner' : ''} from ${base}`, + `[offerings] ${mapped.packages.length} packages from ${base}`, ); + // The banner: 200 is the active one, 204 means none. A + // failing banner call keeps the snapshot's banner (none). + try { + const banner = mapBanner( + await fetchAnswer(base, '/api/v1/offerings/banner'), + ); + result.banner = banner; + console.log( + banner + ? `[offerings] banner "${banner.title}"` + : '[offerings] no active banner', + ); + } catch (error) { + console.warn( + `[offerings] banner not available (${String(error)}): none`, + ); + } } else { console.warn( `[offerings] answer of ${base} has no valid package: using the snapshot`, diff --git a/web/config/previewServer.test.ts b/web/config/previewServer.test.ts index 5b16f5b..427d0dd 100644 --- a/web/config/previewServer.test.ts +++ b/web/config/previewServer.test.ts @@ -669,6 +669,9 @@ describe('startPreviewServer', () => { expect( (await ask(port, '/api/v1/contact-messages', 'POST')).status, ).toBe(202); + // Live pakketten: geen gegevens, zonder 404 + expect((await ask(port, '/api/v1/offerings')).status).toBe(204); + expect((await ask(port, '/api/v1/offerings/banner')).status).toBe(204); // Al het andere blijft zoals het was expect((await ask(port, '/api/v1/andere')).status).toBe(404); expect((await ask(port, '/api/v1/contact-messages')).status).toBe(404); diff --git a/web/config/previewServer.ts b/web/config/previewServer.ts index 2fa9a10..203cc00 100644 --- a/web/config/previewServer.ts +++ b/web/config/previewServer.ts @@ -217,6 +217,15 @@ export function contactStubResponse( captcha: null, }); } + // Live packages and banner: "no data" (204), so the page stays with the + // baked list and shows no banner, without a 404 in the console (the site + // asks once per page load) + if ( + method === 'GET' && + (path === '/api/v1/offerings' || path === '/api/v1/offerings/banner') + ) { + return { status: 204, body: '' }; + } if (method === 'POST' && path === CONTACT_API) { return json(202, { status: 'received' }); } @@ -248,10 +257,12 @@ export function startPreviewServer( response, stub.status, { - 'Content-Type': 'application/json', + ...(stub.body + ? { 'Content-Type': 'application/json' } + : {}), 'Cache-Control': 'no-store', }, - stub.body, + stub.body || null, ); request.resume(); return; diff --git a/web/e2e/contactForm.e2e.ts b/web/e2e/contactForm.e2e.ts index 2080c25..2d29fed 100644 --- a/web/e2e/contactForm.e2e.ts +++ b/web/e2e/contactForm.e2e.ts @@ -40,6 +40,11 @@ function mockApi(options: { await page.route('**/api/v1/**', async (route) => { const request = route.request(); const path = new URL(request.url()).pathname; + // The live packages call of every page: no live data, and + // not part of what these tests count + if (path.startsWith('/api/v1/offerings')) { + return route.fulfill({ status: 204 }); + } requests.push(`${request.method()} ${path}`); if (path.endsWith('/token')) { const { status, body } = options.token ?? { diff --git a/web/e2e/packagesLive.e2e.ts b/web/e2e/packagesLive.e2e.ts new file mode 100644 index 0000000..c498cc3 --- /dev/null +++ b/web/e2e/packagesLive.e2e.ts @@ -0,0 +1,79 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + eventually, + openPage, + waitForHydration, + type OpenedPage, +} from './support/browser.ts'; +import { startServer } from './support/server.ts'; + +// De pakketten staan gebakken in de HTML. Na het laden vraagt de pagina het +// CMS (/api/v1/offerings); een afwijkend antwoord vervangt de lijst, een +// fout laat de gebakken lijst staan. +let server: Awaited>; +beforeAll(async () => { + server = await startServer(); +}); +afterAll(() => server.close()); + +const answer = (price: string) => [ + { + slug: 'newborn', + title: 'Newborn', + price, + features: ['Een kenmerk'], + displayOrder: 0, + layout: 'card', + }, +]; + +const mock = + (status: number, body?: unknown) => async (page: OpenedPage['page']) => { + await page.route('**/api/v1/offerings', (route) => + route.fulfill({ + status, + contentType: 'application/json', + body: body === undefined ? '' : JSON.stringify(body), + }), + ); + }; + +const cards = (page: OpenedPage['page']) => + page.locator('[data-testid^="price-card-"]:not([data-testid$="-book"])'); + +describe('pakketten live uit het CMS', () => { + it('toont eerst de gebakken pakketten en daarna het antwoord van het CMS', async () => { + const { page } = await openPage(server.origin + '/', { + prepare: mock(200, answer('€ 200')), + }); + await waitForHydration(page); + await eventually(() => cards(page).count()).toBe(1); + expect(await cards(page).first().textContent()).toContain('€\u00a0200'); + }); + + it('past ook de keuze in het formulier aan', async () => { + const { page } = await openPage( + server.origin + '/contact?pakket=newborn', + { prepare: mock(200, answer('€ 200')) }, + ); + await waitForHydration(page); + await eventually(() => + page.getByTestId('contact-form-shoot').locator('option').count(), + ).toBe(3); // Kies een optie, Newborn, Overig + }); + + it.each([ + ['een fout', mock(500)], + ['geen gegevens (204)', mock(204)], + ['een ongeldig antwoord', mock(200, { error: 'x' })], + ['een lijst zonder geldig pakket', mock(200, answer('op aanvraag'))], + ])('houdt de gebakken pakketten bij %s', async (_name, prepare) => { + const { page, messages } = await openPage(server.origin + '/', { + prepare, + }); + await waitForHydration(page); + await page.waitForTimeout(800); + expect(await cards(page).count()).toBe(3); + expect(messages.filter((m) => !m.includes('500'))).toEqual([]); + }); +}); diff --git a/web/src/components/PackagesProvider/PackagesProvider.test.tsx b/web/src/components/PackagesProvider/PackagesProvider.test.tsx new file mode 100644 index 0000000..fa9cc36 --- /dev/null +++ b/web/src/components/PackagesProvider/PackagesProvider.test.tsx @@ -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 ( + <> +
    + {usePackages().map((pkg) => ( +
  • {`${pkg.name} ${pkg.price}`}
  • + ))} +
+

{banner ? banner.title : 'geen banner'}

+ + ); +} + +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( + + + , + ); + // 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(); + 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( + + + , + ); + expect(signals).toHaveLength(2); + expect(signals.every((signal) => !signal.aborted)).toBe(true); + view.unmount(); + expect(signals.every((signal) => signal.aborted)).toBe(true); + }); +}); diff --git a/web/src/components/PackagesProvider/PackagesProvider.tsx b/web/src/components/PackagesProvider/PackagesProvider.tsx new file mode 100644 index 0000000..74e90c4 --- /dev/null +++ b/web/src/components/PackagesProvider/PackagesProvider.tsx @@ -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; + +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(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(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) => + 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 ( + {children} + ); +} diff --git a/web/src/components/home/Pricing/PriceBanner.tsx b/web/src/components/home/Pricing/PriceBanner.tsx index 157f700..6ecce66 100644 --- a/web/src/components/home/Pricing/PriceBanner.tsx +++ b/web/src/components/home/Pricing/PriceBanner.tsx @@ -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" > @@ -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} - {banner.description && ( - - {banner.description} + {banner.text && ( + + {banner.text} )} - {banner.features.length > 0 && ( - - {banner.features.map((feature) => ( - {feature} - ))} - - )} - - {banner.priceText && ( - - {banner.priceText} - - )} - {banner.priceNote && ( - - {banner.priceNote} - - )} + {banner.link && ( - - {banner.ctaLabel ?? 'Neem contact op'} - + + {banner.link.label} + - + )} ); } diff --git a/web/src/components/home/Pricing/Pricing.test.tsx b/web/src/components/home/Pricing/Pricing.test.tsx index 6344547..fcb47da 100644 --- a/web/src/components/home/Pricing/Pricing.test.tsx +++ b/web/src/components/home/Pricing/Pricing.test.tsx @@ -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( , @@ -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( , + ); + 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( + , ); 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(); }); diff --git a/web/src/content/types.ts b/web/src/content/types.ts index 95ce0f2..88be7fc 100644 --- a/web/src/content/types.ts +++ b/web/src/content/types.ts @@ -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 diff --git a/web/config/offerings.test.ts b/web/src/lib/offerings.test.ts similarity index 67% rename from web/config/offerings.test.ts rename to web/src/lib/offerings.test.ts index 739d3e0..a09df87 100644 --- a/web/config/offerings.test.ts +++ b/web/src/lib/offerings.test.ts @@ -1,6 +1,11 @@ import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; -import { mapOfferings, parsePriceText } from './offerings'; +import { + isSafeBannerUrl, + mapBanner, + mapOfferings, + parsePriceText, +} from './offerings'; const card = (over: Record = {}) => ({ id: 'x', @@ -70,59 +75,6 @@ describe('mapOfferings', () => { priceNote: 'incl. galerij', ctaLabel: 'Boek', }); - expect(result?.banner).toBeNull(); - }); - - it('houdt de banner buiten de pakketten en neemt de eerste bruikbare', () => { - const result = mapOfferings([ - card(), - card({ - slug: 'actie', - title: 'Kerstactie', - price: '€ 99 i.p.v. € 150', - layout: 'banner', - displayOrder: 9, - }), - card({ - slug: 'actie2', - title: 'Tweede', - layout: 'banner', - displayOrder: 10, - }), - ]); - expect(result?.packages.map((p) => p.id)).toEqual(['newborn']); - expect(result?.banner).toMatchObject({ - title: 'Kerstactie', - priceText: '€ 99 i.p.v. € 150', - }); - }); - - it('neemt een banner met alleen een titel; lege velden blijven leeg', () => { - const result = mapOfferings([ - card(), - card({ - slug: 'actie', - title: 'Past er niets bij?', - description: '', - price: '', - priceNote: '', - ctaLabel: '', - features: [], - layout: 'banner', - }), - ]); - expect(result?.banner).toEqual({ - title: 'Past er niets bij?', - description: undefined, - priceText: undefined, - priceNote: undefined, - features: [], - ctaLabel: undefined, - }); - expect( - mapOfferings([card(), card({ title: ' ', layout: 'banner' })]) - ?.banner, - ).toBeNull(); }); it('slaat ongeldige kaarten over en behoudt de rest', () => { @@ -142,7 +94,6 @@ describe('mapOfferings', () => { it('verwerpt een antwoord zonder geldig pakket', () => { expect(mapOfferings([])).toBeNull(); expect(mapOfferings([card({ price: '' })])).toBeNull(); - expect(mapOfferings([card({ layout: 'banner' })])).toBeNull(); expect(mapOfferings({ items: [] })).toBeNull(); expect(mapOfferings(null)).toBeNull(); expect(mapOfferings('fout')).toBeNull(); @@ -161,3 +112,60 @@ describe('mapOfferings', () => { ); }); }); + +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)); +}); diff --git a/web/config/offerings.ts b/web/src/lib/offerings.ts similarity index 70% rename from web/config/offerings.ts rename to web/src/lib/offerings.ts index f65ebd5..53710e0 100644 --- a/web/config/offerings.ts +++ b/web/src/lib/offerings.ts @@ -1,5 +1,5 @@ // Turns the answer of GET /api/v1/offerings (the CMS) into what the site -// shows: the shoot packages (cards) and at most one banner. Pure functions, so +// 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). // @@ -19,14 +19,12 @@ export interface OfferingPackage { featured?: boolean; } -// Only the title is required: the banner hides every field that is empty +// 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; - description?: string; - priceText?: string; - priceNote?: string; - features: string[]; - ctaLabel?: string; + text?: string; + link?: { label: string; url: string }; } export interface SiteOfferings { @@ -86,16 +84,35 @@ function toPackage(raw: RawOffering): OfferingPackage | null { }; } -function toBanner(raw: RawOffering): OfferingBanner | null { - const title = asText(raw.title); +// 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, - description: asText(raw.description), - priceText: asText(raw.price), - priceNote: asText(raw.priceNote), - features: asFeatures(raw.features) ?? [], - ctaLabel: asText(raw.ctaLabel), + text: asText(answer.text), + link: label && url && isSafeBannerUrl(url) ? { label, url } : undefined, }; } @@ -103,7 +120,9 @@ 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): SiteOfferings | null { +export function mapOfferings( + answer: unknown, +): { packages: OfferingPackage[] } | null { if (!Array.isArray(answer)) return null; const rows = answer .filter(isObject) @@ -113,17 +132,11 @@ export function mapOfferings(answer: unknown): SiteOfferings | null { const seen = new Set(); const packages: OfferingPackage[] = []; - let banner: OfferingBanner | null = null; for (const raw of rows) { - if (raw.layout === 'banner') { - // The CMS allows one banner per site; the first usable one wins - banner ??= toBanner(raw); - continue; - } const pkg = toPackage(raw); if (!pkg || seen.has(pkg.id)) continue; seen.add(pkg.id); packages.push(pkg); } - return packages.length > 0 ? { packages, banner } : null; + return packages.length > 0 ? { packages } : null; } diff --git a/web/src/routes/__root.tsx b/web/src/routes/__root.tsx index 4fa1864..45363f9 100644 --- a/web/src/routes/__root.tsx +++ b/web/src/routes/__root.tsx @@ -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 = () => ( - <> + - + ); export const Route = createRootRoute({ diff --git a/web/src/routes/contact.tsx b/web/src/routes/contact.tsx index 6c9f183..2d4ac21 100644 --- a/web/src/routes/contact.tsx +++ b/web/src/routes/contact.tsx @@ -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) diff --git a/web/src/routes/index.tsx b/web/src/routes/index.tsx index 6fea5a4..62d4ec0 100644 --- a/web/src/routes/index.tsx +++ b/web/src/routes/index.tsx @@ -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) diff --git a/web/src/routes/soorten-fotoshoots/-useShootPageSources.ts b/web/src/routes/soorten-fotoshoots/-useShootPageSources.ts new file mode 100644 index 0000000..e1205a2 --- /dev/null +++ b/web/src/routes/soorten-fotoshoots/-useShootPageSources.ts @@ -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]); +} diff --git a/web/src/routes/soorten-fotoshoots/gezin.tsx b/web/src/routes/soorten-fotoshoots/gezin.tsx index 9cc9251..3b808ea 100644 --- a/web/src/routes/soorten-fotoshoots/gezin.tsx +++ b/web/src/routes/soorten-fotoshoots/gezin.tsx @@ -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 ; return ( <> diff --git a/web/src/routes/soorten-fotoshoots/index.tsx b/web/src/routes/soorten-fotoshoots/index.tsx index 2e00b29..948d625 100644 --- a/web/src/routes/soorten-fotoshoots/index.tsx +++ b/web/src/routes/soorten-fotoshoots/index.tsx @@ -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 ( <> diff --git a/web/src/routes/soorten-fotoshoots/loveshoot.tsx b/web/src/routes/soorten-fotoshoots/loveshoot.tsx index c86f5f6..83b8530 100644 --- a/web/src/routes/soorten-fotoshoots/loveshoot.tsx +++ b/web/src/routes/soorten-fotoshoots/loveshoot.tsx @@ -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 ; return ( <> diff --git a/web/src/routes/soorten-fotoshoots/newborn.tsx b/web/src/routes/soorten-fotoshoots/newborn.tsx index 863694e..27af600 100644 --- a/web/src/routes/soorten-fotoshoots/newborn.tsx +++ b/web/src/routes/soorten-fotoshoots/newborn.tsx @@ -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 ; return ( <> diff --git a/web/src/routes/soorten-fotoshoots/portret.tsx b/web/src/routes/soorten-fotoshoots/portret.tsx index 607c3b2..5b0772e 100644 --- a/web/src/routes/soorten-fotoshoots/portret.tsx +++ b/web/src/routes/soorten-fotoshoots/portret.tsx @@ -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 ; return ( <> diff --git a/web/src/routes/soorten-fotoshoots/zwangerschap.tsx b/web/src/routes/soorten-fotoshoots/zwangerschap.tsx index 754ecbe..51b3dba 100644 --- a/web/src/routes/soorten-fotoshoots/zwangerschap.tsx +++ b/web/src/routes/soorten-fotoshoots/zwangerschap.tsx @@ -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 ; return ( <>