Adds the shoot page layout and the shoot-type submenu

Shoot pages follow design E: breadcrumb, story blocks, process
timeline with icons, photo mosaic, FAQ, package block and booking
call to action, with per-shoot OG images. The navigation gets a
"Soorten fotoshoots" submenu (desktop panel, mobile group) built from
shootTypes, with exact current-page matching in menu, footer and
breadcrumb. A 404 under /soorten-fotoshoots/ also offers a link back
to the overview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 14:43:43 +01:00
co-authored by Claude Opus 5.5
parent e5f4348178
commit 7af2069959
84 changed files with 6090 additions and 128 deletions
+5 -2
View File
@@ -516,10 +516,13 @@ describe('shoot pages', () => {
expect(
document.head.querySelector('link[rel="canonical"]'),
).toHaveAttribute('href', `${siteUrl}${path}`);
// The default image until unit 2 gives the pages their own
// Each shoot page has its own preview image from the registry
expect(
document.head.querySelector('meta[property="og:image"]'),
).toHaveAttribute('content', `${siteUrl}/og-image.jpg`);
).toHaveAttribute(
'content',
`${siteUrl}${sitePages[path].ogImage!.path}`,
);
expect(document.head.querySelector('meta[name="robots"]')).toBeNull();
const data = structuredData();
@@ -0,0 +1,97 @@
import { screen, within } from '@testing-library/react';
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { cleanup } from '@testing-library/react';
import type { BreadcrumbItem } from '@/lib/shootPageView';
import { axeResults } from '@/test/axe';
import { knownRoutePath } from '@/test/arbitraries';
import { renderWithProviders } from '@/test/renderWithProviders';
import Breadcrumb from './Breadcrumb';
const three: BreadcrumbItem[] = [
{ label: 'Home', to: '/' },
{ label: 'Soorten fotoshoots', to: '/soorten-fotoshoots' },
{ label: 'Newborn', to: '/soorten-fotoshoots/newborn' },
];
describe('Breadcrumb', () => {
it('shows links for all but the last item, which is the current page', async () => {
const { container } = await renderWithProviders(
<Breadcrumb label="Kruimelpad" items={three} data-testid="crumb" />,
{ path: '/soorten-fotoshoots/newborn' },
);
const nav = screen.getByRole('navigation', { name: 'Kruimelpad' });
expect(nav).toBe(screen.getByTestId('crumb'));
expect(within(nav).getAllByRole('link')).toHaveLength(2);
expect(screen.getByRole('link', { name: 'Home' })).toHaveAttribute(
'href',
'/',
);
expect(
screen.getByRole('link', { name: 'Soorten fotoshoots' }),
).toHaveAttribute('href', '/soorten-fotoshoots');
const current = screen.getByText('Newborn');
expect(current.tagName).toBe('SPAN');
expect(current).toHaveAttribute('aria-current', 'page');
expect(nav.querySelectorAll('[aria-current]')).toHaveLength(1);
expect(nav.querySelectorAll('li[aria-hidden="true"]')).toHaveLength(2);
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows only the current page for one item', async () => {
await renderWithProviders(
<Breadcrumb label="Kruimelpad" items={three.slice(2)} />,
);
expect(screen.queryByRole('link')).toBeNull();
expect(screen.getByText('Newborn')).toHaveAttribute(
'aria-current',
'page',
);
expect(
document.querySelectorAll('li[aria-hidden="true"]'),
).toHaveLength(0);
});
it('renders nothing without items', async () => {
const { container } = await renderWithProviders(
<Breadcrumb label="Kruimelpad" items={[]} />,
);
expect(screen.queryByRole('navigation')).toBeNull();
expect(container.querySelector('ol')).toBeNull();
});
it('marks only the last item as current, and the links are not current on their own page (invariant)', async () => {
const items = fc.uniqueArray(
fc.record({
label: fc
.string({ minLength: 1, maxLength: 12 })
.filter((text) => text.trim() !== ''),
to: knownRoutePath,
}),
{ selector: (item) => item.to, minLength: 1, maxLength: 5 },
);
const samples = fc.sample(items, { numRuns: 8 });
for (const sample of samples) {
const { container } = await renderWithProviders(
<Breadcrumb label="Kruimelpad" items={sample} />,
{ path: sample[sample.length - 1].to },
);
const entries = [...container.querySelectorAll('ol > li')].filter(
(li) => li.getAttribute('aria-hidden') !== 'true',
);
expect(entries).toHaveLength(sample.length);
entries.forEach((li, index) => {
const last = index === sample.length - 1;
expect(li.querySelectorAll('a')).toHaveLength(last ? 0 : 1);
expect(
li.querySelectorAll('[aria-current="page"]').length,
).toBe(last ? 1 : 0);
expect(li.textContent).toBe(sample[index].label);
});
expect(
container.querySelectorAll('li[aria-hidden="true"]'),
).toHaveLength(sample.length - 1);
cleanup();
}
});
});
@@ -0,0 +1,80 @@
import { Fragment } from 'react';
import { Box, Flex, Text } from '@chakra-ui/react';
import RouterLink from '@/components/RouterLink';
import type { BreadcrumbItem } from '@/lib/shootPageView';
type BreadcrumbProps = {
// The name of the navigation landmark, e.g. "Kruimelpad"
label: string;
// The last item is the page itself
items: readonly BreadcrumbItem[];
'data-testid'?: string;
};
// The path to the current page (BR-SP-01..04): links for every item but the
// last, which is plain text marked as the current page. The links match
// exactly, so only the page itself can ever be "current".
export default function Breadcrumb({
label,
items,
'data-testid': testId,
}: BreadcrumbProps) {
if (items.length === 0) return null;
return (
<Box as="nav" aria-label={label} data-testid={testId}>
<Flex
as="ol"
wrap="wrap"
justify="center"
align="center"
gap={2}
fontSize="0.875rem"
color="ink.soft"
listStyle="none"
m={0}
p={0}
>
{items.map((item, index) => {
const last = index === items.length - 1;
// The list is static, so the index is a stable key
return (
<Fragment key={index}>
<Box as="li">
{last ? (
<Text
as="span"
aria-current="page"
color="ink"
minH="2.75rem"
display="inline-flex"
alignItems="center"
>
{item.label}
</Text>
) : (
<RouterLink
to={item.to}
activeOptions={{ exact: true }}
color="accent.deep"
textDecoration="underline"
minH="2.75rem"
display="inline-flex"
alignItems="center"
>
{item.label}
</RouterLink>
)}
</Box>
{!last && (
<Box as="li" aria-hidden="true">
/
</Box>
)}
</Fragment>
);
})}
</Flex>
</Box>
);
}
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import LinkButton from '@/components/LinkButton';
import RichParagraph from '@/components/RichParagraph/RichParagraph';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import CallToAction from './CallToAction';
@@ -66,4 +67,28 @@ describe('CallToAction', () => {
);
expect(screen.queryByRole('paragraph')).toBeNull();
});
it('takes the alt tone by default and the given tone otherwise', async () => {
const { unmount } = await renderWithProviders(
<CallToAction title="Vragen?" titleId="q" data-testid="cta">
<LinkButton to="/">Contact</LinkButton>
</CallToAction>,
);
const rules = (testId: string) =>
cssRulesFor(screen.getByTestId(testId)).join();
expect(rules('cta')).toContain('var(--slp-colors-paper-alt)');
unmount();
await renderWithProviders(
<CallToAction
title="Vragen?"
titleId="q"
tone="paper"
data-testid="cta"
>
<LinkButton to="/">Contact</LinkButton>
</CallToAction>,
);
expect(rules('cta')).not.toContain('var(--slp-colors-paper-alt)');
});
});
@@ -9,6 +9,8 @@ type CallToActionProps = {
titleId: string;
// Plain text, or a paragraph with links in it (e.g. RichParagraph)
lead?: ReactNode;
// Band colour; alt unless the page needs it to differ from the band above
tone?: 'paper' | 'alt';
'data-testid'?: string;
// The action below the text, e.g. a LinkButton
children: ReactNode;
@@ -16,18 +18,19 @@ type CallToActionProps = {
// Closing block of a page (design .section--alt.section--tight with a narrow,
// centred column): a heading, a short lead and one action. The page chooses
// the action and any link in the lead.
// the action, any link in the lead and, when needed, the band colour.
export default function CallToAction({
title,
titleId,
lead,
tone = 'alt',
'data-testid': testId,
children,
}: CallToActionProps) {
return (
<PageSection
labelledBy={titleId}
tone="alt"
tone={tone}
width="narrow"
spacing="tight"
data-testid={testId}
+101
View File
@@ -0,0 +1,101 @@
import { cleanup, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import type { FaqItem } from '@/content/types';
import { faqItems } from '@/test/arbitraries';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import FaqList from './FaqList';
const items: FaqItem[] = [
{
id: 'een',
question: 'Wanneer boek ik?',
answer: [
'Zo vroeg mogelijk, zie ',
{ text: 'de prijzen', to: '/', hash: 'prijzen' },
'.',
],
},
{ id: 'twee', question: 'Waar?', answer: ['Bij jullie thuis.'] },
{ id: 'drie', question: 'Hoe lang?', answer: ['Twee uur.'] },
];
describe('FaqList', () => {
it('shows every question closed, with the answers in the page', async () => {
const { container } = await renderWithProviders(
<FaqList items={items} data-testid="faq" />,
);
const details = container.querySelectorAll('details');
expect(details).toHaveLength(3);
for (const item of details) expect(item).not.toHaveAttribute('open');
for (const item of items) {
expect(screen.getByText(item.question).tagName).toBe('SUMMARY');
}
expect(
screen.getByText('Bij jullie thuis.', { exact: false }),
).toBeInTheDocument();
expect(
screen.getByRole('link', { name: 'de prijzen' }),
).toHaveAttribute('href', '/#prijzen');
// The questions are labels, not headings
expect(screen.queryByRole('heading')).toBeNull();
expect(
container.querySelectorAll('summary svg[aria-hidden="true"]'),
).toHaveLength(3);
expect(await axeResults(container)).toHaveNoViolations();
});
// jsdom does not turn Enter or Space on a summary into the click that
// opens the details (browsers do, for any summary that is the first
// child of its details), and user-event only does so for buttons and
// links. So the test checks what the page controls: the summary is
// focusable and is the first child of its details, and activating it
// (the click a browser sends) toggles the item.
it('has a focusable summary as first child, which toggles the item when activated', async () => {
const user = userEvent.setup();
const { container } = await renderWithProviders(
<FaqList items={items} />,
);
const first = container.querySelector('details')!;
const summary = first.firstElementChild as HTMLElement;
expect(summary.tagName).toBe('SUMMARY');
expect(summary).toHaveTextContent('Wanneer boek ik?');
expect(summary.getAttribute('tabindex')).not.toBe('-1');
await user.tab();
expect(summary).toHaveFocus();
await user.click(summary);
expect(first).toHaveAttribute('open');
await user.click(summary);
expect(first).not.toHaveAttribute('open');
});
it('renders nothing without questions', async () => {
const { container } = await renderWithProviders(<FaqList items={[]} />);
expect(container.querySelector('details')).toBeNull();
});
it('has one closed details per item, with every answer in the page (invariant)', async () => {
for (const sample of fc.sample(faqItems, { numRuns: 6 })) {
const { container } = await renderWithProviders(
<FaqList items={sample} />,
);
const details = container.querySelectorAll('details');
expect(details).toHaveLength(sample.length);
details.forEach((item, index) => {
expect(item.hasAttribute('open')).toBe(false);
expect(item.querySelector('summary')!.textContent).toBe(
sample[index].question,
);
const answer = sample[index].answer
.map((piece) =>
typeof piece === 'string' ? piece : piece.text,
)
.join('');
expect(item.querySelector('p')!.textContent).toBe(answer);
});
cleanup();
}
});
});
+82
View File
@@ -0,0 +1,82 @@
import { Box, chakra } from '@chakra-ui/react';
import RichParagraph from '@/components/RichParagraph/RichParagraph';
import type { FaqItem } from '@/content/types';
type FaqListProps = {
items: readonly FaqItem[];
'data-testid'?: string;
};
// The plus that turns into a minus while its item is open: the vertical
// stroke is hidden by CSS under details[open]. Decoration only.
function ToggleIcon() {
return (
<chakra.svg
aria-hidden="true"
focusable="false"
viewBox="0 0 24 24"
w="1.25rem"
h="1.25rem"
flexShrink={0}
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
>
<path d="M5 12h14" />
<path data-faq-vertical d="M12 5v14" />
</chakra.svg>
);
}
// The questions of a shoot page (FR-ST-06, BR-SP-50..52): one native
// details element per question, so it works without JavaScript and by
// keyboard. All items start closed; the answers are in the page either way.
// The browser keeps track of what is open, there is no state here.
export default function FaqList({
items,
'data-testid': testId,
}: FaqListProps) {
if (items.length === 0) return null;
return (
<Box borderTopWidth="1px" borderColor="sand" data-testid={testId}>
{items.map((item) => (
<Box
as="details"
key={item.id}
borderBottomWidth="1px"
borderColor="sand"
css={{
'&[open] [data-faq-vertical]': { display: 'none' },
}}
>
<Box
as="summary"
display="flex"
alignItems="center"
justifyContent="space-between"
gap={4}
minH="2.75rem"
py={5}
fontFamily="heading"
fontSize="1.25rem"
color="ink"
cursor="pointer"
listStyle="none"
css={{
'&::-webkit-details-marker': { display: 'none' },
}}
_focusVisible={{ outlineOffset: '2px' }}
>
{item.question}
<ToggleIcon />
</Box>
<Box mb={6} maxW="680px" color="ink.soft">
<RichParagraph paragraph={item.answer} />
</Box>
</Box>
))}
</Box>
);
}
+38
View File
@@ -77,6 +77,44 @@ describe('Footer', () => {
expect(links[1]).not.toHaveAttribute('aria-current');
});
it('markeert op een shootpagina geen footerlink (exact)', async () => {
await renderFooter(siteContent, '/soorten-fotoshoots/newborn');
const nav = screen.getByRole('navigation', { name: 'Footermenu' });
for (const link of within(nav).getAllByRole('link')) {
expect(link).not.toHaveAttribute('aria-current');
}
});
it.each(['/soorten-fotoshoots', '/soorten-fotoshoots/'])(
'markeert Soorten fotoshoots op %s',
async (path) => {
await renderFooter(siteContent, path);
const nav = screen.getByRole('navigation', { name: 'Footermenu' });
expect(
within(nav).getByRole('link', { name: 'Soorten fotoshoots' }),
).toHaveAttribute('aria-current', 'page');
expect(
within(nav).getByRole('link', { name: 'Portfolio' }),
).not.toHaveAttribute('aria-current');
},
);
it('markeert Portfolio ook met een query in de URL', async () => {
await renderFooter(siteContent, '/portfolio?shoot=newborn');
const nav = screen.getByRole('navigation', { name: 'Footermenu' });
expect(
within(nav).getByRole('link', { name: 'Portfolio' }),
).toHaveAttribute('aria-current', 'page');
});
it('blijft zonder axe-fouten op een shootpagina', async () => {
const { container } = await renderFooter(
siteContent,
'/soorten-fotoshoots/newborn',
);
expect(await axeResults(container)).toHaveNoViolations();
});
it('laat lege kolommen weg', async () => {
await renderFooter({
...siteContent,
+6
View File
@@ -138,6 +138,12 @@ export default function Footer({ content }: FooterProps) {
<FooterLink asChild>
<RouterLink
to={item.to}
// Exact, also with a query: on a shoot page the
// overview link is not the current page
activeOptions={{
exact: true,
includeSearch: false,
}}
data-testid={`footer-nav-${item.to.slice(1)}`}
>
{item.label}
@@ -167,4 +167,23 @@ describe('MediaText', () => {
);
expect(await axeResults(container)).toHaveNoViolations();
});
it('keeps a medium photo at most 30rem wide and lays out like small', async () => {
await renderWithProviders(
<MediaText image={image} aspectRatio="4 / 5" mediaSize="medium">
<h2>Newborn</h2>
</MediaText>,
);
expect(gridRules()).toMatch(
/grid-template-columns: minmax\(0, ?30rem\) minmax\(0, ?1fr\)/,
);
expect(cssRulesFor(photoColumnElement()).join()).toContain(
'max-width: 30rem',
);
const textRules = cssRulesFor(
screen.getByRole('heading').closest('[data-reveal]')!,
).join();
expect(textRules).toContain('max-width: 36rem');
expect(textRules).toMatch(/min-width: 64rem.*margin-inline: auto/s);
});
});
+13 -4
View File
@@ -9,6 +9,8 @@ import type { ContentImage, FrameColor } from '@/content/types';
// alone, or the photo with a detail photo overlapping it
const SMALL_MEDIA = '20rem';
const SMALL_MEDIA_WITH_DETAIL = '28rem';
// Widest a medium photo column gets (a portrait photo on a shoot page)
const MEDIUM_MEDIA = '30rem';
// Widest the text next to a small photo gets: about 70 characters a line
const SMALL_TEXT = '36rem';
@@ -23,8 +25,9 @@ type MediaTextProps = {
reverse?: boolean;
// half: photo and text share the width equally (design .about);
// small: the photo column stays narrow (20rem, 28rem with a detail
// photo); the text, at most 36rem, is centred in the rest
mediaSize?: 'half' | 'small';
// photo); the text, at most 36rem, is centred in the rest;
// medium: laid out like small, with a photo column up to 30rem
mediaSize?: 'half' | 'small' | 'medium';
// A smaller square photo overlapping the main one's lower right corner
detailImage?: ContentImage;
// Colour of the block behind the photo (FramedImage)
@@ -48,8 +51,14 @@ export default function MediaText({
'data-testid': testId,
children,
}: MediaTextProps) {
const small = mediaSize === 'small';
const mediaWidth = detailImage ? SMALL_MEDIA_WITH_DETAIL : SMALL_MEDIA;
// medium shares the layout of small, with a wider photo column
const small = mediaSize !== 'half';
const mediaWidth =
mediaSize === 'medium'
? MEDIUM_MEDIA
: detailImage
? SMALL_MEDIA_WITH_DETAIL
: SMALL_MEDIA;
const media = `minmax(0, ${mediaWidth})`;
const columns = small
? reverse
@@ -0,0 +1,28 @@
import { chakra } from '@chakra-ui/react';
// A small chevron for the submenu toggles. Decorative: the button carries the
// name and aria-expanded. It turns upside down while its button has
// `data-open`; with reduced motion it jumps instead of turning (BR-NAV-42).
export default function ChevronIcon() {
return (
<chakra.svg
viewBox="0 0 12 12"
width="12px"
height="12px"
aria-hidden="true"
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
transitionProperty="transform"
transitionDuration="swap"
transitionTimingFunction="smooth"
_motionReduce={{ transition: 'none' }}
css={{ '[data-open] > &': { transform: 'rotate(180deg)' } }}
>
<path d="M2 4.25 6 8l4-3.75" />
</chakra.svg>
);
}
@@ -0,0 +1,177 @@
import { screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { mockViewport } from '@/test/navViewport';
import { renderWithProviders } from '@/test/renderWithProviders';
import NavigationBar from './NavigationBar';
const GROUP = 'Submenu Soorten fotoshoots';
// The mobile layout (below lg) through the whole navigation bar
async function renderMobile(path = '/contact') {
mockViewport(375);
const result = await renderWithProviders(<NavigationBar />, { path });
return { ...result, user: userEvent.setup() };
}
const hamburger = () => screen.getByTestId('nav-menu-toggle');
const menu = () => document.getElementById('mobile-nav')!;
const inMenu = () => within(menu());
const groupToggle = () => inMenu().getByRole('button', { name: GROUP });
const subLinks = () => ['Newborn', 'Zwangerschap', 'Gezin'];
async function openMenu(path?: string) {
const rendered = await renderMobile(path);
await rendered.user.click(hamburger());
return rendered;
}
describe('MobileNav', () => {
it('opens with the hamburger and shows the main items', async () => {
await openMenu();
expect(hamburger()).toHaveAttribute('aria-expanded', 'true');
expect(hamburger()).toHaveAccessibleName('Menu sluiten');
for (const name of ['Home', 'Over mij', 'Portfolio', 'Contact']) {
expect(inMenu().getByRole('link', { name })).toBeVisible();
}
});
it('keeps the menu out of reach while closed', async () => {
await renderMobile();
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
expect(
within(menu()).queryByRole('link', { name: 'Contact' }),
).toBeNull();
});
it('starts with the group collapsed outside the section (BR-NAV-31)', async () => {
await openMenu('/contact');
expect(groupToggle()).toHaveAttribute('aria-expanded', 'false');
});
it.each(['/soorten-fotoshoots', '/soorten-fotoshoots/gezin'])(
'starts with the group expanded on %s (BR-NAV-31)',
async (path) => {
await openMenu(path);
expect(groupToggle()).toHaveAttribute('aria-expanded', 'true');
for (const name of subLinks()) {
expect(inMenu().getByRole('link', { name })).toBeVisible();
}
},
);
it('flips the group with the chevron and hides collapsed links (BR-NAV-36)', async () => {
const { user } = await openMenu('/contact');
expect(groupToggle()).toHaveAttribute(
'aria-controls',
'mobile-group-soorten-fotoshoots',
);
for (const name of subLinks()) {
expect(inMenu().queryByRole('link', { name })).toBeNull();
}
await user.click(groupToggle());
expect(groupToggle()).toHaveAttribute('aria-expanded', 'true');
for (const name of subLinks()) {
expect(inMenu().getByRole('link', { name })).toBeVisible();
}
await user.click(groupToggle());
expect(groupToggle()).toHaveAttribute('aria-expanded', 'false');
expect(inMenu().queryByRole('link', { name: 'Gezin' })).toBeNull();
});
it('is not reached by Tab while the group is collapsed', async () => {
const { user } = await openMenu('/contact');
const reached: string[] = [];
for (let i = 0; i < 10; i += 1) {
await user.tab();
reached.push(document.activeElement?.textContent ?? '');
}
for (const name of subLinks()) expect(reached).not.toContain(name);
});
it.each(['Contact', 'Soorten fotoshoots'])(
'closes the whole menu when %s is chosen (BR-NAV-32)',
async (name) => {
const { user } = await openMenu('/contact');
await user.click(inMenu().getByRole('link', { name }));
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
expect(hamburger()).toHaveAccessibleName('Menu openen');
},
);
it('closes the whole menu when a sub-link is chosen', async () => {
const { user } = await openMenu('/soorten-fotoshoots');
await user.click(inMenu().getByRole('link', { name: 'Gezin' }));
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
});
it('closes with the hamburger itself', async () => {
const { user } = await openMenu();
await user.click(hamburger());
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
});
it('closes with Escape and puts the focus on the hamburger (BR-NAV-33)', async () => {
const { user } = await openMenu();
inMenu().getByRole('link', { name: 'Portfolio' }).focus();
await user.keyboard('{Escape}');
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
expect(hamburger()).toHaveFocus();
});
it('also returns the focus to the hamburger when Escape is pressed on it', async () => {
const { user } = await openMenu();
expect(hamburger()).toHaveFocus();
await user.keyboard('{Escape}');
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
expect(hamburger()).toHaveFocus();
});
it('does not move the focus on Escape when it was elsewhere', async () => {
const { user } = await openMenu();
(document.activeElement as HTMLElement).blur();
await user.keyboard('{Escape}');
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
expect(hamburger()).not.toHaveFocus();
});
it('scrolls inside the screen and centres short content (BR-NAV-34)', async () => {
await openMenu();
expect(getComputedStyle(menu()).overflowY).toBe('auto');
const rules = cssRulesFor(menu()).join('\n');
expect(rules).toContain('overscroll-behavior');
const centring = menu().firstElementChild!;
expect(cssRulesFor(centring).join('\n')).toContain('margin-block');
expect(centring.querySelector('nav')).not.toBeNull();
});
it('locks the page behind it while open and restores it after', async () => {
const { user } = await openMenu();
expect(document.body.style.overflow).toBe('hidden');
await user.click(hamburger());
expect(document.body.style.overflow).toBe('');
});
it('has no axe violations open, collapsed and expanded', async () => {
const { container, user } = await openMenu('/contact');
expect(await axeResults(container)).toHaveNoViolations();
await user.click(groupToggle());
expect(await axeResults(container)).toHaveNoViolations();
});
it('removes the transitions with reduced motion (BR-NAV-42)', async () => {
await openMenu('/soorten-fotoshoots');
const group = document.getElementById(
'mobile-group-soorten-fotoshoots',
)!;
for (const element of [menu(), group]) {
const rules = cssRulesFor(element).join('\n');
expect(rules).toContain('prefers-reduced-motion: reduce');
expect(rules).toContain('transition: none');
}
});
});
+68 -27
View File
@@ -1,22 +1,43 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import { Box, Stack } from '@chakra-ui/react';
import { mainNav } from '@/navigation';
import type { NavMenuEvent } from '@/lib/navMenuState';
import { hasChildren, mainNav } from '@/navigation';
import RouterLink from '../RouterLink';
import MobileNavGroup from './MobileNavGroup';
type MobileNavProps = {
id: string;
open: boolean;
onClose: () => void;
// The sub-list of the item with children is expanded
groupOpen: boolean;
pathname: string;
dispatch: (event: NavMenuEvent) => void;
};
// Menu onder de navigatiebalk op mobiel, vult de rest van het scherm
export default function MobileNav({ id, open, onClose }: MobileNavProps) {
// Pagina eronder niet laten scrollen, en sluiten met Escape
export default function MobileNav({
id,
open,
groupOpen,
pathname,
dispatch,
}: MobileNavProps) {
const box = useRef<HTMLDivElement>(null);
// Pagina eronder niet laten scrollen, en sluiten met Escape. De focus gaat
// terug naar de hamburger als die in het menu of op de hamburger stond
// (de hamburger herken je aan aria-controls naar dit menu).
useEffect(() => {
if (!open) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') onClose();
if (event.key !== 'Escape') return;
const active = document.activeElement;
const focusInside =
!!active &&
(!!box.current?.contains(active) ||
active.getAttribute('aria-controls') === id);
dispatch({ type: 'escape', focusInside });
};
document.body.style.overflow = 'hidden';
document.addEventListener('keydown', onKeyDown);
@@ -25,10 +46,11 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) {
document.body.style.overflow = '';
document.removeEventListener('keydown', onKeyDown);
};
}, [open, onClose]);
}, [open, id, dispatch]);
return (
<Box
ref={box}
id={id}
position="fixed"
top="header"
@@ -38,7 +60,9 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) {
zIndex="mobileNav"
display={{ base: 'flex', lg: 'none' }}
flexDirection="column"
justifyContent="center"
// Een hoog menu scrolt binnen het scherm (BR-NAV-34)
overflowY="auto"
overscrollBehavior="contain"
pt={8}
pb={16}
px="gutter"
@@ -49,26 +73,43 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) {
transitionProperty="clip-path, visibility"
transitionDuration="interaction"
transitionTimingFunction="smooth"
_motionReduce={{ transition: 'none' }}
>
<nav aria-label="Mobiel menu">
<Stack as="ul" gap={5} listStyleType="none">
{mainNav.map((item) => (
<li key={item.to}>
<RouterLink
to={item.to}
onClick={onClose}
display="block"
fontFamily="heading"
fontSize="1.9rem"
color="ink"
_currentPage={{ color: 'accent' }}
>
{item.label}
</RouterLink>
</li>
))}
</Stack>
</nav>
{/* Automatische marges centreren een kort menu en laten een hoog
menu bovenaan beginnen (centreren zou de bovenkant afknippen) */}
<Box marginBlock="auto">
<nav aria-label="Mobiel menu">
<Stack as="ul" gap={5} listStyleType="none">
{mainNav.map((item) => (
<li key={item.to}>
{hasChildren(item) ? (
<MobileNavGroup
item={item}
id={`mobile-group-${item.to.slice(1)}`}
open={groupOpen}
pathname={pathname}
dispatch={dispatch}
/>
) : (
<RouterLink
to={item.to}
onClick={() =>
dispatch({ type: 'linkChosen' })
}
display="block"
fontFamily="heading"
fontSize="1.9rem"
color="ink"
_currentPage={{ color: 'accent' }}
>
{item.label}
</RouterLink>
)}
</li>
))}
</Stack>
</nav>
</Box>
</Box>
);
}
@@ -0,0 +1,113 @@
import { Box, chakra, Flex } from '@chakra-ui/react';
import { isSectionCurrent } from '@/lib/navCurrent';
import type { NavMenuEvent } from '@/lib/navMenuState';
import type { NavItem } from '@/navigation';
import RouterLink from '../RouterLink';
import ChevronIcon from './ChevronIcon';
type MobileNavGroupProps = {
item: NavItem & { children: readonly NavItem[] };
// Id of the sub-list, for aria-controls
id: string;
open: boolean;
pathname: string;
dispatch: (event: NavMenuEvent) => void;
};
// Exact: only the page itself is current (BR-NAV-01), also with a query
const exactActive = { exact: true, includeSearch: false } as const;
const duration = '0.3s';
const easing = 'cubic-bezier(.22, .61, .36, 1)';
// The parent row of the mobile menu: the link to the overview, a chevron
// button and an expandable list of sub-pages (BR-NAV-30..36)
export default function MobileNavGroup({
item,
id,
open,
pathname,
dispatch,
}: MobileNavGroupProps) {
return (
<>
<Flex alignItems="center" gap={1}>
<RouterLink
to={item.to}
activeOptions={exactActive}
onClick={() => dispatch({ type: 'linkChosen' })}
display="block"
fontFamily="heading"
fontSize="1.9rem"
color={isSectionCurrent(item, pathname) ? 'accent' : 'ink'}
_currentPage={{ color: 'accent' }}
>
{item.label}
</RouterLink>
<chakra.button
type="button"
aria-expanded={open}
aria-controls={id}
aria-label={`Submenu ${item.label}`}
data-open={open || undefined}
display="flex"
alignItems="center"
justifyContent="center"
// 44px: minimaal klikdoel op touch (BR-NAV-40)
w="44px"
h="44px"
flexShrink={0}
cursor="pointer"
color="ink"
onClick={() => dispatch({ type: 'toggleGroup' })}
>
<ChevronIcon />
</chakra.button>
</Flex>
{/* Grid rows 0fr to 1fr animate the height without measuring. On
close the visibility switches only after the collapse, so the
collapse is seen; collapsed links are neither focusable nor
read (BR-NAV-36). */}
<Box
id={id}
display="grid"
gridTemplateRows={open ? '1fr' : '0fr'}
visibility={open ? 'visible' : 'hidden'}
transition={`grid-template-rows ${duration} ${easing}, visibility 0s linear ${open ? '0s' : duration}`}
_motionReduce={{ transition: 'none' }}
>
<Box overflow="hidden" minH={0}>
<chakra.ul
listStyleType="none"
pl="1.25rem"
pt={2}
display="flex"
flexDirection="column"
>
{item.children.map((child) => (
<li key={child.to}>
<RouterLink
to={child.to}
activeOptions={exactActive}
onClick={() =>
dispatch({ type: 'linkChosen' })
}
display="flex"
alignItems="center"
minH="44px"
fontFamily="heading"
fontSize="1.4rem"
color="ink"
// accent.deep: 1.4rem is not large text
_currentPage={{ color: 'accent.deep' }}
>
{child.label}
</RouterLink>
</li>
))}
</chakra.ul>
</Box>
</Box>
</>
);
}
@@ -0,0 +1,63 @@
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import NavLink from './NavLink';
describe('NavLink', () => {
it('marks the section without aria-current', async () => {
await renderWithProviders(
<NavLink
to="/soorten-fotoshoots"
activeOptions={{ exact: true, includeSearch: false }}
sectionCurrent
>
Soorten
</NavLink>,
{ path: '/soorten-fotoshoots/newborn' },
);
const link = screen.getByRole('link', { name: 'Soorten' });
expect(link).toHaveAttribute('data-section-current');
expect(link).not.toHaveAttribute('aria-current');
});
it('sets no section mark by default or when false', async () => {
await renderWithProviders(
<>
<NavLink to="/portfolio">Plain</NavLink>
<NavLink to="/contact" sectionCurrent={false}>
Off
</NavLink>
</>,
);
for (const name of ['Plain', 'Off']) {
expect(screen.getByRole('link', { name })).not.toHaveAttribute(
'data-section-current',
);
}
});
it('still lets the router set aria-current on the current page', async () => {
await renderWithProviders(
<NavLink to="/portfolio">Portfolio</NavLink>,
{
path: '/portfolio',
},
);
expect(screen.getByRole('link')).toHaveAttribute(
'aria-current',
'page',
);
});
it('draws the underline for the section mark too', async () => {
await renderWithProviders(
<NavLink to="/soorten-fotoshoots" sectionCurrent>
Soorten
</NavLink>,
);
const rules = cssRulesFor(screen.getByRole('link')).join('\n');
expect(rules).toContain('[data-section-current]::after');
expect(rules).toContain('[aria-current="page"]::after');
});
});
+12 -3
View File
@@ -1,8 +1,16 @@
import RouterLink from '../RouterLink';
type NavLinkProps = React.ComponentProps<typeof RouterLink>;
type NavLinkProps = React.ComponentProps<typeof RouterLink> & {
// The page is below this link (a shoot page below the overview): shows
// the same underline as the current page, without aria-current
sectionCurrent?: boolean;
};
export default function NavLink({ children, ...props }: NavLinkProps) {
export default function NavLink({
children,
sectionCurrent,
...props
}: NavLinkProps) {
return (
<RouterLink
textStyle="eyebrow"
@@ -11,6 +19,7 @@ export default function NavLink({ children, ...props }: NavLinkProps) {
display="inline-block"
py="2"
mx="4"
data-section-current={sectionCurrent ? '' : undefined}
css={{
'&::after': {
content: '""',
@@ -26,7 +35,7 @@ export default function NavLink({ children, ...props }: NavLinkProps) {
transitionDuration: 'interaction',
transitionTimingFunction: 'smooth',
},
'&:hover::after, &:focus-visible::after, &[aria-current="page"]::after':
'&:hover::after, &:focus-visible::after, &[aria-current="page"]::after, &[data-section-current]::after':
{
transform: 'scaleX(1)',
transformOrigin: 'left',
@@ -0,0 +1,158 @@
import { createRef } from 'react';
import { fireEvent, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { hasChildren, mainNav } from '@/navigation';
import { renderWithProviders } from '@/test/renderWithProviders';
import NavSubmenu from './NavSubmenu';
const item = mainNav.find(hasChildren)!;
const TOGGLE = 'Submenu Soorten fotoshoots';
// The component alone with a fake dispatch: what it reports, not what the
// reducer does with it
async function renderSubmenu({
open = false,
path = '/',
transparent = false,
} = {}) {
const dispatch = vi.fn();
const toggleRef = createRef<HTMLButtonElement>();
await renderWithProviders(
<>
<NavSubmenu
item={item}
id="submenu-soorten-fotoshoots"
open={open}
pathname={path}
transparent={transparent}
toggleRef={toggleRef}
dispatch={dispatch}
/>
<button>elsewhere</button>
</>,
{ path },
);
return { dispatch, toggleRef, user: userEvent.setup() };
}
const toggle = () => screen.getByRole('button', { name: TOGGLE });
describe('NavSubmenu', () => {
it('renders without errors with the real main menu item', async () => {
await renderSubmenu();
expect(
screen.getByRole('link', { name: 'Soorten fotoshoots' }),
).toHaveAttribute('href', '/soorten-fotoshoots');
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
});
it('passes the toggle element to toggleRef', async () => {
const { toggleRef } = await renderSubmenu();
expect(toggleRef.current).toBe(toggle());
});
it('reflects open in aria-expanded and data-open', async () => {
await renderSubmenu({ open: true });
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
expect(toggle()).toHaveAttribute('data-open');
});
it('reports toggleSubmenu for a click on the toggle', async () => {
const { dispatch, user } = await renderSubmenu();
await user.click(toggle());
expect(dispatch).toHaveBeenCalledExactlyOnceWith({
type: 'toggleSubmenu',
});
});
it('reports linkChosen for a click on a panel link', async () => {
const { dispatch, user } = await renderSubmenu({ open: true });
await user.click(screen.getByRole('link', { name: 'Gezin' }));
expect(dispatch).toHaveBeenCalledExactlyOnceWith({
type: 'linkChosen',
});
});
it('reports escape with focusInside true when focus is in the submenu', async () => {
const { dispatch, user } = await renderSubmenu({ open: true });
toggle().focus();
await user.keyboard('{Escape}');
expect(dispatch).toHaveBeenCalledExactlyOnceWith({
type: 'escape',
focusInside: true,
});
});
it('reports escape with focusInside false when focus is elsewhere', async () => {
const { dispatch, user } = await renderSubmenu({ open: true });
screen.getByRole('button', { name: 'elsewhere' }).focus();
await user.keyboard('{Escape}');
expect(dispatch).toHaveBeenCalledExactlyOnceWith({
type: 'escape',
focusInside: false,
});
});
it('reports outside for a pointer down outside, not inside', async () => {
const { dispatch } = await renderSubmenu({ open: true });
fireEvent.pointerDown(toggle());
expect(dispatch).not.toHaveBeenCalled();
fireEvent.pointerDown(
screen.getByRole('button', { name: 'elsewhere' }),
);
expect(dispatch).toHaveBeenCalledExactlyOnceWith({ type: 'outside' });
});
it('listens for Escape and outside only while open', async () => {
const { dispatch, user } = await renderSubmenu({ open: false });
await user.keyboard('{Escape}');
fireEvent.pointerDown(
screen.getByRole('button', { name: 'elsewhere' }),
);
expect(dispatch).not.toHaveBeenCalled();
});
it('reports focusLeave when focus moves to an element outside', async () => {
const { dispatch } = await renderSubmenu({ open: true });
fireEvent.focusOut(toggle(), {
relatedTarget: screen.getByRole('button', { name: 'elsewhere' }),
});
expect(dispatch).toHaveBeenCalledExactlyOnceWith({
type: 'focusLeave',
});
});
it('ignores focus that stays inside or has no target', async () => {
const { dispatch } = await renderSubmenu({ open: true });
fireEvent.focusOut(toggle(), {
relatedTarget: screen.getByRole('link', { name: 'Newborn' }),
});
fireEvent.focusOut(toggle(), { relatedTarget: null });
expect(dispatch).not.toHaveBeenCalled();
});
it('reports nothing for hover or arrow keys (BR-NAV-21, BR-NAV-27)', async () => {
const { dispatch, user } = await renderSubmenu({ open: true });
await user.hover(toggle());
await user.hover(screen.getByRole('link', { name: 'Gezin' }));
screen.getByRole('link', { name: 'Gezin' }).focus();
await user.keyboard(
'{ArrowDown}{ArrowUp}{ArrowLeft}{ArrowRight}{Home}{End}',
);
expect(dispatch).not.toHaveBeenCalled();
});
it('marks the shoot page in the panel and the section on the parent', async () => {
await renderSubmenu({ open: true, path: '/soorten-fotoshoots/gezin' });
expect(screen.getByRole('link', { name: 'Gezin' })).toHaveAttribute(
'aria-current',
'page',
);
const parent = screen.getByRole('link', {
name: 'Soorten fotoshoots',
});
expect(parent).not.toHaveAttribute('aria-current');
expect(parent).toHaveAttribute('data-section-current');
});
});
@@ -0,0 +1,162 @@
import { useRef, type RefObject } from 'react';
import { Box, chakra } from '@chakra-ui/react';
import useDismiss from '@/hooks/useDismiss';
import { isSectionCurrent } from '@/lib/navCurrent';
import type { NavMenuEvent } from '@/lib/navMenuState';
import type { NavItem } from '@/navigation';
import RouterLink from '../RouterLink';
import ChevronIcon from './ChevronIcon';
import NavLink from './NavLink';
type NavSubmenuProps = {
item: NavItem & { children: readonly NavItem[] };
// Id of the panel, for aria-controls
id: string;
open: boolean;
pathname: string;
// The header is see-through over the home hero (white text)
transparent: boolean;
toggleRef: RefObject<HTMLButtonElement | null>;
dispatch: (event: NavMenuEvent) => void;
};
// Exact: only the page itself is current, not the pages below it (BR-NAV-01);
// without the query, so a filter in the URL does not switch it off
const exactActive = { exact: true, includeSearch: false } as const;
// Desktop submenu: the parent stays a link, a separate toggle opens a panel
// with the sub-pages. Disclosure navigation: no role="menu", no arrow keys,
// no hover opening (BR-NAV-21, BR-NAV-27).
export default function NavSubmenu({
item,
id,
open,
pathname,
transparent,
toggleRef,
dispatch,
}: NavSubmenuProps) {
const wrapper = useRef<HTMLDivElement>(null);
useDismiss(wrapper, open, (reason) =>
dispatch(
reason === 'escape'
? {
type: 'escape',
focusInside:
wrapper.current?.contains(document.activeElement) ??
false,
}
: { type: 'outside' },
),
);
return (
<Box
ref={wrapper}
position="relative"
display="flex"
alignItems="center"
// Focus moving to something outside closes the panel; a blur
// without a target (window blur) is ignored (BR-NAV-25)
onBlur={(event) => {
const next = event.relatedTarget;
if (
next instanceof Node &&
!event.currentTarget.contains(next)
) {
dispatch({ type: 'focusLeave' });
}
}}
>
<NavLink
to={item.to}
activeOptions={exactActive}
sectionCurrent={isSectionCurrent(item, pathname)}
mr={0}
>
{item.label}
</NavLink>
<chakra.button
ref={toggleRef}
type="button"
aria-expanded={open}
aria-controls={id}
aria-label={`Submenu ${item.label}`}
data-open={open || undefined}
display="flex"
alignItems="center"
justifyContent="center"
// 44px: minimaal klikdoel op touch (BR-NAV-40)
w="44px"
h="44px"
cursor="pointer"
color="currentColor"
// Over the hero the header is dark: a white ring (BR-NAV-43)
css={
transparent ? { '--focus-ring-color': 'white' } : undefined
}
onClick={() => dispatch({ type: 'toggleSubmenu' })}
>
<ChevronIcon />
</chakra.button>
<Box
id={id}
position="absolute"
top="calc(100% + 0.75rem)"
left="4"
minW="15rem"
// Own colours, so the panel is solid also over the hero (BR-NAV-29)
bg="bg"
color="fg"
borderWidth="1px"
borderColor="line"
shadow="panel"
// Hidden from sight and from Tab and screen readers while
// closed, but kept in the DOM so aria-controls stays valid
visibility={open ? 'visible' : 'hidden'}
opacity={open ? 1 : 0}
transform={open ? 'none' : 'translateY(-6px)'}
pointerEvents={open ? 'auto' : 'none'}
transitionProperty="opacity, transform, visibility"
transitionDuration="swap"
transitionTimingFunction="smooth"
_motionReduce={{ transition: 'none' }}
>
<chakra.ul listStyleType="none" py="2">
{item.children.map((child) => (
<li key={child.to}>
<RouterLink
to={child.to}
activeOptions={exactActive}
onClick={() => dispatch({ type: 'linkChosen' })}
textStyle="eyebrow"
color="fg"
display="flex"
alignItems="center"
minH="44px"
px="5"
position="relative"
_hover={{ bg: 'paper.alt' }}
_currentPage={{
color: 'accent.deep',
_before: {
content: '""',
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
width: '2px',
bg: 'accent',
},
}}
>
{child.label}
</RouterLink>
</li>
))}
</chakra.ul>
</Box>
</Box>
);
}
@@ -1,9 +1,30 @@
import { screen, within } from '@testing-library/react';
import { fireEvent, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { mockViewport } from '@/test/navViewport';
import { renderWithProviders } from '@/test/renderWithProviders';
import NavigationBar from './NavigationBar';
const TOGGLE = 'Submenu Soorten fotoshoots';
const SHOOTS = ['Newborn', 'Zwangerschap', 'Gezin', 'Loveshoot', 'Portretten'];
// The desktop layout (lg and up) unless a width is given
async function renderBar(path = '/', width = 1280) {
mockViewport(width);
const result = await renderWithProviders(<NavigationBar />, { path });
return { ...result, user: userEvent.setup() };
}
const toggle = () => screen.getByRole('button', { name: TOGGLE });
const panel = () => document.getElementById('submenu-soorten-fotoshoots')!;
// By text: the name of a link in a closed (hidden) panel is empty
const panelLink = (text: string) =>
within(panel())
.getAllByRole('link', { hidden: true })
.find((link) => link.textContent === text)!;
describe('NavigationBar', () => {
it('heeft het logo als link naar home', async () => {
await renderWithProviders(<NavigationBar />, { path: '/portfolio' });
@@ -15,12 +36,11 @@ describe('NavigationBar', () => {
});
it('toont het hoofdmenu in de vaste volgorde', async () => {
const { container } = await renderWithProviders(<NavigationBar />);
const { container } = await renderBar();
const nav = screen.getByRole('navigation', { name: 'Hoofdmenu' });
const topLevel = [...nav.querySelectorAll(':scope > ul > li')];
expect(
within(nav)
.getAllByRole('link', { hidden: true })
.map((link) => link.textContent),
topLevel.map((li) => li.querySelector('a')?.textContent),
).toEqual([
'Home',
'Over mij',
@@ -28,6 +48,11 @@ describe('NavigationBar', () => {
'Soorten fotoshoots',
'Contact',
]);
expect(
within(panel())
.getAllByRole('link', { hidden: true })
.map((link) => link.textContent),
).toEqual(SHOOTS);
expect(await axeResults(container)).toHaveNoViolations();
});
@@ -38,3 +63,222 @@ describe('NavigationBar', () => {
);
});
});
describe('NavigationBar submenu', () => {
it('heeft een knop met vaste naam, aria-expanded en een bestaand paneel', async () => {
await renderBar();
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
expect(toggle()).toHaveAttribute(
'aria-controls',
'submenu-soorten-fotoshoots',
);
expect(panel()).toBeInTheDocument();
});
it('opent met een klik en meldt dat in aria-expanded', async () => {
const { user } = await renderBar();
await user.click(toggle());
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
expect(toggle()).toHaveAccessibleName(TOGGLE);
for (const name of SHOOTS) {
expect(screen.getByRole('link', { name })).toBeVisible();
}
});
it.each(['{Enter}', ' '])('opent met toets %j', async (key) => {
const { user } = await renderBar();
toggle().focus();
await user.keyboard(key);
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
});
it('opent niet bij hoveren (BR-NAV-21)', async () => {
const { user } = await renderBar();
await user.hover(toggle());
await user.hover(
screen.getByRole('link', { name: 'Soorten fotoshoots' }),
);
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
});
it('sluit met Escape en zet de focus op de knop als die binnen stond (BR-NAV-23)', async () => {
const { user } = await renderBar();
await user.click(toggle());
await user.tab();
expect(document.activeElement).toBe(panelLink('Newborn'));
await user.keyboard('{Escape}');
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
expect(document.activeElement).toBe(toggle());
});
it('laat de focus staan bij Escape als die buiten het submenu stond', async () => {
const { user } = await renderBar();
await user.click(toggle());
toggle().blur();
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
await user.keyboard('{Escape}');
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
expect(document.activeElement).not.toBe(toggle());
});
it('sluit bij een pointer-down buiten zonder de focus te verplaatsen (BR-NAV-24)', async () => {
const { user } = await renderBar();
await user.click(toggle());
fireEvent.pointerDown(document.body);
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
expect(document.activeElement).toBe(toggle());
});
it('blijft open bij een pointer-down binnen het paneel', async () => {
const { user } = await renderBar();
await user.click(toggle());
fireEvent.pointerDown(panelLink('Gezin'));
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
});
it('sluit als Tab de focus uit het laatste paneellink haalt (BR-NAV-25)', async () => {
const { user } = await renderBar();
await user.click(toggle());
panelLink('Portretten').focus();
await user.tab();
expect(screen.getByRole('link', { name: 'Contact' })).toHaveFocus();
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
});
it('blijft open bij een focusout zonder doel, zoals een venster-blur', async () => {
const { user } = await renderBar();
await user.click(toggle());
fireEvent.focusOut(toggle(), { relatedTarget: null });
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
});
it('blijft open als de focus binnen het submenu verschuift', async () => {
const { user } = await renderBar();
await user.click(toggle());
await user.tab();
await user.tab();
expect(panelLink('Zwangerschap')).toHaveFocus();
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
});
it('houdt de links van een gesloten paneel buiten bereik van rolzoeker en Tab (BR-NAV-28)', async () => {
const { user } = await renderBar();
for (const name of SHOOTS) {
expect(screen.queryByRole('link', { name })).toBeNull();
}
const reached: string[] = [];
for (let i = 0; i < 8; i += 1) {
await user.tab();
reached.push(document.activeElement?.textContent ?? '');
}
for (const name of SHOOTS) expect(reached).not.toContain(name);
await user.click(toggle());
for (const name of SHOOTS) {
expect(screen.getByRole('link', { name })).toBeVisible();
}
});
it('sluit na het kiezen van een link', async () => {
const { user } = await renderBar();
await user.click(toggle());
await user.click(screen.getByRole('link', { name: 'Gezin' }));
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
});
it('sluit weer met een tweede klik en laat de focus op de knop', async () => {
const { user } = await renderBar();
await user.click(toggle());
await user.click(toggle());
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
expect(toggle()).toHaveFocus();
});
it('gebruikt geen menu-rollen (disclosure, geen menu)', async () => {
const { user } = await renderBar();
await user.click(toggle());
expect(
document.querySelector('[role="menu"], [role="menuitem"]'),
).toBeNull();
});
it('heeft geen axe-fouten met het paneel dicht en open', async () => {
const { container, user } = await renderBar();
expect(await axeResults(container)).toHaveNoViolations();
await user.click(toggle());
expect(await axeResults(container)).toHaveNoViolations();
});
it('zet de eigen kleuren op het paneel en currentColor op de knop (BR-NAV-29)', async () => {
await renderBar('/');
const panelRules = cssRulesFor(panel()).join('\n');
expect(panelRules).toMatch(/background(-color)?:/);
const toggleRules = cssRulesFor(toggle()).join('\n');
expect(toggleRules.toLowerCase()).toContain('color: currentcolor');
// Over de hero is de header doorzichtig: witte focusring (BR-NAV-43)
expect(toggleRules).toContain('--focus-ring-color: white');
});
it('zet de witte focusring niet op een effen header', async () => {
await renderBar('/portfolio');
expect(cssRulesFor(toggle()).join('\n')).not.toContain(
'--focus-ring-color: white',
);
});
it('zet bij voorkeur voor minder beweging geen overgang (BR-NAV-42)', async () => {
await renderBar();
const panelRules = cssRulesFor(panel()).join('\n');
expect(panelRules).toContain('prefers-reduced-motion: reduce');
expect(panelRules).toContain('transition: none');
const chevron = toggle().querySelector('svg')!;
const chevronRules = cssRulesFor(chevron).join('\n');
expect(chevronRules).toContain('prefers-reduced-motion: reduce');
expect(chevronRules).toContain('transition: none');
});
it('draait de pijl open via data-open (rotatie 180 graden)', async () => {
const { user } = await renderBar();
const chevron = toggle().querySelector('svg')!;
expect(cssRulesFor(chevron).join('\n')).toContain('rotate(180deg)');
expect(toggle()).not.toHaveAttribute('data-open');
await user.click(toggle());
expect(toggle()).toHaveAttribute('data-open');
});
});
describe('NavigationBar current page', () => {
it('markeert op een shootpagina het paneellink en alleen de sectie bij het hoofditem', async () => {
await renderBar('/soorten-fotoshoots/newborn');
expect(panelLink('Newborn')).toHaveAttribute('aria-current', 'page');
for (const name of SHOOTS.slice(1)) {
expect(panelLink(name)).not.toHaveAttribute('aria-current');
}
const parent = screen.getByRole('link', {
name: 'Soorten fotoshoots',
});
expect(parent).not.toHaveAttribute('aria-current');
expect(parent).toHaveAttribute('data-section-current');
});
it('markeert op het overzicht het hoofditem met beide', async () => {
await renderBar('/soorten-fotoshoots');
const parent = screen.getByRole('link', {
name: 'Soorten fotoshoots',
});
expect(parent).toHaveAttribute('aria-current', 'page');
expect(parent).toHaveAttribute('data-section-current');
for (const name of SHOOTS) {
expect(panelLink(name)).not.toHaveAttribute('aria-current');
}
});
it('markeert op een andere pagina het hoofditem niet', async () => {
await renderBar('/portfolio');
const parent = screen.getByRole('link', {
name: 'Soorten fotoshoots',
});
expect(parent).not.toHaveAttribute('data-section-current');
expect(parent).not.toHaveAttribute('aria-current');
});
});
@@ -8,32 +8,65 @@ import {
} from '@chakra-ui/react';
import NavLink from './NavLink';
import MobileNav from './MobileNav';
import { mainNav } from '@/navigation';
import NavSubmenu from './NavSubmenu';
import { hasChildren, mainNav } from '@/navigation';
import RouterLink from '../RouterLink';
import useScrolledPast from '@/hooks/useScrolledPast';
import { useCallback, useState } from 'react';
import { isSectionCurrent } from '@/lib/navCurrent';
import { initialNavMenuState, navMenuReducer } from '@/lib/navMenuState';
import { useEffect, useReducer, useRef } from 'react';
import { useRouterState } from '@tanstack/react-router';
// Images
import logoLight from '../../assets/logo-light.png';
import logoDark from '../../assets/logo-dark.png';
// Het item met een submenu: bepaalt of het mobiele menu open start in een sectie
const parentItem = mainNav.find(hasChildren);
export default function NavigationBar() {
const [open, setOpen] = useState(false);
const closeMenu = useCallback(() => setOpen(false), []);
// Eén reducer voor het mobiele menu, de groep en het desktop-submenu, zodat
// ze elkaar niet tegenspreken
const [state, dispatch] = useReducer(navMenuReducer, initialNavMenuState);
const hamburgerRef = useRef<HTMLButtonElement>(null);
const submenuToggleRef = useRef<HTMLButtonElement>(null);
// Het mobiele menu bestaat alleen onder lg; wordt het scherm breder, dan
// telt het als dicht.
// sluit de reducer het. Eerste render kan undefined geven: telt als mobiel.
const isDesktop = useBreakpointValue(
{ base: false, lg: true },
{ ssr: false },
);
const menuOpen = open && !isDesktop;
useEffect(() => {
dispatch({ type: 'viewport', isDesktop: !!isDesktop });
}, [isDesktop]);
const pathname = useRouterState({
select: (routerState) => routerState.location.pathname,
});
const isHome = pathname === '/';
// Elke wissel van pagina sluit de menu's (ook de terugknop), maar niet
// bij de eerste render
const previousPathname = useRef(pathname);
useEffect(() => {
if (previousPathname.current === pathname) return;
previousPathname.current = pathname;
dispatch({ type: 'routeChanged' });
}, [pathname]);
// De reducer vraagt om focus (na Escape); hier wordt die verplaatst
useEffect(() => {
if (!state.focusRequest) return;
const target =
state.focusRequest === 'menuToggle'
? hamburgerRef.current
: submenuToggleRef.current;
target?.focus();
dispatch({ type: 'focusHandled' });
}, [state.focusRequest]);
const pastHero = useScrolledPast(() => 150);
const isHome = useRouterState({
select: (state) => state.location.pathname === '/',
});
const isSolid = pastHero || !isHome;
// Doorzichtig over de hero, maar alleen op desktop. Op mobiel staat de
@@ -119,9 +152,21 @@ export default function NavigationBar() {
>
{mainNav.map((item) => (
<chakra.li key={item.to}>
<NavLink to={item.to}>
{item.label}
</NavLink>
{hasChildren(item) ? (
<NavSubmenu
item={item}
id={`submenu-${item.to.slice(1)}`}
open={state.submenuOpen}
pathname={pathname}
transparent={!isSolid}
toggleRef={submenuToggleRef}
dispatch={dispatch}
/>
) : (
<NavLink to={item.to}>
{item.label}
</NavLink>
)}
</chakra.li>
))}
</HStack>
@@ -134,13 +179,26 @@ export default function NavigationBar() {
justifyContent="flex-end"
>
<chakra.button
onClick={() => setOpen(!menuOpen)}
aria-label={
menuOpen ? 'Menu sluiten' : 'Menu openen'
ref={hamburgerRef}
onClick={() =>
dispatch({
type: 'toggleMenu',
inSection: parentItem
? isSectionCurrent(
parentItem,
pathname,
)
: false,
})
}
aria-expanded={menuOpen}
aria-label={
state.menuOpen
? 'Menu sluiten'
: 'Menu openen'
}
aria-expanded={state.menuOpen}
aria-controls="mobile-nav"
data-open={menuOpen || undefined}
data-open={state.menuOpen || undefined}
// Op desktop opent deze knop straks het info-menu (side area)
display={{ base: 'block', lg: 'none' }}
data-testid="nav-menu-toggle"
@@ -189,7 +247,13 @@ export default function NavigationBar() {
</Flex>
</Container>
</chakra.header>
<MobileNav id="mobile-nav" open={menuOpen} onClose={closeMenu} />
<MobileNav
id="mobile-nav"
open={state.menuOpen}
groupOpen={state.groupOpen}
pathname={pathname}
dispatch={dispatch}
/>
</>
);
}
@@ -0,0 +1,108 @@
import { cleanup, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { renderApp } from '@/test/renderApp';
import { renderWithProviders } from '@/test/renderWithProviders';
import RouterLink from '../RouterLink';
// Regression probe of the router's `activeOptions` (BR-NAV-01, BR-NAV-04).
// The facts pinned here decide why every nav and footer link gets
// `{ exact: true, includeSearch: false }`: a plain `exact` ignores a trailing
// slash but not letter case, and loses `aria-current` on any query string.
const bothVariants = [
['exact', { exact: true }],
['exact + includeSearch false', { exact: true, includeSearch: false }],
] as const;
async function currentOf(
variant: (typeof bothVariants)[number][1],
path: string,
) {
cleanup();
await renderWithProviders(
<>
<RouterLink to="/soorten-fotoshoots" activeOptions={variant}>
parent
</RouterLink>
<RouterLink
to="/soorten-fotoshoots/newborn"
activeOptions={variant}
>
child
</RouterLink>
</>,
{ path },
);
const isCurrent = (name: string) =>
screen.getByRole('link', { name }).getAttribute('aria-current') ===
'page';
return { parent: isCurrent('parent'), child: isCurrent('child') };
}
describe.each(bothVariants)('activeOptions %s', (_name, variant) => {
it('marks the exact path only', async () => {
expect(await currentOf(variant, '/soorten-fotoshoots')).toEqual({
parent: true,
child: false,
});
});
it('marks the child, not the parent, on the child path', async () => {
expect(await currentOf(variant, '/soorten-fotoshoots/newborn')).toEqual(
{ parent: false, child: true },
);
});
it('ignores a trailing slash', async () => {
expect(await currentOf(variant, '/soorten-fotoshoots/')).toEqual({
parent: true,
child: false,
});
expect(
await currentOf(variant, '/soorten-fotoshoots/newborn/'),
).toEqual({ parent: false, child: true });
});
it('does not ignore letter case', async () => {
expect(await currentOf(variant, '/Soorten-Fotoshoots/Newborn')).toEqual(
{ parent: false, child: false },
);
});
});
describe('activeOptions and the query string', () => {
it('plain exact loses aria-current when the URL has a query', async () => {
expect(
await currentOf({ exact: true }, '/soorten-fotoshoots?x=1'),
).toEqual({ parent: false, child: false });
});
it('includeSearch false keeps aria-current with a query', async () => {
expect(
await currentOf(
{ exact: true, includeSearch: false },
'/soorten-fotoshoots?x=1',
),
).toEqual({ parent: true, child: false });
});
it('includeSearch false keeps a non-matching page unmarked', async () => {
expect(
await currentOf(
{ exact: true, includeSearch: false },
'/portfolio?shoot=newborn',
),
).toEqual({ parent: false, child: false });
});
});
describe('activeOptions in the real route tree', () => {
it('renders the Newborn page on a case variant', async () => {
// The router matches case-insensitively, so the page shows; which
// links are current there is pinned in navSubmenu.test.tsx
await renderApp('/soorten-fotoshoots/Newborn');
expect(
await screen.findByRole('heading', { level: 1 }),
).toBeInTheDocument();
});
});
@@ -0,0 +1,95 @@
import { screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import LinkButton from '@/components/LinkButton';
import packages from '@/content/packages';
import shootTypes from '@/content/shootTypes';
import type { PricingPackage } from '@/content/types';
import { formatPrice } from '@/lib/formatPrice';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import PackageBlock from './PackageBlock';
const newborn = shootTypes.find((shoot) => shoot.id === 'newborn')!;
const pkg: PricingPackage = packages.find(
(item) => item.id === newborn.packageId,
)!;
const onRequest = { price: 'Prijs op aanvraag', text: 'Neem contact op.' };
describe('PackageBlock', () => {
it('shows the price, the features, the actions and the note for a package', async () => {
const { container } = await renderWithProviders(
<PackageBlock
titleId="offer-title"
eyebrow="Het pakket"
title="Newbornshoot"
image={newborn.image}
pkg={pkg}
onRequest={onRequest}
note="Aanbetaling € 50."
data-testid="package"
>
<LinkButton variant="accent" to="/contact">
Boek dit pakket
</LinkButton>
<a href="/contact">Eerst een vraag stellen</a>
</PackageBlock>,
);
expect(screen.getByRole('heading', { level: 2 })).toHaveAttribute(
'id',
'offer-title',
);
// The price keeps its non-breaking space
const price = screen.getByText(/185/);
expect(price.textContent).toBe(formatPrice(pkg.price));
expect(price.textContent).toBe('€ 185');
const list = screen.getByRole('list');
const rows = within(list).getAllByRole('listitem');
expect(rows.map((row) => row.textContent)).toEqual(pkg.features);
expect(screen.queryByText(onRequest.text)).toBeNull();
expect(
screen.getByRole('link', { name: 'Boek dit pakket' }),
).toBeInTheDocument();
expect(
screen.getByRole('link', { name: 'Eerst een vraag stellen' }),
).toBeInTheDocument();
expect(screen.getByText('Aanbetaling € 50.')).toBeInTheDocument();
expect(screen.getByTestId('package')).toBeInTheDocument();
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows the on-request price and text, without a list, when there is no package', async () => {
const { container } = await renderWithProviders(
<PackageBlock
titleId="offer-title"
eyebrow="Het aanbod"
title="Loveshoot"
image={newborn.image}
onRequest={onRequest}
>
<LinkButton variant="accent" to="/contact">
Vraag naar de mogelijkheden
</LinkButton>
</PackageBlock>,
);
expect(screen.getByText('Prijs op aanvraag')).toBeInTheDocument();
expect(screen.getByText('Neem contact op.')).toBeInTheDocument();
expect(screen.queryByRole('list')).toBeNull();
expect(await axeResults(container)).toHaveNoViolations();
});
it('leaves out the note when there is none', async () => {
await renderWithProviders(
<PackageBlock
titleId="t"
eyebrow="e"
title="Titel"
image={newborn.image}
pkg={pkg}
onRequest={onRequest}
>
<a href="/contact">Actie</a>
</PackageBlock>,
);
expect(screen.queryByText(/Aanbetaling/)).toBeNull();
});
});
@@ -0,0 +1,94 @@
import type { ReactNode } from 'react';
import { Box, Flex, Heading, Text } from '@chakra-ui/react';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import MediaText from '@/components/MediaText/MediaText';
import type { ContentImage, FrameColor, PricingPackage } from '@/content/types';
import { formatPrice } from '@/lib/formatPrice';
type PackageBlockProps = {
// Id of the h2, which names the section around the block
titleId: string;
eyebrow: string;
title: string;
image: ContentImage;
frameColor?: FrameColor;
// Present: the price and the features. Absent: the on-request text.
pkg?: PricingPackage;
onRequest: { price: string; text: string };
// Small print below the actions, e.g. the deposit
note?: string;
'data-testid'?: string;
// The actions below the text, e.g. link buttons
children: ReactNode;
};
// The offer of a shoot page (FR-ST-07, BR-SP-60..62): a small square photo
// next to the price and either the features of the package or the text for
// a shoot without a fixed price. The variant follows from `pkg` alone.
export default function PackageBlock({
titleId,
eyebrow,
title,
image,
frameColor,
pkg,
onRequest,
note,
'data-testid': testId,
children,
}: PackageBlockProps) {
return (
<MediaText
image={image}
aspectRatio="1 / 1"
mediaSize="small"
frameColor={frameColor}
data-testid={testId}
>
<Eyebrow>{eyebrow}</Eyebrow>
<Heading as="h2" id={titleId} textStyle="sectionTitle">
{title}
</Heading>
<Text
fontFamily="heading"
fontSize="2.25rem"
lineHeight="1.2"
color="accent.deep"
mt={4}
>
{pkg ? formatPrice(pkg.price) : onRequest.price}
</Text>
{pkg ? (
<Box as="ul" role="list" listStyle="none" m={0} p={0} mt={5}>
{pkg.features.map((feature, index) => (
<Box
as="li"
key={`${index}-${feature}`}
py={3}
color="ink.soft"
borderTopWidth="1px"
borderColor="sand"
borderBottomWidth={
index === pkg.features.length - 1 ? '1px' : 0
}
>
{feature}
</Box>
))}
</Box>
) : (
<Text color="ink.soft" mt={4}>
{onRequest.text}
</Text>
)}
<Flex wrap="wrap" align="center" columnGap={7} rowGap={3} mt={7}>
{children}
</Flex>
{note && (
<Text fontSize="0.875rem" color="ink.soft" mt={5}>
{note}
</Text>
)}
</MediaText>
);
}
@@ -28,4 +28,46 @@ describe('PageIntro', () => {
'Contact',
);
});
it('renders exactly the old markup when the new props are left out', async () => {
const { container } = await renderWithProviders(
<PageIntro eyebrow="Werk" title="Portfolio">
Intro
</PageIntro>,
);
const section = container.querySelector('section')!;
expect(section.hasAttribute('aria-labelledby')).toBe(false);
expect([...section.children].map((child) => child.tagName)).toEqual([
'P',
'H1',
'P',
]);
expect(section.querySelector('h1')!.hasAttribute('id')).toBe(false);
});
it('names the section by the h1 and shows the breadcrumb above the label', async () => {
const { container } = await renderWithProviders(
<PageIntro
eyebrow="Newborn"
title="Newbornshoot"
titleId="intro-title"
breadcrumb={<nav aria-label="Kruimelpad">Pad</nav>}
>
Intro
</PageIntro>,
);
expect(
screen.getByRole('region', { name: 'Newbornshoot' }),
).toBeInTheDocument();
expect(screen.getByRole('heading', { level: 1 })).toHaveAttribute(
'id',
'intro-title',
);
const nav = screen.getByRole('navigation', { name: 'Kruimelpad' });
expect(
nav.compareDocumentPosition(screen.getByText('Newborn')) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(await axeResults(container)).toHaveNoViolations();
});
});
+12 -3
View File
@@ -1,29 +1,38 @@
import type { ReactNode } from 'react';
import { Container, Heading, Text } from '@chakra-ui/react';
import { Box, Container, Heading, Text } from '@chakra-ui/react';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
type PageIntroProps = {
title: string;
eyebrow?: string;
// Id of the h1; the section is then named by it
titleId?: string;
// E.g. a Breadcrumb, shown above the eyebrow
breadcrumb?: ReactNode;
children?: ReactNode;
};
// Bovenste blok van een gewone pagina (.page-head in het design): label,
// de enige h1 van de pagina en een korte intro
// de enige h1 van de pagina en een korte intro. Optioneel een kruimelpad
// erboven en een id voor de h1 (de sectie krijgt daar zijn naam van).
export default function PageIntro({
title,
eyebrow,
titleId,
breadcrumb,
children,
}: PageIntroProps) {
return (
<Container
as="section"
aria-labelledby={titleId}
pt="pageTop"
pb={{ base: 8, md: 12, lg: 16 }}
textAlign="center"
>
{breadcrumb && <Box mb={{ base: 6, md: 7 }}>{breadcrumb}</Box>}
{eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
<Heading as="h1" textStyle="pageTitle" mb={4}>
<Heading as="h1" id={titleId} textStyle="pageTitle" mb={4}>
{title}
</Heading>
{children && (
@@ -0,0 +1,84 @@
import { cleanup, screen } from '@testing-library/react';
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import type { ContentImage } from '@/content/types';
import { contentImage } from '@/test/arbitraries';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import PhotoMosaic from './PhotoMosaic';
const photo = (n: number): ContentImage => ({
src: `/foto-${n}.jpg`,
alt: `Foto ${n}`,
width: 800,
height: 1200,
});
const photos = (count: number) =>
Array.from({ length: count }, (_, index) => photo(index + 1));
describe('PhotoMosaic', () => {
it.each([
[2, 2],
[3, 3],
[4, 4],
[5, 4],
])('shows %i photos as %i tiles', async (count, tiles) => {
const { container } = await renderWithProviders(
<PhotoMosaic images={photos(count)} data-testid="mosaic" />,
);
const list = screen.getByTestId('mosaic');
expect(list.tagName).toBe('UL');
expect(screen.getAllByRole('listitem')).toHaveLength(tiles);
expect(screen.getAllByRole('img')).toHaveLength(tiles);
expect(
screen.getAllByRole('img').map((img) => img.getAttribute('alt')),
).toEqual(photos(tiles).map((image) => image.alt));
expect(container.querySelector('a, button')).toBeNull();
expect(await axeResults(container)).toHaveNoViolations();
});
it('renders nothing without photos', async () => {
const { container } = await renderWithProviders(
<PhotoMosaic images={[]} />,
);
expect(container.querySelector('ul')).toBeNull();
});
it('places the tiles in a 4 x 2 grid from md and in two columns below', async () => {
await renderWithProviders(<PhotoMosaic images={photos(4)} />);
const rules = cssRulesFor(screen.getByRole('list')).join('\n');
expect(rules).toContain('repeat(2, minmax(0, 1fr))');
expect(rules).toMatch(
/min-width: 48rem[^}]*repeat\(4, minmax\(0, 1fr\)\)/,
);
const second = cssRulesFor(screen.getAllByRole('listitem')[1]).join(
'\n',
);
expect(second).toContain('span 2');
expect(second).toMatch(/min-width: 48rem[^}]*grid-column: 3 ?\/ ?5/);
});
it('shows min(n, 4) photos with the given alt texts, in order (invariant)', async () => {
const images = fc.array(contentImage, { minLength: 2, maxLength: 6 });
for (const sample of fc.sample(images, { numRuns: 6 })) {
const unique = sample.map((image, index) => ({
...image,
src: `${index}${image.src}`,
}));
await renderWithProviders(<PhotoMosaic images={unique} />);
const shown = screen.queryAllByRole('img');
const expected = unique.slice(0, 4);
expect(document.querySelectorAll('li > img')).toHaveLength(
expected.length,
);
expect(
[...document.querySelectorAll('li > img')].map((img) =>
img.getAttribute('alt'),
),
).toEqual(expected.map((image) => image.alt));
expect(shown.length).toBeLessThanOrEqual(4);
cleanup();
}
});
});
@@ -0,0 +1,69 @@
import { Box } from '@chakra-ui/react';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import Reveal from '@/components/Reveal/Reveal';
import type { ContentImage } from '@/content/types';
import { MOSAIC_MAX_PHOTOS, mosaicLayout } from '@/lib/mosaicLayout';
type PhotoMosaicProps = {
images: readonly ContentImage[];
'data-testid'?: string;
};
// A mosaic of up to four photos (FR-ST-05, BR-SP-30b..35): a 4 x 2 grid from
// `md`, two columns on phones. Only a picture: no link, no button, no
// hover effect. The photos fill their cells, so their own size never sets a
// row height. Renders nothing without photos.
export default function PhotoMosaic({
images,
'data-testid': testId,
}: PhotoMosaicProps) {
const shown = images.slice(0, MOSAIC_MAX_PHOTOS);
const tiles = mosaicLayout(shown.length);
if (tiles.length === 0) return null;
return (
<Box
as="ul"
role="list"
listStyle="none"
m={0}
p={0}
display="grid"
gridTemplateColumns={{
base: 'repeat(2, minmax(0, 1fr))',
md: 'repeat(4, minmax(0, 1fr))',
}}
gridTemplateRows={{
md: 'repeat(2, clamp(12rem, 22vw, 18.75rem))',
}}
gap="gridGap"
data-testid={testId}
>
{tiles.map((tile, index) => (
<Reveal
as="li"
key={shown[index].src}
delay={index * 0.08}
position="relative"
overflow="hidden"
bg="paper.deep"
gridColumn={{
base: tile.wide ? 'span 2' : 'auto',
md: tile.column,
}}
gridRow={{ md: tile.row }}
aspectRatio={{ base: tile.phoneRatio, md: 'auto' }}
>
<DeferredImage
image={shown[index]}
position="absolute"
inset={0}
w="100%"
h="100%"
objectFit="cover"
/>
</Reveal>
))}
</Box>
);
}
@@ -0,0 +1,144 @@
import { cleanup, screen, within } from '@testing-library/react';
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { processIcons } from '@/components/shoots/ProcessIcons/ProcessIcons';
import shootPageShared from '@/content/shootPageShared';
import { PROCESS_STEP_ORDER } from '@/lib/shootPageView';
import { timelineSteps } from '@/test/arbitraries';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import ProcessTimeline from './ProcessTimeline';
const six = PROCESS_STEP_ORDER.map((id) => {
const Icon = processIcons[id];
return {
id,
title: shootPageShared.process.steps[id].title,
text: shootPageShared.process.steps[id].text,
icon: <Icon />,
};
});
describe('ProcessTimeline', () => {
it('lists six steps in order, each with an h3 and a text', async () => {
const { container } = await renderWithProviders(
<ProcessTimeline steps={six} data-testid="timeline" />,
);
const list = screen.getByRole('list');
expect(list.tagName).toBe('OL');
const items = within(list).getAllByRole('listitem');
expect(items).toHaveLength(6);
items.forEach((item, index) => {
expect(
within(item).getByRole('heading', { level: 3 }),
).toHaveTextContent(six[index].title);
expect(within(item).getByText(six[index].text)).toBeInTheDocument();
});
expect(await axeResults(container)).toHaveNoViolations();
});
it('puts the text above the line for even indexes and below for odd ones', async () => {
await renderWithProviders(<ProcessTimeline steps={six} />);
const positions = screen
.getAllByRole('listitem')
.map((item) =>
item
.querySelector('[data-text-position]')!
.getAttribute('data-text-position'),
);
expect(positions).toEqual([
'above',
'below',
'above',
'below',
'above',
'below',
]);
});
it('fills only the last marker and hides every marker and line from assistive technology', async () => {
const { container } = await renderWithProviders(
<ProcessTimeline steps={six} data-testid="timeline" />,
);
const markers = screen.getAllByTestId('timeline-marker');
expect(markers.map((m) => m.getAttribute('data-filled'))).toEqual([
'false',
'false',
'false',
'false',
'false',
'true',
]);
for (const marker of markers) {
expect(marker).toHaveAttribute('aria-hidden', 'true');
}
const lines = container.querySelectorAll('li > span');
// One horizontal line per step, one vertical line per step but the
// last
expect(lines).toHaveLength(6 + 5);
for (const line of lines) {
expect(line).toHaveAttribute('aria-hidden', 'true');
}
});
it('is one column up to lg and a grid of one column per step from lg', async () => {
await renderWithProviders(<ProcessTimeline steps={six} />);
const rules = cssRulesFor(screen.getByRole('list')).join('\n');
expect(rules).toMatch(
/min-width: 64rem[^}]*repeat\(6, minmax\(0, 1fr\)\)/,
);
expect(rules).toContain('max-width: 34rem');
});
it('lines the markers up with subgrid rows from lg', async () => {
await renderWithProviders(<ProcessTimeline steps={six} />);
const rules = cssRulesFor(screen.getAllByRole('listitem')[0]).join();
expect(rules).toContain('subgrid');
});
it('lays out one step and works without icons, in the alt tone', async () => {
const { container } = await renderWithProviders(
<ProcessTimeline
tone="alt"
steps={[{ id: 'a', title: 'Eén', text: 'Alleen' }]}
/>,
);
expect(screen.getAllByRole('listitem')).toHaveLength(1);
expect(container.querySelectorAll('svg')).toHaveLength(0);
expect(
container.querySelector('li > span[aria-hidden]'),
).not.toBeNull();
});
it('renders nothing without steps', async () => {
const { container } = await renderWithProviders(
<ProcessTimeline steps={[]} />,
);
expect(container.querySelector('ol')).toBeNull();
});
it('keeps the order and adds no numbers for any steps (invariant)', async () => {
for (const steps of fc.sample(timelineSteps, { numRuns: 6 })) {
const { container } = await renderWithProviders(
<ProcessTimeline steps={steps} />,
);
const items = container.querySelectorAll('ol > li');
expect(items).toHaveLength(steps.length);
items.forEach((item, index) => {
expect(item.querySelectorAll('h3')).toHaveLength(1);
expect(item.querySelector('h3')!.textContent).toBe(
steps[index].title,
);
// Nothing but the title and the text is visible text
expect(item.textContent).toBe(
steps[index].title + steps[index].text,
);
for (const hidden of item.querySelectorAll('[aria-hidden]')) {
expect(hidden.textContent).toBe('');
}
});
cleanup();
}
});
});
@@ -0,0 +1,164 @@
import type { ReactNode } from 'react';
import { Box, Flex, Heading, Text } from '@chakra-ui/react';
import Reveal from '@/components/Reveal/Reveal';
// Height and width of a marker, and so the height of the middle row
const MARKER = '3.5rem';
type TimelineStep = {
id: string;
title: string;
text: string;
// A decorative icon, e.g. from ProcessIcons
icon?: ReactNode;
};
type ProcessTimelineProps = {
steps: readonly TimelineStep[];
// The band colour: the markers use it to hide the line behind them
tone?: 'paper' | 'alt';
'data-testid'?: string;
};
// The steps of a process as a timeline (FR-ST-04, BR-SP-20..26): vertical
// with the text beside each marker below `lg`, horizontal from `lg` with
// the texts alternating above and below the line. One ordered list in both
// layouts, so the reading order is the order of the steps. The line, the
// markers and the icons are decoration only.
export default function ProcessTimeline({
steps,
tone = 'paper',
'data-testid': testId,
}: ProcessTimelineProps) {
if (steps.length === 0) return null;
const background = tone === 'alt' ? 'paper.alt' : 'paper';
return (
<Reveal data-testid={testId}>
<Box
as="ol"
role="list"
listStyle="none"
m={0}
p={0}
maxW={{ base: '34rem', lg: 'none' }}
mx="auto"
display={{ lg: 'grid' }}
gridTemplateColumns={{
lg: `repeat(${steps.length}, minmax(0, 1fr))`,
}}
gridTemplateRows={{ lg: `auto ${MARKER} auto` }}
>
{steps.map((step, index) => {
const first = index === 0;
const last = index === steps.length - 1;
const above = index % 2 === 0;
return (
<Box
as="li"
key={step.id}
position="relative"
display="grid"
gridTemplateColumns={{
base: `${MARKER} 1fr`,
lg: 'minmax(0, 1fr)',
}}
columnGap={{ base: 5, lg: 0 }}
pb={{ base: last ? 0 : 8, lg: 0 }}
gridRow={{ lg: '1 / 4' }}
// The rows of the list itself, so the markers line
// up whatever the text heights are. Subgrid is
// supported by every current browser; a style prop
// cannot hold a fallback for older ones.
gridTemplateRows={{ lg: 'subgrid' }}
>
{/* The line down to the next marker (vertical
layout); the next marker hides its end */}
{!last && (
<Box
as="span"
aria-hidden="true"
display={{ base: 'block', lg: 'none' }}
position="absolute"
left={`calc(${MARKER} / 2 - 1px)`}
top={`calc(${MARKER} / 2)`}
bottom={`calc(${MARKER} / -2)`}
w="2px"
bg="sand"
/>
)}
{/* The line through the marker (horizontal
layout), from the first to the last centre */}
<Box
as="span"
aria-hidden="true"
display={{ base: 'none', lg: 'block' }}
gridRow={{ lg: 2 }}
gridColumn={{ lg: 1 }}
alignSelf="center"
h="2px"
bg="sand"
ml={first ? '50%' : 0}
mr={last ? '50%' : 0}
/>
<Flex
aria-hidden="true"
data-testid={
testId ? `${testId}-marker` : undefined
}
data-filled={last ? 'true' : 'false'}
position="relative"
zIndex={1}
align="center"
justify="center"
w={MARKER}
h={MARKER}
borderRadius="full"
borderWidth="1.5px"
borderColor="accent.deep"
bg={last ? 'accent.deep' : background}
color={last ? 'white' : 'accent.deep'}
gridRow={{ base: 1, lg: 2 }}
gridColumn={1}
justifySelf={{ lg: 'center' }}
>
{step.icon}
</Flex>
<Box
data-text-position={above ? 'above' : 'below'}
gridColumn={{ base: 2, lg: 1 }}
gridRow={{ base: 1, lg: above ? 1 : 3 }}
alignSelf={{
base: 'start',
lg: above ? 'end' : 'start',
}}
pt={{ base: 3, lg: above ? 0 : 6 }}
pb={{ lg: above ? 6 : 0 }}
px={{ lg: 3 }}
textAlign={{ lg: 'center' }}
>
<Heading
as="h3"
fontFamily="heading"
fontWeight="normal"
fontSize="xl"
lineHeight="1.2"
>
{step.title}
</Heading>
<Text
mt={2}
fontSize="0.9375rem"
lineHeight="1.6"
color="ink.soft"
>
{step.text}
</Text>
</Box>
</Box>
);
})}
</Box>
</Reveal>
);
}
+32 -1
View File
@@ -1,14 +1,45 @@
import { useRouterState } from '@tanstack/react-router';
import { isShootSectionPath } from '@/lib/isShootSectionPath';
import LinkButton from '../LinkButton';
import StatusPage from './StatusPage';
// Pagina voor een onbekende URL, binnen de shell (FR-09). Een globale
// not-found heeft geen eigen route-head; React 19 zet <title> en <meta>
// daarom zelf in <head> en haalt ze weer weg bij het verlaten (BR-404-02).
// Onder /soorten-fotoshoots/ komt er een knop naar het overzicht bij
// (FR-ST-14).
export default function NotFound() {
const pathname = useRouterState({
select: (routerState) => routerState.location.pathname,
});
return (
<>
<title>Pagina niet gevonden | Andrea Slop Fotografie</title>
<meta name="robots" content="noindex" />
<StatusPage title="Pagina niet gevonden">
<StatusPage
title="Pagina niet gevonden"
actions={
isShootSectionPath(pathname) ? (
<>
<LinkButton
to="/soorten-fotoshoots"
variant="accent"
data-testid="status-page-section-link"
>
Terug naar Soorten fotoshoots
</LinkButton>
<LinkButton
to="/"
variant="outline"
data-testid="status-page-home-link"
>
Terug naar home
</LinkButton>
</>
) : undefined
}
>
Deze pagina bestaat niet (meer). Misschien is de link verouderd
of zit er een typfout in het adres.
</StatusPage>
@@ -29,6 +29,35 @@ describe('NotFound', () => {
document.head.querySelector('meta[name="robots"]'),
).toHaveAttribute('content', 'noindex');
});
it('toont onder /soorten-fotoshoots/ twee knoppen in vaste volgorde', async () => {
const { container } = await renderWithProviders(<NotFound />, {
path: '/soorten-fotoshoots/niet-bestaande-shoot',
});
const links = screen.getAllByRole('link');
expect(links.map((link) => link.textContent)).toEqual([
'Terug naar Soorten fotoshoots',
'Terug naar home',
]);
expect(links[0]).toHaveAttribute('href', '/soorten-fotoshoots');
expect(links[1]).toHaveAttribute('href', '/');
expect(await axeResults(container)).toHaveNoViolations();
});
it('herkent het prefix hoofdletterongevoelig', async () => {
await renderWithProviders(<NotFound />, {
path: '/Soorten-Fotoshoots/x',
});
expect(screen.getAllByRole('link')).toHaveLength(2);
expect(
screen.getByRole('link', { name: 'Terug naar Soorten fotoshoots' }),
).toHaveAttribute('href', '/soorten-fotoshoots');
});
it('houdt buiten de sectie één knop', async () => {
await renderWithProviders(<NotFound />, { path: '/bestaat-niet' });
expect(screen.getAllByRole('link')).toHaveLength(1);
});
});
describe('ErrorPage', () => {
@@ -0,0 +1,41 @@
import { render } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { PROCESS_STEP_ORDER } from '@/lib/shootPageView';
import { axeResults } from '@/test/axe';
import { processIcons } from './ProcessIcons';
describe('processIcons', () => {
it('has exactly one icon for every step of the process', () => {
expect(Object.keys(processIcons).sort()).toEqual(
[...PROCESS_STEP_ORDER].sort(),
);
});
it.each(PROCESS_STEP_ORDER)(
'draws the %s icon as a hidden, unfocusable 24 px svg without a title',
(id) => {
const Icon = processIcons[id];
const { container } = render(<Icon />);
const svg = container.querySelector('svg')!;
expect(svg).toHaveAttribute('aria-hidden', 'true');
expect(svg).toHaveAttribute('focusable', 'false');
expect(svg).toHaveAttribute('viewBox', '0 0 24 24');
expect(svg).toHaveAttribute('width', '24');
expect(svg).toHaveAttribute('height', '24');
expect(svg.querySelector('title')).toBeNull();
expect(svg.children.length).toBeGreaterThan(0);
},
);
it('has no accessibility violations', async () => {
const { container } = render(
<div>
{PROCESS_STEP_ORDER.map((id) => {
const Icon = processIcons[id];
return <Icon key={id} />;
})}
</div>,
);
expect(await axeResults(container)).toHaveNoViolations();
});
});
@@ -0,0 +1,76 @@
import type { ReactElement, ReactNode } from 'react';
import type { ProcessStepId } from '@/content/types';
// One decorative 24 x 24 icon of the process timeline (design E, stroke
// icons in the text colour). Hidden from assistive technology: the step
// title says everything.
function Icon({ children }: { children: ReactNode }) {
return (
<svg
viewBox="0 0 24 24"
width="24"
height="24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
{children}
</svg>
);
}
// The icon of every step; the Record makes a missing step a compile error
export const processIcons: Record<ProcessStepId, () => ReactElement> = {
// Envelope
aanvragen: () => (
<Icon>
<rect x="3" y="5.5" width="18" height="13" />
<path d="M3.5 6.5l8.5 6.5 8.5-6.5" />
</Icon>
),
// Calendar with a heart
datum: () => (
<Icon>
<rect x="3.5" y="5" width="17" height="15.5" />
<path d="M3.5 9.5h17M8 3v4M16 3v4" />
<path d="M12 18.6s-3-2.6-3-4.7a3 3 0 0 1 6 0c0 2.1-3 4.7-3 4.7z" />
<circle cx="12" cy="13.9" r="0.8" />
</Icon>
),
// Coin
aanbetaling: () => (
<Icon>
<circle cx="12" cy="12" r="9" />
<path d="M15.5 8.6a4.2 4.2 0 1 0 0 6.8" />
<path d="M7.5 10.9h5.5M7.5 13.1h5.5" />
</Icon>
),
// Camera
shoot: () => (
<Icon>
<path d="M3 8h4l1.6-2.5h6.8L17 8h4v11H3z" />
<circle cx="12" cy="13.5" r="3.5" />
</Icon>
),
// Sliders
bewerking: () => (
<Icon>
<path d="M4 7h9M17 7h3M4 12h4M12 12h8M4 17h3M11 17h9" />
<circle cx="15" cy="7" r="2" />
<circle cx="10" cy="12" r="2" />
<circle cx="9" cy="17" r="2" />
</Icon>
),
// Picture
oplevering: () => (
<Icon>
<rect x="3.5" y="4.5" width="17" height="15" />
<circle cx="9" cy="9.5" r="1.6" />
<path d="M3.5 17l5-4.5 3.5 3 3-2.5 5.5 4.5" />
</Icon>
),
};
@@ -79,4 +79,31 @@ describe('ShootBlock', () => {
expect(main).not.toHaveAttribute('loading', 'lazy');
expect(detail).toHaveAttribute('loading', 'lazy');
});
it.each([
['newborn', 'Lees meer over de newbornshoot'],
['zwangerschap', 'Lees meer over de zwangerschapsshoot'],
['gezin', 'Lees meer over de gezinsshoot'],
['loveshoot', 'Lees meer over de loveshoot'],
['portret', 'Lees meer over de portretshoot'],
])('links %s to its own page with the text "%s"', async (id, text) => {
await renderBlock(id);
const link = screen.getByRole('link', { name: text });
expect(link).toHaveAttribute('href', `/soorten-fotoshoots/${id}`);
expect(link).toBe(screen.getByTestId(`shoot-${id}-readmore`));
// The visible text is the name: no aria-label
expect(link).not.toHaveAttribute('aria-label');
});
it('puts the page link first in the row, before the contact link', async () => {
await renderBlock('newborn', { portfolioLink: true });
const links = within(
screen.getByRole('article', { name: 'Newborn' }),
).getAllByRole('link');
expect(links.map((link) => link.getAttribute('data-testid'))).toEqual([
'shoot-newborn-readmore',
'shoot-newborn-contact',
'shoot-newborn-portfolio',
]);
});
});
@@ -4,7 +4,9 @@ import { Box, Flex, Heading, Link, Stack, Text } from '@chakra-ui/react';
import { Link as RouterLink } from '@tanstack/react-router';
import MediaText from '@/components/MediaText/MediaText';
import type { PricingPackage, ShootType } from '@/content/types';
import { readMoreLabel } from '@/lib/readMoreLabel';
import { shootContactLink, shootPortfolioLink } from '@/lib/shootLinks';
import { shootPagePath } from '@/lib/shootPages';
type ShootBlockProps = {
shoot: ShootType;
@@ -21,7 +23,7 @@ type ShootBlockProps = {
const linkStyle = { py: 2.5, display: 'inline-block' } as const;
// One kind of shoot (design .shoot): its photo next to the name, the text
// and the links. The article is the anchor (#newborn) and is named by its
// and the links, the first of which leads to the shoot's own page. The article is the anchor (#newborn) and is named by its
// heading.
export default function ShootBlock({
shoot,
@@ -59,6 +61,16 @@ export default function ShootBlock({
))}
</Stack>
<Flex wrap="wrap" columnGap={6} mt={3}>
{/* The visible text already differs per shoot, so no
aria-label is needed to tell the links apart */}
<Link variant="underline" asChild {...linkStyle}>
<RouterLink
to={shootPagePath(shoot.id)}
data-testid={`shoot-${shoot.id}-readmore`}
>
{readMoreLabel(shoot)}
</RouterLink>
</Link>
<Link variant="underline" asChild {...linkStyle}>
{/* Five links say "Stuur een berichtje"; the full name
tells screen reader users which shoot each is about.
@@ -74,4 +74,23 @@ describe('ShootList', () => {
);
expect(tones).toEqual([false, true, false, true, false]);
});
it('gives every shoot its own page link, first in its row, with a unique name', async () => {
await renderList();
const ids = shootTypes.map((shoot) => shoot.id);
const names = ids.map((id) => {
const link = screen.getByTestId(`shoot-${id}-readmore`);
expect(link).toHaveAttribute('href', `/soorten-fotoshoots/${id}`);
const article = link.closest('article')!;
expect(within(article).getAllByRole('link')[0]).toBe(link);
return link.textContent;
});
expect(new Set(names).size).toBe(ids.length);
// The other links are still there
for (const id of ids) {
expect(
screen.getByTestId(`shoot-${id}-contact`),
).toBeInTheDocument();
}
});
});
@@ -1,26 +1,66 @@
import { screen } from '@testing-library/react';
import { screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import loveshootPage from '@/content/shootPages/loveshoot';
import newbornPage from '@/content/shootPages/newborn';
import shootPageShared from '@/content/shootPageShared';
import packages from '@/content/packages';
import shootTypes from '@/content/shootTypes';
import siteContent from '@/content/siteContent';
import { shootPageView } from '@/lib/shootPageView';
import type { ShootTypeId } from '@/content/types';
import { shootPageView, type ShootPageView } from '@/lib/shootPageView';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import ShootPage from './ShootPage';
const view = shootPageView('newborn', newbornPage, {
const sources = {
shootTypes,
packages,
shared: shootPageShared,
site: siteContent,
portfolioShoots: [],
});
};
const viewOf = (id: ShootTypeId, page = newbornPage) => {
const view = shootPageView(id, page, {
...sources,
portfolioShoots: [id],
});
if (view === undefined) throw new Error(`no view for ${id}`);
return view;
};
const view = viewOf('newborn');
const loveshootView = viewOf('loveshoot', loveshootPage as typeof newbornPage);
const withoutFaq: ShootPageView = (() => {
const copy = shootPageView(
'newborn',
{ ...newbornPage, faq: { ...newbornPage.faq, items: [] } },
sources,
);
if (copy === undefined) throw new Error('no view');
return copy;
})();
// The heading levels and texts in page order
const outline = (container: HTMLElement) =>
[...container.querySelectorAll('h1, h2, h3, h4, h5, h6')].map(
(heading) => ({
level: Number(heading.tagName[1]),
text: heading.textContent,
}),
);
// No heading level is skipped when going down the page
const expectNoSkippedLevel = (levels: number[]) => {
expect(levels[0]).toBe(1);
levels.slice(1).forEach((level, index) => {
expect(level).toBeLessThanOrEqual(levels[index] + 1);
});
};
describe('ShootPage', () => {
it('toont label, de enige h1 en de intro', async () => {
if (view === undefined) throw new Error('no view for newborn');
const { container } = await renderWithProviders(
<ShootPage view={view} />,
);
@@ -32,4 +72,129 @@ describe('ShootPage', () => {
expect(screen.getByText(view.intro.text)).toBeInTheDocument();
expect(await axeResults(container)).toHaveNoViolations();
});
it('has a clean heading outline for newborn: h1, h2 per section, h3 per step', async () => {
const { container } = await renderWithProviders(
<ShootPage view={view} />,
);
const headings = outline(container);
expectNoSkippedLevel(headings.map((heading) => heading.level));
expect(headings.filter((h) => h.level === 1)).toHaveLength(1);
expect(headings.filter((h) => h.level === 3)).toHaveLength(6);
expect(
headings.filter((h) => h.level === 2).map((h) => h.text),
).toEqual([
...view.stories.map((story) => story.title),
view.process.title,
view.photos!.title,
view.faq!.title,
view.offer.title,
view.closing.title,
]);
expect(await axeResults(container)).toHaveNoViolations();
});
it('has a clean heading outline for the loveshoot, without a mosaic', async () => {
const { container } = await renderWithProviders(
<ShootPage view={loveshootView} />,
);
expectNoSkippedLevel(outline(container).map((h) => h.level));
expect(container.querySelector('#impressie')).toBeNull();
expect(screen.queryByTestId('photo-mosaic')).toBeNull();
expect(container.querySelector('#vragen')).not.toBeNull();
expect(await axeResults(container)).toHaveNoViolations();
});
it('leaves out the FAQ section and keeps the outline valid when there are no questions', async () => {
const { container } = await renderWithProviders(
<ShootPage view={withoutFaq} />,
);
expect(container.querySelector('#vragen')).toBeNull();
expect(screen.queryByTestId('faq-list')).toBeNull();
expectNoSkippedLevel(outline(container).map((h) => h.level));
expect(await axeResults(container)).toHaveNoViolations();
});
it('names every section by an existing heading and offers the anchors', async () => {
const { container } = await renderWithProviders(
<ShootPage view={view} />,
);
const sections = container.querySelectorAll('section');
expect(sections.length).toBe(view.stories.length + 6);
for (const section of sections) {
const target = section.getAttribute('aria-labelledby')!;
expect(target).toBeTruthy();
expect(container.querySelector(`#${target}`)).not.toBeNull();
}
for (const anchor of [
'zo-werkt-het',
'impressie',
'vragen',
'pakket',
]) {
expect(container.querySelector(`section#${anchor}`)).not.toBeNull();
}
});
it('never gives two adjacent bands the same colour', async () => {
const { container } = await renderWithProviders(
<ShootPage view={view} />,
);
const sections = [
...screen
.getByTestId('shoot-page')
.querySelectorAll(':scope > section'),
];
const alt = sections.map((section) =>
cssRulesFor(section).join().includes('var(--slp-colors-paper-alt)'),
);
// The intro is paper; every band after it alternates
// The intro and the first story are both paper on purpose: the
// story has no space above it and continues the intro (flushTop).
// From the first story on, the bands alternate.
expect(alt[0]).toBe(false);
const bands = alt.slice(1);
bands.forEach((isAlt, index) => {
expect(isAlt).toBe(index % 2 === 1);
});
expect(sections).toHaveLength(view.stories.length + 6);
expect(container).toBeTruthy();
});
it('shows the breadcrumb, the package with its actions and the closing button', async () => {
await renderWithProviders(<ShootPage view={view} />);
const crumb = screen.getByTestId('shoot-breadcrumb');
expect(within(crumb).getAllByRole('link')).toHaveLength(2);
const offer = screen.getByTestId('package-block');
expect(
within(offer).getByRole('link', { name: view.offer.bookLabel }),
).toHaveAttribute('href', '/contact?pakket=newborn');
expect(
within(offer).getByRole('link', { name: view.offer.askLabel }),
).toHaveAttribute('href', '/contact');
expect(
within(screen.getByTestId('shoot-closing')).getByRole('link', {
name: view.closing.buttonLabel,
}),
).toHaveAttribute('href', '/contact?pakket=newborn');
expect(
screen.getByRole('link', {
name: `Bekijk meer ${view.shoot.photosLabel}`,
}),
).toHaveAttribute('href', '/portfolio?shoot=newborn');
});
it('shows one primary button and no price for a shoot on request', async () => {
await renderWithProviders(<ShootPage view={loveshootView} />);
const offer = screen.getByTestId('package-block');
expect(
within(offer).getByText(loveshootView.offer.onRequest.price),
).toBeInTheDocument();
expect(within(offer).getAllByRole('link')).toHaveLength(1);
expect(
within(offer).getByRole('link', {
name: loveshootView.offer.onRequest.linkLabel,
}),
).toHaveAttribute('href', '/contact');
});
});
@@ -1,17 +1,217 @@
import type { ReactElement } from 'react';
import { Box, Flex, Grid, Heading, Link, useRecipe } from '@chakra-ui/react';
// The router's own Link keeps the route types, so `search` is checked
// against the target route (as in ShootBlock)
import { Link as RouterLink } from '@tanstack/react-router';
import Breadcrumb from '@/components/Breadcrumb/Breadcrumb';
import CallToAction from '@/components/CallToAction/CallToAction';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import FaqList from '@/components/FaqList/FaqList';
import PackageBlock from '@/components/PackageBlock/PackageBlock';
import PageIntro from '@/components/PageIntro/PageIntro';
import PageSection from '@/components/PageSection/PageSection';
import PhotoMosaic from '@/components/PhotoMosaic/PhotoMosaic';
import ProcessTimeline from '@/components/ProcessTimeline/ProcessTimeline';
import RichParagraph from '@/components/RichParagraph/RichParagraph';
import SectionHeading from '@/components/SectionHeading/SectionHeading';
import { processIcons } from '@/components/shoots/ProcessIcons/ProcessIcons';
import StoryBlocks from '@/components/shoots/StoryBlocks/StoryBlocks';
import { shootPageBands, type SectionBand } from '@/lib/shootPageBands';
import type { ShootPageView } from '@/lib/shootPageView';
type ShootPageProps = {
view: ShootPageView;
};
// One shoot page. For now only the page head with the h1; unit 2 adds the
// sections in the order of the page structure.
// Links under or beside a text: room around them for a 44px touch target
const linkStyle = { py: 2.5, display: 'inline-block' } as const;
// One shoot page (FR-ST-02..08): the intro with the breadcrumb, the story
// blocks, the process timeline, the photos and the FAQ when there are any,
// the offer and the closing block, in the order and colours of
// shootPageBands. Everything comes from the view; nothing is stored here.
export default function ShootPage({ view }: ShootPageProps) {
const { intro } = view;
const { intro, shoot, offer } = view;
const linkButton = useRecipe({ key: 'linkButton' });
// The accent button style for the router's own Link, which keeps the
// route types, so `search` is checked against /contact (as PriceCard)
const accentButton = linkButton({ variant: 'accent' });
const bands = shootPageBands(view);
const tone = (id: SectionBand['id']) =>
bands.find((band) => band.id === id)?.tone ?? 'paper';
return (
<PageIntro eyebrow={intro.eyebrow} title={intro.title}>
{intro.text}
</PageIntro>
<Box data-testid="shoot-page">
<PageIntro
eyebrow={intro.eyebrow}
title={intro.title}
titleId="intro-title"
breadcrumb={
<Breadcrumb
label={view.breadcrumb.label}
items={view.breadcrumb.items}
data-testid="shoot-breadcrumb"
/>
}
>
{intro.text}
</PageIntro>
<StoryBlocks
stories={view.stories}
frameColor={shoot.frameColor}
idPrefix="story"
/>
<PageSection
id="zo-werkt-het"
labelledBy="process-title"
tone={tone('process')}
>
<SectionHeading
id="process-title"
eyebrow={view.process.eyebrow}
title={view.process.title}
lead={view.process.lead}
/>
<ProcessTimeline
steps={view.process.steps.map((step) => {
// An id without an icon gets none (BR-SP-74)
const Icon: (() => ReactElement) | undefined =
processIcons[step.id];
return {
id: step.id,
title: step.title,
text: step.text,
icon: Icon ? <Icon /> : undefined,
};
})}
tone={tone('process')}
data-testid="process-timeline"
/>
</PageSection>
{view.photos && (
<PageSection
id="impressie"
labelledBy="photos-title"
tone={tone('photos')}
>
<Flex
wrap="wrap"
justify="space-between"
align="end"
columnGap={6}
mb="sectionHeadGap"
>
<Box>
<Eyebrow>{view.photos.eyebrow}</Eyebrow>
<Heading
as="h2"
id="photos-title"
textStyle="sectionTitle"
>
{view.photos.title}
</Heading>
</Box>
{view.photos.portfolioLink && (
<Link variant="underline" asChild {...linkStyle}>
<RouterLink {...view.photos.portfolioLink}>
Bekijk meer {shoot.photosLabel}
</RouterLink>
</Link>
)}
</Flex>
<PhotoMosaic
images={view.photos.images}
data-testid="photo-mosaic"
/>
</PageSection>
)}
{view.faq && (
<PageSection
id="vragen"
labelledBy="faq-title"
tone={tone('faq')}
>
<Grid
templateColumns={{ base: '1fr', lg: '1fr 2fr' }}
gap="clamp(2rem, 6vw, 5.5rem)"
alignItems="start"
>
<Box color="ink.soft">
<Eyebrow>{view.faq.eyebrow}</Eyebrow>
<Heading
as="h2"
id="faq-title"
textStyle="sectionTitle"
mb={4}
>
{view.faq.title}
</Heading>
<RichParagraph paragraph={view.faq.lead} />
</Box>
<FaqList
items={view.faq.items}
data-testid="faq-list"
/>
</Grid>
</PageSection>
)}
<PageSection
id="pakket"
labelledBy="offer-title"
tone={tone('offer')}
>
<PackageBlock
titleId="offer-title"
eyebrow={offer.eyebrow}
title={offer.title}
image={offer.image}
frameColor={shoot.frameColor}
pkg={offer.pkg}
onRequest={offer.onRequest}
note={offer.depositNote}
data-testid="package-block"
>
{offer.pkg ? (
<>
<Box asChild css={accentButton}>
<RouterLink {...offer.bookLink}>
{offer.bookLabel}
</RouterLink>
</Box>
<Link variant="underline" asChild {...linkStyle}>
<RouterLink {...offer.askLink}>
{offer.askLabel}
</RouterLink>
</Link>
</>
) : (
<Box asChild css={accentButton}>
<RouterLink {...offer.bookLink}>
{offer.onRequest.linkLabel}
</RouterLink>
</Box>
)}
</PackageBlock>
</PageSection>
<CallToAction
title={view.closing.title}
titleId="closing-title"
lead={<RichParagraph paragraph={view.closing.lead} />}
tone={tone('closing')}
data-testid="shoot-closing"
>
<Box asChild css={accentButton}>
<RouterLink {...view.closing.link}>
{view.closing.buttonLabel}
</RouterLink>
</Box>
</CallToAction>
</Box>
);
}
@@ -0,0 +1,119 @@
import { screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import loveshootPage from '@/content/shootPages/loveshoot';
import newbornPage from '@/content/shootPages/newborn';
import type { StoryBlock } from '@/content/types';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import StoryBlocks from './StoryBlocks';
const tone = (element: HTMLElement) =>
cssRulesFor(element).join().includes('var(--slp-colors-paper-alt)')
? 'alt'
: 'paper';
describe('StoryBlocks', () => {
it('shows one section per newborn story, each named by its h2', async () => {
const stories = newbornPage.stories;
const { container } = await renderWithProviders(
<StoryBlocks
stories={stories}
frameColor="frame.stone"
idPrefix="story"
/>,
);
expect(container.querySelectorAll('section')).toHaveLength(4);
for (const story of stories) {
const section = screen.getByTestId(`story-${story.id}`);
expect(screen.getByRole('region', { name: story.title })).toBe(
section,
);
expect(
within(section).getByRole('heading', { level: 2 }),
).toHaveTextContent(story.title);
}
expect(await axeResults(container)).toHaveNoViolations();
});
it('loads only the first photo with priority and alternates the tones', async () => {
const stories = newbornPage.stories;
await renderWithProviders(
<StoryBlocks
stories={stories}
frameColor="frame.stone"
idPrefix="story"
/>,
);
const images = screen.getAllByRole('img');
expect(images).toHaveLength(stories.length);
expect(images[0]).toHaveAttribute('fetchpriority', 'high');
expect(images[0]).not.toHaveAttribute('loading', 'lazy');
for (const image of images.slice(1)) {
expect(image).toHaveAttribute('loading', 'lazy');
expect(image).not.toHaveAttribute('fetchpriority');
}
expect(
stories.map((story) =>
tone(screen.getByTestId(`story-${story.id}`)),
),
).toEqual(['paper', 'alt', 'paper', 'alt']);
});
it('gives the loveshoot one photo and three text-only bands', async () => {
const { container } = await renderWithProviders(
<StoryBlocks
stories={loveshootPage.stories}
frameColor="accent"
idPrefix="story"
/>,
);
expect(container.querySelectorAll('section')).toHaveLength(4);
expect(screen.getAllByRole('img')).toHaveLength(1);
for (const story of loveshootPage.stories.slice(1)) {
const section = screen.getByTestId(`story-${story.id}`);
expect(within(section).queryByRole('img')).toBeNull();
expect(
within(section).getByRole('heading', { level: 2 }),
).toHaveTextContent(story.title);
}
expect(await axeResults(container)).toHaveNoViolations();
});
it('gives hostile story ids valid aria-labelledby targets', async () => {
const stories: StoryBlock[] = [
{
id: 'Met Spatie',
eyebrow: 'a',
title: 'Een',
paragraphs: [['x']],
},
{
id: '</script>',
eyebrow: 'b',
title: 'Twee',
paragraphs: [['y']],
},
];
const { container } = await renderWithProviders(
<StoryBlocks
stories={stories}
frameColor="sand"
idPrefix="story"
/>,
);
for (const section of container.querySelectorAll('section')) {
const target = section.getAttribute('aria-labelledby')!;
expect(target).toMatch(/^[a-z0-9\-_]+$/);
expect(container.querySelector(`#${target}`)).not.toBeNull();
}
expect(await axeResults(container)).toHaveNoViolations();
});
it('renders nothing without stories', async () => {
const { container } = await renderWithProviders(
<StoryBlocks stories={[]} frameColor="sand" idPrefix="story" />,
);
expect(container.querySelector('section')).toBeNull();
});
});
@@ -0,0 +1,90 @@
import { Box, Heading, Stack } from '@chakra-ui/react';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import MediaText from '@/components/MediaText/MediaText';
import PageSection from '@/components/PageSection/PageSection';
import Reveal from '@/components/Reveal/Reveal';
import RichParagraph from '@/components/RichParagraph/RichParagraph';
import type { FrameColor, StoryBlock } from '@/content/types';
import { headingId } from '@/lib/headingId';
import { storyLayout } from '@/lib/storyLayout';
type StoryBlocksProps = {
stories: readonly StoryBlock[];
// Colour of the block behind every photo
frameColor: FrameColor;
// Start of the heading ids, so they cannot clash with other ids
idPrefix: string;
};
// The story blocks of a shoot page (FR-ST-03, BR-SP-10..14): one band per
// story, named by its h2. Tone, side, spacing and the photo's shape come
// from storyLayout. A story without a photo is a text-only band in a
// narrow column, with no frame and no empty column.
export default function StoryBlocks({
stories,
frameColor,
idPrefix,
}: StoryBlocksProps) {
const layouts = storyLayout(stories);
return (
<>
{stories.map((story, index) => {
const layout = layouts[index];
const titleId = `${headingId(idPrefix, story.id)}-title`;
const text = (
<>
<Eyebrow>{story.eyebrow}</Eyebrow>
<Heading
as="h2"
id={titleId}
textStyle="sectionTitle"
mb={5}
>
{story.title}
</Heading>
<Stack gap={4} color="ink.soft">
{story.paragraphs.map((paragraph, number) => (
// Static content: the order never changes
<RichParagraph
key={number}
paragraph={paragraph}
/>
))}
</Stack>
</>
);
return (
<PageSection
key={story.id}
labelledBy={titleId}
tone={layout.tone}
spacing={layout.spacing}
width={story.image === undefined ? 'narrow' : 'default'}
data-testid={`story-${story.id}`}
>
{story.image !== undefined && layout.media ? (
<MediaText
image={story.image}
aspectRatio={layout.media.aspectRatio}
mediaSize={layout.media.mediaSize}
reverse={layout.reverse}
priority={layout.priority}
frameColor={frameColor}
>
{text}
</MediaText>
) : (
<Reveal>
<Box maxW="36rem" mx="auto">
{text}
</Box>
</Reveal>
)}
</PageSection>
);
})}
</>
);
}
+114
View File
@@ -0,0 +1,114 @@
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useRef } from 'react';
import { describe, expect, it, vi } from 'vitest';
import useDismiss, { type DismissReason } from './useDismiss';
function Harness({
active,
onDismiss,
}: {
active: boolean;
onDismiss: (reason: DismissReason) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useDismiss(ref, active, onDismiss);
return (
<>
<div ref={ref}>
<button>inside</button>
</div>
<button>outside</button>
</>
);
}
describe('useDismiss', () => {
it('reports Escape while active', async () => {
const onDismiss = vi.fn();
render(<Harness active onDismiss={onDismiss} />);
await userEvent.keyboard('{Escape}');
expect(onDismiss).toHaveBeenCalledExactlyOnceWith('escape');
});
it('ignores other keys', async () => {
const onDismiss = vi.fn();
render(<Harness active onDismiss={onDismiss} />);
await userEvent.keyboard('a{Enter}{Tab}');
expect(onDismiss).not.toHaveBeenCalled();
});
it('reports a pointer down outside, not inside', async () => {
const onDismiss = vi.fn();
render(<Harness active onDismiss={onDismiss} />);
await userEvent.click(screen.getByRole('button', { name: 'inside' }));
expect(onDismiss).not.toHaveBeenCalled();
await userEvent.click(screen.getByRole('button', { name: 'outside' }));
expect(onDismiss).toHaveBeenCalledExactlyOnceWith('outside');
});
it('reports nothing while inactive', async () => {
const onDismiss = vi.fn();
render(<Harness active={false} onDismiss={onDismiss} />);
await userEvent.keyboard('{Escape}');
await userEvent.click(screen.getByRole('button', { name: 'outside' }));
expect(onDismiss).not.toHaveBeenCalled();
});
it('starts and stops listening when active changes', async () => {
const onDismiss = vi.fn();
const { rerender } = render(
<Harness active={false} onDismiss={onDismiss} />,
);
rerender(<Harness active onDismiss={onDismiss} />);
await userEvent.keyboard('{Escape}');
expect(onDismiss).toHaveBeenCalledTimes(1);
rerender(<Harness active={false} onDismiss={onDismiss} />);
await userEvent.keyboard('{Escape}');
expect(onDismiss).toHaveBeenCalledTimes(1);
});
it('removes its listeners on unmount', async () => {
const onDismiss = vi.fn();
const { unmount } = render(<Harness active onDismiss={onDismiss} />);
const remove = vi.spyOn(document, 'removeEventListener');
unmount();
expect(remove.mock.calls.map(([type]) => type).sort()).toEqual([
'keydown',
'pointerdown',
]);
await userEvent.keyboard('{Escape}');
fireEvent.pointerDown(document.body);
expect(onDismiss).not.toHaveBeenCalled();
});
it('calls the latest callback once without re-subscribing', async () => {
const first = vi.fn();
const second = vi.fn();
const { rerender } = render(<Harness active onDismiss={first} />);
const add = vi.spyOn(document, 'addEventListener');
rerender(<Harness active onDismiss={second} />);
expect(add).not.toHaveBeenCalled();
await userEvent.keyboard('{Escape}');
expect(first).not.toHaveBeenCalled();
expect(second).toHaveBeenCalledTimes(1);
});
it('ignores a pointer down whose target is not a Node', () => {
const onDismiss = vi.fn();
render(<Harness active onDismiss={onDismiss} />);
fireEvent.pointerDown(window);
expect(onDismiss).not.toHaveBeenCalled();
});
it('ignores a pointer down when the ref is empty', () => {
const onDismiss = vi.fn();
function Detached() {
useDismiss({ current: null }, true, onDismiss);
return null;
}
render(<Detached />);
fireEvent.pointerDown(document.body);
expect(onDismiss).not.toHaveBeenCalled();
});
});
+39
View File
@@ -0,0 +1,39 @@
import { useEffect, useRef, type RefObject } from 'react';
export type DismissReason = 'escape' | 'outside';
// Reports Escape and a pointer down outside `ref` while `active` is true.
// It only listens: what a dismissal means is up to the caller (FR-ST-10).
// The listeners exist only while active and are removed on deactivation and
// unmount. A missing element or a target that is no Node is ignored.
export default function useDismiss(
ref: RefObject<HTMLElement | null>,
active: boolean,
onDismiss: (reason: DismissReason) => void,
) {
// The latest callback, so a new function identity does not re-subscribe
const callback = useRef(onDismiss);
useEffect(() => {
callback.current = onDismiss;
}, [onDismiss]);
useEffect(() => {
if (!active) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') callback.current('escape');
};
const onPointerDown = (event: PointerEvent) => {
const element = ref.current;
if (!element || !(event.target instanceof Node)) return;
if (!element.contains(event.target)) callback.current('outside');
};
document.addEventListener('keydown', onKeyDown);
document.addEventListener('pointerdown', onPointerDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('pointerdown', onPointerDown);
};
}, [active, ref]);
}
+52
View File
@@ -0,0 +1,52 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { shootTypeId } from '@/test/arbitraries';
import { headingId } from './headingId';
describe('headingId', () => {
it.each([
['story', 'verwachten', 'story-verwachten'],
['story', 'Met Spatie', 'story-met-spatie'],
['story', 'UPPER', 'story-upper'],
['story', '</script>', 'story---script-'],
['story', '', 'story-'],
['story', 'één', 'story---n'],
['Story', 'a_b-c', 'story-a_b-c'],
])('maps (%s, %s) to %s', (prefix, id, expected) => {
expect(headingId(prefix, id)).toBe(expected);
});
it('keeps the five real shoot ids readable', () => {
for (const id of [
'newborn',
'zwangerschap',
'gezin',
'loveshoot',
'portret',
]) {
expect(headingId('shoot', id)).toBe(`shoot-${id}`);
}
});
it('only produces a-z, 0-9, - and _, and is deterministic (invariant)', () => {
fc.assert(
fc.property(
fc.oneof(
fc.string(),
fc.string({ unit: 'binary' }),
shootTypeId,
),
fc.oneof(
fc.string(),
fc.string({ unit: 'binary' }),
fc.constantFrom('</script>', ' ', '"', "'", '\u0130'),
),
(prefix, id) => {
const result = headingId(prefix, id);
expect(result).toMatch(/^[a-z0-9\-_]*$/);
expect(headingId(prefix, id)).toBe(result);
},
),
);
});
});
+7
View File
@@ -0,0 +1,7 @@
// An id for a heading that aria-labelledby can always point at: lower-case
// letters, digits, '-' and '_' only. Anything else, such as a space in a
// story id from the content, becomes '-' (BR-SP-72). The caller adds
// '-title' where the id belongs to a heading.
export function headingId(prefix: string, id: string): string {
return `${prefix}-${id}`.toLowerCase().replace(/[^a-z0-9\-_]/g, '-');
}
+52
View File
@@ -0,0 +1,52 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { isShootSectionPath } from './isShootSectionPath';
// Het prefix in willekeurige hoofd- en kleine letters
const prefixInRandomCase = fc
.array(fc.boolean(), { minLength: 20, maxLength: 20 })
.map((flags) =>
[...'/soorten-fotoshoots/']
.map((ch, i) => (flags[i] ? ch.toUpperCase() : ch))
.join(''),
);
describe('isShootSectionPath', () => {
it.each([
['/soorten-fotoshoots/niet-bestaande-shoot', true],
['/Soorten-Fotoshoots/x', true],
['/soorten-fotoshoots/', true],
['/soorten-fotoshoots', false],
['/soorten-fotoshootsx/abc', false],
['/bestaat-niet', false],
['/', false],
])('%s geeft %s', (path, expected) => {
expect(isShootSectionPath(path)).toBe(expected);
});
it('is true voor elk pad met het prefix, in elke schrijfwijze (property)', () => {
fc.assert(
fc.property(prefixInRandomCase, fc.string(), (prefix, rest) => {
expect(isShootSectionPath(prefix + rest)).toBe(true);
}),
);
});
it('is false voor paden zonder het prefix (property)', () => {
fc.assert(
fc.property(
fc
.string()
.filter(
(path) =>
!path
.toLowerCase()
.startsWith('/soorten-fotoshoots/'),
),
(path) => {
expect(isShootSectionPath(path)).toBe(false);
},
),
);
});
});
+7
View File
@@ -0,0 +1,7 @@
const SHOOT_SECTION_PREFIX = '/soorten-fotoshoots/';
// Staat het pad onder /soorten-fotoshoots/ (FR-ST-14)? Hoofdletterongevoelig,
// net als de router. Het overzicht zelf (zonder slash) hoort er niet bij.
export function isShootSectionPath(pathname: string): boolean {
return pathname.toLowerCase().startsWith(SHOOT_SECTION_PREFIX);
}
+96
View File
@@ -0,0 +1,96 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { mosaicCount } from '@/test/arbitraries';
import {
MOSAIC_MAX_PHOTOS,
mosaicLayout,
type MosaicTile,
} from './mosaicLayout';
// The grid cells ("column,row") a tile covers, from its 'start / end' strings
function cells(tile: MosaicTile): string[] {
const [c0, c1] = tile.column.split(' / ').map(Number);
const [r0, r1] = tile.row.split(' / ').map(Number);
const result: string[] = [];
for (let c = c0; c < c1; c++) {
for (let r = r0; r < r1; r++) result.push(`${c},${r}`);
}
return result;
}
describe('mosaicLayout', () => {
it('gives nothing for 0, a negative or a fractional count', () => {
expect(mosaicLayout(0)).toEqual([]);
expect(mosaicLayout(-1)).toEqual([]);
expect(mosaicLayout(1.5)).toEqual([]);
expect(mosaicLayout(Number.NaN)).toEqual([]);
});
it('gives one wide tile for 1', () => {
expect(mosaicLayout(1)).toEqual([
{ column: '1 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' },
]);
});
it('gives two equal tiles for 2', () => {
expect(mosaicLayout(2)).toEqual([
{ column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' },
{ column: '3 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' },
]);
});
it('gives a large and two wide tiles for 3', () => {
expect(mosaicLayout(3).map((tile) => tile.phoneRatio)).toEqual([
'4 / 3',
'3 / 2',
'3 / 2',
]);
expect(mosaicLayout(3)[2]).toMatchObject({
column: '3 / 5',
row: '2 / 3',
});
});
it('gives design E for 4, and the same for 5 or more', () => {
expect(mosaicLayout(4)).toEqual([
{ column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' },
{ column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' },
{ column: '3 / 4', row: '2 / 3', wide: false, phoneRatio: '1 / 1' },
{ column: '4 / 5', row: '2 / 3', wide: false, phoneRatio: '1 / 1' },
]);
expect(mosaicLayout(5)).toEqual(mosaicLayout(4));
expect(mosaicLayout(12)).toEqual(mosaicLayout(4));
});
it('returns fresh objects, so a caller cannot change the layout', () => {
mosaicLayout(4)[0].column = 'x';
expect(mosaicLayout(4)[0].column).toBe('1 / 3');
});
it('fills the 4 x 2 grid without overlap and stays well formed (invariant)', () => {
fc.assert(
fc.property(mosaicCount, (count) => {
const tiles = mosaicLayout(count);
expect(mosaicLayout(count)).toEqual(tiles);
if (count <= 0) {
expect(tiles).toEqual([]);
return;
}
expect(tiles).toHaveLength(Math.min(count, MOSAIC_MAX_PHOTOS));
const covered = tiles.flatMap(cells);
expect(new Set(covered).size).toBe(covered.length);
if (count >= 2) expect(covered).toHaveLength(8);
if (count >= 2) {
// (A single photo, never shown, spans the whole grid)
expect(tiles[0]).toMatchObject({
column: '1 / 3',
row: '1 / 3',
});
expect(tiles.filter((tile) => !tile.wide).length % 2).toBe(
0,
);
}
}),
);
});
});
+50
View File
@@ -0,0 +1,50 @@
// The photo mosaic of a shoot page: a 4 x 2 grid from `md`, two columns on
// phones (FR-ST-05). Each tile says where it sits; the component only
// draws them.
// The most photos the mosaic shows; more stay in the content
export const MOSAIC_MAX_PHOTOS = 4;
export interface MosaicTile {
// CSS grid-column from `md`, e.g. '1 / 3'
column: string;
// CSS grid-row from `md`
row: string;
// Spans both columns below `md`
wide: boolean;
// Aspect ratio of the tile below `md`
phoneRatio: '4 / 3' | '3 / 2' | '1 / 1';
}
const large: MosaicTile = {
column: '1 / 3',
row: '1 / 3',
wide: true,
phoneRatio: '4 / 3',
};
const layouts: Record<1 | 2 | 3 | 4, readonly MosaicTile[]> = {
// Never shown (the view needs at least two photos), kept so that the
// function is total
1: [{ column: '1 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }],
2: [large, { ...large, column: '3 / 5' }],
3: [
large,
{ column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' },
{ column: '3 / 5', row: '2 / 3', wide: true, phoneRatio: '3 / 2' },
],
4: [
large,
{ column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' },
{ column: '3 / 4', row: '2 / 3', wide: false, phoneRatio: '1 / 1' },
{ column: '4 / 5', row: '2 / 3', wide: false, phoneRatio: '1 / 1' },
],
};
// The tiles for `count` photos. Nothing for a count below 1 or one that is
// not a whole number (fail safe); five or more get the layout for four.
export function mosaicLayout(count: number): MosaicTile[] {
if (!Number.isInteger(count) || count < 1) return [];
const key = Math.min(count, MOSAIC_MAX_PHOTOS) as 1 | 2 | 3 | 4;
return layouts[key].map((tile) => ({ ...tile }));
}
+200
View File
@@ -0,0 +1,200 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import type { NavItem } from '../navigation';
import { knownRoutePath, uniqueShootTypes } from '../test/arbitraries';
import { pathname } from '../test/navArbitraries';
import { isItemCurrent, isSectionCurrent } from './navCurrent';
import { shootNavItems } from './shootNavItems';
// The comparison rule written out once more: lower case, one trailing slash
const normalise = (path: string) => {
const lower = path.toLowerCase();
return lower.length > 1 && lower.endsWith('/') ? lower.slice(0, -1) : lower;
};
const item = fc.record({ to: knownRoutePath, label: fc.string() });
// The overview with a random set of shoot pages as children
const parent = uniqueShootTypes.map((shoots): NavItem => ({
to: '/soorten-fotoshoots',
label: 'Soorten fotoshoots',
children: shootNavItems(shoots),
}));
describe('isItemCurrent', () => {
it('is true exactly when the normalised paths are equal (invariant)', () => {
fc.assert(
fc.property(item, pathname, (nav, path) => {
expect(isItemCurrent(nav, path)).toBe(
normalise(nav.to) === normalise(path),
);
}),
);
});
it('is true for its own path in every spelling (invariant)', () => {
fc.assert(
fc.property(item, (nav) => {
for (const spelling of [
nav.to,
`${nav.to}/`,
nav.to.toUpperCase(),
`${nav.to.toUpperCase()}/`,
]) {
expect(isItemCurrent(nav, spelling)).toBe(true);
}
}),
);
});
it('is not changed by letter case or one added trailing slash (idempotency)', () => {
fc.assert(
fc.property(item, pathname, (nav, path) => {
// '' and '/' have no "added slash" twin that means the same
fc.pre(path.length > 0 && path !== '/');
const result = isItemCurrent(nav, path);
expect(isItemCurrent(nav, path.toUpperCase())).toBe(
isItemCurrent(nav, path.toLowerCase()),
);
// Adding a slash to a path without one gives the same answer
fc.pre(!path.endsWith('/'));
expect(isItemCurrent(nav, `${path}/`)).toBe(result);
}),
);
});
it('is false for a path that normalises differently (invariant)', () => {
fc.assert(
fc.property(item, pathname, (nav, path) => {
fc.pre(normalise(nav.to) !== normalise(path));
expect(isItemCurrent(nav, path)).toBe(false);
}),
);
});
it('accepts the item path with a trailing slash and other case', () => {
const nav: NavItem = { to: '/portfolio', label: 'Portfolio' };
expect(isItemCurrent(nav, '/portfolio')).toBe(true);
expect(isItemCurrent(nav, '/portfolio/')).toBe(true);
expect(isItemCurrent(nav, '/Portfolio')).toBe(true);
expect(isItemCurrent(nav, '/')).toBe(false);
});
it('keeps the home page apart from every other path', () => {
const home: NavItem = { to: '/', label: 'Home' };
expect(isItemCurrent(home, '/')).toBe(true);
expect(isItemCurrent(home, '')).toBe(false);
expect(isItemCurrent(home, '/portfolio')).toBe(false);
});
});
describe('isSectionCurrent', () => {
it('is implied by isItemCurrent (invariant)', () => {
fc.assert(
fc.property(parent, pathname, (nav, path) => {
fc.pre(isItemCurrent(nav, path));
expect(isSectionCurrent(nav, path)).toBe(true);
}),
);
});
it('is implied by any child being current (invariant)', () => {
fc.assert(
fc.property(parent, fc.nat(), (nav, index) => {
const children = nav.children ?? [];
fc.pre(children.length > 0);
const child = children[index % children.length];
expect(isSectionCurrent(nav, child.to)).toBe(true);
expect(isSectionCurrent(nav, `${child.to}/`)).toBe(true);
expect(isSectionCurrent(nav, child.to.toUpperCase())).toBe(
true,
);
}),
);
});
it('is true only for the item or a child (invariant)', () => {
fc.assert(
fc.property(parent, pathname, (nav, path) => {
const expected =
isItemCurrent(nav, path) ||
(nav.children ?? []).some((child) =>
isItemCurrent(child, path),
);
expect(isSectionCurrent(nav, path)).toBe(expected);
}),
);
});
it('is false for unrelated paths and prefix look-alikes (invariant)', () => {
fc.assert(
fc.property(
parent,
fc.constantFrom(
'/',
'/portfolio',
'/contact',
'/soorten-fotoshoots-extra',
'/soorten-fotoshootsX',
'/soorten-fotoshoots/newborn/extra',
'/soorten-fotoshoots/onbekend',
),
(nav, path) => {
expect(isSectionCurrent(nav, path)).toBe(false);
},
),
);
});
it('is false on the home page for the overview', () => {
const nav: NavItem = {
to: '/soorten-fotoshoots',
label: 'Soorten fotoshoots',
children: shootNavItems([]),
};
expect(isSectionCurrent(nav, '/')).toBe(false);
});
it('marks the parent as section and the child as item on a shoot page', () => {
const child: NavItem = {
to: '/soorten-fotoshoots/newborn',
label: 'Newborn',
};
const nav: NavItem = {
to: '/soorten-fotoshoots',
label: 'Soorten fotoshoots',
children: [child],
};
expect(isSectionCurrent(nav, '/soorten-fotoshoots/newborn/')).toBe(
true,
);
expect(isItemCurrent(child, '/soorten-fotoshoots/newborn/')).toBe(true);
expect(isItemCurrent(nav, '/soorten-fotoshoots/newborn/')).toBe(false);
});
it('works for an item without children', () => {
const nav: NavItem = { to: '/contact', label: 'Contact' };
expect(isSectionCurrent(nav, '/contact')).toBe(true);
expect(isSectionCurrent(nav, '/portfolio')).toBe(false);
});
});
describe('hostile pathnames', () => {
it('always gives a boolean and does not throw (invariant)', () => {
fc.assert(
fc.property(parent, fc.string(), (nav, path) => {
expect(typeof isItemCurrent(nav, path)).toBe('boolean');
expect(typeof isSectionCurrent(nav, path)).toBe('boolean');
}),
);
});
it.each(['', '//', ' ', '%2F', '/%2F', 'a'.repeat(100_000)])(
'handles %j without throwing',
(path) => {
const nav: NavItem = { to: '/', label: 'Home' };
expect(() => isItemCurrent(nav, path)).not.toThrow();
expect(() => isSectionCurrent(nav, path)).not.toThrow();
},
);
});
+24
View File
@@ -0,0 +1,24 @@
import type { NavItem } from '../navigation.ts';
// Lower case and without one trailing slash (not for "/"), the way the
// router matches a path (BR-NAV-04)
function normalise(path: string): string {
const lower = path.toLowerCase();
return lower.length > 1 && lower.endsWith('/') ? lower.slice(0, -1) : lower;
}
// Whether the item is the page at `pathname`. Pure string comparison: never
// throws and never renders the pathname (SECURITY-05, SECURITY-15).
export function isItemCurrent(item: NavItem, pathname: string): boolean {
return normalise(item.to) === normalise(pathname);
}
// Whether the item or one of its children is the page at `pathname`; marks
// the parent while a page below it is open (D4)
export function isSectionCurrent(item: NavItem, pathname: string): boolean {
return (
isItemCurrent(item, pathname) ||
(item.children?.some((child) => isItemCurrent(child, pathname)) ??
false)
);
}
+398
View File
@@ -0,0 +1,398 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
navMenuEvent,
navMenuEvents,
navMenuState,
navMenuStateOn,
} from '../test/navArbitraries';
import {
initialNavMenuState,
navMenuReducer,
type NavMenuEvent,
type NavMenuState,
} from './navMenuState';
const reduce = (events: readonly NavMenuEvent[], start = initialNavMenuState) =>
events.reduce(navMenuReducer, start);
const closed: NavMenuState = { ...initialNavMenuState };
const mobile: NavMenuState = { ...closed, isDesktop: false };
const desktop: NavMenuState = { ...closed, isDesktop: true };
const mobileOpen: NavMenuState = { ...mobile, menuOpen: true };
const mobileGroup: NavMenuState = { ...mobileOpen, groupOpen: true };
const desktopOpen: NavMenuState = { ...desktop, submenuOpen: true };
// The invariants I1-I4 of the domain model
function expectInvariants(state: NavMenuState) {
if (state.submenuOpen) expect(state.isDesktop).toBe(true);
if (state.menuOpen) expect(state.isDesktop).toBe(false);
if (state.groupOpen) expect(state.menuOpen).toBe(true);
if (state.focusRequest === 'menuToggle') {
expect(state.isDesktop).toBe(false);
}
if (state.focusRequest === 'submenuToggle') {
expect(state.isDesktop).toBe(true);
}
}
// An independent, deliberately plain model of the transition table, written
// per field instead of per event as the reducer does
function model(state: NavMenuState, event: NavMenuEvent) {
const next = { ...state };
const everythingClosed = () => {
next.menuOpen = false;
next.groupOpen = false;
next.submenuOpen = false;
};
if (event.type === 'viewport') {
next.isDesktop = event.isDesktop;
if (event.isDesktop) {
next.menuOpen = false;
next.groupOpen = false;
} else {
next.submenuOpen = false;
}
if (event.isDesktop && next.focusRequest === 'menuToggle') {
next.focusRequest = null;
}
if (!event.isDesktop && next.focusRequest === 'submenuToggle') {
next.focusRequest = null;
}
} else if (event.type === 'toggleMenu' && !state.isDesktop) {
next.menuOpen = !state.menuOpen;
next.groupOpen = next.menuOpen ? event.inSection : false;
} else if (event.type === 'toggleGroup' && state.menuOpen) {
next.groupOpen = !state.groupOpen;
} else if (event.type === 'toggleSubmenu' && state.isDesktop) {
next.submenuOpen = !state.submenuOpen;
} else if (event.type === 'escape' && state.menuOpen) {
next.menuOpen = false;
next.groupOpen = false;
next.focusRequest = event.focusInside ? 'menuToggle' : null;
} else if (event.type === 'escape' && state.submenuOpen) {
next.submenuOpen = false;
next.focusRequest = event.focusInside ? 'submenuToggle' : null;
} else if (
(event.type === 'outside' || event.type === 'focusLeave') &&
state.submenuOpen
) {
next.submenuOpen = false;
} else if (event.type === 'linkChosen' || event.type === 'routeChanged') {
everythingClosed();
next.focusRequest = null;
} else if (event.type === 'focusHandled') {
next.focusRequest = null;
}
return next;
}
describe('navMenuReducer (stateful)', () => {
it('keeps I1-I4 and follows the model after every event (stateful)', () => {
fc.assert(
fc.property(navMenuEvents, (events) => {
let state = initialNavMenuState;
for (const event of events) {
const expected = model(state, event);
state = navMenuReducer(state, event);
expect(state).toEqual(expected);
expectInvariants(state);
}
}),
);
});
it('starts all closed and keeps the invariants for any reached state', () => {
expectInvariants(initialNavMenuState);
fc.assert(
fc.property(navMenuState, (state) => {
expectInvariants(state);
}),
);
});
it('returns the same object when an event does not apply (invariant)', () => {
fc.assert(
fc.property(navMenuState, navMenuEvent, (state, event) => {
const next = navMenuReducer(state, event);
if (JSON.stringify(next) === JSON.stringify(state)) {
expect(next).toBe(state);
}
}),
);
});
});
describe('navMenuReducer (idempotency)', () => {
it('ends all closed after routeChanged or linkChosen, twice as once (idempotency)', () => {
fc.assert(
fc.property(
navMenuState,
fc.constantFrom('routeChanged', 'linkChosen'),
(state, type) => {
const once = navMenuReducer(state, { type });
expect(once.menuOpen).toBe(false);
expect(once.groupOpen).toBe(false);
expect(once.submenuOpen).toBe(false);
expect(once.focusRequest).toBeNull();
expect(once.isDesktop).toBe(state.isDesktop);
expect(navMenuReducer(once, { type })).toEqual(once);
},
),
);
});
it('closes the same on escape twice as once, apart from the focus request (idempotency)', () => {
fc.assert(
fc.property(navMenuState, fc.boolean(), (state, focusInside) => {
const event = { type: 'escape', focusInside } as const;
const once = navMenuReducer(state, event);
const twice = navMenuReducer(once, event);
expect({ ...twice, focusRequest: null }).toEqual({
...once,
focusRequest: null,
});
}),
);
});
it('closes the submenu on outside or focusLeave without touching the rest (invariant)', () => {
fc.assert(
fc.property(
navMenuState,
fc.constantFrom('outside', 'focusLeave'),
(state, type) => {
const once = navMenuReducer(state, { type });
expect(once.menuOpen).toBe(state.menuOpen);
expect(once.groupOpen).toBe(state.groupOpen);
expect(once.focusRequest).toBe(state.focusRequest);
expect(once.submenuOpen).toBe(false);
expect(navMenuReducer(once, { type })).toBe(once);
},
),
);
});
});
describe('navMenuReducer (invariant)', () => {
it('gives back the original state after two submenu toggles on desktop (invariant)', () => {
fc.assert(
fc.property(navMenuStateOn(true), (state) => {
const twice = reduce(
[{ type: 'toggleSubmenu' }, { type: 'toggleSubmenu' }],
state,
);
expect(twice).toEqual(state);
}),
);
});
it('leaves no mobile state open after viewport(true) (invariant)', () => {
fc.assert(
fc.property(navMenuState, (state) => {
const next = navMenuReducer(state, {
type: 'viewport',
isDesktop: true,
});
expect(next.isDesktop).toBe(true);
expect(next.menuOpen).toBe(false);
expect(next.groupOpen).toBe(false);
}),
);
});
it('leaves no submenu open after viewport(false) (invariant)', () => {
fc.assert(
fc.property(navMenuState, (state) => {
const next = navMenuReducer(state, {
type: 'viewport',
isDesktop: false,
});
expect(next.isDesktop).toBe(false);
expect(next.submenuOpen).toBe(false);
}),
);
});
it('opens the menu with the group set to inSection and closes both (invariant)', () => {
fc.assert(
fc.property(fc.boolean(), (inSection) => {
const open = navMenuReducer(mobile, {
type: 'toggleMenu',
inSection,
});
expect(open.menuOpen).toBe(true);
expect(open.groupOpen).toBe(inSection);
const shut = navMenuReducer(open, {
type: 'toggleMenu',
inSection,
});
expect(shut.menuOpen).toBe(false);
expect(shut.groupOpen).toBe(false);
}),
);
});
});
describe('navMenuReducer (examples)', () => {
it('viewport sets the width and closes what no longer exists', () => {
expect(
navMenuReducer(initialNavMenuState, {
type: 'viewport',
isDesktop: true,
}),
).toEqual(desktop);
expect(
navMenuReducer(mobileGroup, { type: 'viewport', isDesktop: true }),
).toEqual(desktop);
expect(
navMenuReducer(desktopOpen, { type: 'viewport', isDesktop: false }),
).toEqual(mobile);
});
it('viewport drops a focus request that no longer fits', () => {
expect(
navMenuReducer(
{ ...desktop, focusRequest: 'submenuToggle' },
{ type: 'viewport', isDesktop: false },
).focusRequest,
).toBeNull();
expect(
navMenuReducer(
{ ...mobile, focusRequest: 'menuToggle' },
{ type: 'viewport', isDesktop: true },
).focusRequest,
).toBeNull();
expect(
navMenuReducer(
{ ...mobile, focusRequest: 'menuToggle' },
{ type: 'viewport', isDesktop: false },
).focusRequest,
).toBe('menuToggle');
});
it('viewport to the same width changes nothing and returns the same object', () => {
expect(
navMenuReducer(mobile, { type: 'viewport', isDesktop: false }),
).toBe(mobile);
expect(
navMenuReducer(desktopOpen, { type: 'viewport', isDesktop: true }),
).toBe(desktopOpen);
});
it('toggleMenu opens with the group expanded in the section, collapsed outside it', () => {
expect(
navMenuReducer(mobile, { type: 'toggleMenu', inSection: true }),
).toEqual(mobileGroup);
expect(
navMenuReducer(mobile, { type: 'toggleMenu', inSection: false }),
).toEqual(mobileOpen);
expect(
navMenuReducer(mobileGroup, {
type: 'toggleMenu',
inSection: true,
}),
).toEqual(mobile);
});
it('toggleMenu on desktop is ignored', () => {
expect(
navMenuReducer(desktop, { type: 'toggleMenu', inSection: true }),
).toBe(desktop);
});
it('toggleGroup flips the group while the menu is open', () => {
expect(navMenuReducer(mobileOpen, { type: 'toggleGroup' })).toEqual(
mobileGroup,
);
expect(navMenuReducer(mobileGroup, { type: 'toggleGroup' })).toEqual(
mobileOpen,
);
});
it('toggleGroup while the menu is closed is ignored', () => {
expect(navMenuReducer(mobile, { type: 'toggleGroup' })).toBe(mobile);
});
it('toggleSubmenu flips the submenu on desktop', () => {
expect(navMenuReducer(desktop, { type: 'toggleSubmenu' })).toEqual(
desktopOpen,
);
expect(navMenuReducer(desktopOpen, { type: 'toggleSubmenu' })).toEqual(
desktop,
);
});
it('toggleSubmenu on mobile is ignored', () => {
expect(navMenuReducer(mobile, { type: 'toggleSubmenu' })).toBe(mobile);
});
it('escape closes the mobile menu and asks for focus on the hamburger when focus is inside', () => {
expect(
navMenuReducer(mobileGroup, { type: 'escape', focusInside: true }),
).toEqual({ ...mobile, focusRequest: 'menuToggle' });
expect(
navMenuReducer(mobileGroup, { type: 'escape', focusInside: false }),
).toEqual(mobile);
});
it('escape closes the submenu and asks for focus on its toggle when focus is inside', () => {
expect(
navMenuReducer(desktopOpen, { type: 'escape', focusInside: true }),
).toEqual({ ...desktop, focusRequest: 'submenuToggle' });
expect(
navMenuReducer(desktopOpen, { type: 'escape', focusInside: false }),
).toEqual(desktop);
});
it('escape with nothing open is ignored', () => {
expect(
navMenuReducer(desktop, { type: 'escape', focusInside: true }),
).toBe(desktop);
expect(
navMenuReducer(mobile, { type: 'escape', focusInside: true }),
).toBe(mobile);
});
it('outside and focusLeave close the submenu without a focus request', () => {
expect(navMenuReducer(desktopOpen, { type: 'outside' })).toEqual(
desktop,
);
expect(navMenuReducer(desktopOpen, { type: 'focusLeave' })).toEqual(
desktop,
);
});
it('outside and focusLeave with the submenu closed are ignored', () => {
expect(navMenuReducer(desktop, { type: 'outside' })).toBe(desktop);
expect(navMenuReducer(desktop, { type: 'focusLeave' })).toBe(desktop);
expect(navMenuReducer(mobileGroup, { type: 'outside' })).toBe(
mobileGroup,
);
});
it('linkChosen and routeChanged close everything', () => {
for (const type of ['linkChosen', 'routeChanged'] as const) {
expect(navMenuReducer(mobileGroup, { type })).toEqual(mobile);
expect(navMenuReducer(desktopOpen, { type })).toEqual(desktop);
expect(navMenuReducer(desktop, { type })).toBe(desktop);
}
});
it('focusHandled clears the request, or is ignored when there is none', () => {
const asked: NavMenuState = {
...desktop,
focusRequest: 'submenuToggle',
};
expect(navMenuReducer(asked, { type: 'focusHandled' })).toEqual(
desktop,
);
expect(navMenuReducer(desktop, { type: 'focusHandled' })).toBe(desktop);
});
it('ignores an unknown event instead of opening anything', () => {
const unknown = { type: 'explode' } as unknown as NavMenuEvent;
expect(navMenuReducer(desktop, unknown)).toBe(desktop);
expect(navMenuReducer(mobileOpen, unknown)).toBe(mobileOpen);
});
});
+140
View File
@@ -0,0 +1,140 @@
// The open/closed state of the navigation menus (FR-ST-10): the desktop
// submenu below "Soorten fotoshoots" and, below lg, the full-screen menu
// with its expandable group. One reducer, so the hamburger, the submenu,
// the group and the route listener cannot disagree.
// Where the focus must go after a state change; cleared by `focusHandled`
export type FocusRequest = 'menuToggle' | 'submenuToggle' | null;
// Invariants (checked by the property tests):
// I1 submenuOpen implies isDesktop
// I2 menuOpen implies !isDesktop
// I3 groupOpen implies menuOpen
// I4 focusRequest 'menuToggle' implies !isDesktop, 'submenuToggle' implies
// isDesktop
export interface NavMenuState {
// Viewport is at or above lg
isDesktop: boolean;
// The full-screen mobile menu
menuOpen: boolean;
// The "Soorten fotoshoots" sub-list inside the mobile menu
groupOpen: boolean;
// The desktop dropdown panel
submenuOpen: boolean;
focusRequest: FocusRequest;
}
export type NavMenuEvent =
| { type: 'viewport'; isDesktop: boolean }
| { type: 'toggleMenu'; inSection: boolean }
| { type: 'toggleGroup' }
| { type: 'toggleSubmenu' }
| { type: 'escape'; focusInside: boolean }
| { type: 'outside' }
| { type: 'focusLeave' }
| { type: 'linkChosen' }
| { type: 'routeChanged' }
| { type: 'focusHandled' };
// Everything closed; the width is unknown until the first `viewport` event
export const initialNavMenuState: NavMenuState = {
isDesktop: false,
menuOpen: false,
groupOpen: false,
submenuOpen: false,
focusRequest: null,
};
// A focus request that cannot be met at this width is dropped (I4)
function fittingRequest(request: FocusRequest, isDesktop: boolean) {
if (request === 'menuToggle' && isDesktop) return null;
if (request === 'submenuToggle' && !isDesktop) return null;
return request;
}
// The transition table of the navigation menus. An event that does not apply
// returns the same state object, so useReducer skips the re-render. Nothing
// is ever opened by a fallback (SECURITY-15).
export function navMenuReducer(
state: NavMenuState,
event: NavMenuEvent,
): NavMenuState {
switch (event.type) {
case 'viewport': {
const { isDesktop } = event;
const next: NavMenuState = {
isDesktop,
menuOpen: isDesktop ? false : state.menuOpen,
groupOpen: isDesktop ? false : state.groupOpen,
submenuOpen: isDesktop ? state.submenuOpen : false,
focusRequest: fittingRequest(state.focusRequest, isDesktop),
};
return sameState(state, next) ? state : next;
}
case 'toggleMenu':
if (state.isDesktop) return state;
return state.menuOpen
? { ...state, menuOpen: false, groupOpen: false }
: { ...state, menuOpen: true, groupOpen: event.inSection };
case 'toggleGroup':
if (!state.menuOpen) return state;
return { ...state, groupOpen: !state.groupOpen };
case 'toggleSubmenu':
if (!state.isDesktop) return state;
return { ...state, submenuOpen: !state.submenuOpen };
case 'escape':
if (state.menuOpen) {
return {
...state,
menuOpen: false,
groupOpen: false,
focusRequest: event.focusInside ? 'menuToggle' : null,
};
}
if (state.submenuOpen) {
return {
...state,
submenuOpen: false,
focusRequest: event.focusInside ? 'submenuToggle' : null,
};
}
return state;
case 'outside':
case 'focusLeave':
if (!state.submenuOpen) return state;
return { ...state, submenuOpen: false };
case 'linkChosen':
case 'routeChanged': {
const closed: NavMenuState = {
...state,
menuOpen: false,
groupOpen: false,
submenuOpen: false,
focusRequest: null,
};
return sameState(state, closed) ? state : closed;
}
case 'focusHandled':
if (state.focusRequest === null) return state;
return { ...state, focusRequest: null };
default:
// A new event type without a case is a type error here (never);
// at run time an unknown event changes nothing
return ignore(state, event);
}
}
function sameState(a: NavMenuState, b: NavMenuState) {
return (
a.isDesktop === b.isDesktop &&
a.menuOpen === b.menuOpen &&
a.groupOpen === b.groupOpen &&
a.submenuOpen === b.submenuOpen &&
a.focusRequest === b.focusRequest
);
}
function ignore(state: NavMenuState, event: never): NavMenuState {
void event;
return state;
}
+38
View File
@@ -0,0 +1,38 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import shootTypes from '@/content/shootTypes';
import { uniqueShootTypes } from '@/test/arbitraries';
import { readMoreLabel } from './readMoreLabel';
describe('readMoreLabel', () => {
it('names each of the five real shoots', () => {
expect(shootTypes.map(readMoreLabel)).toEqual([
'Lees meer over de newbornshoot',
'Lees meer over de zwangerschapsshoot',
'Lees meer over de gezinsshoot',
'Lees meer over de loveshoot',
'Lees meer over de portretshoot',
]);
expect(new Set(shootTypes.map(readMoreLabel)).size).toBe(5);
});
it('starts with the fixed words and is unique for unique shoot labels (invariant)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
const unique = shoots.filter(
(shoot, index) =>
shoots.findIndex(
(other) =>
other.shootLabel.toLowerCase() ===
shoot.shootLabel.toLowerCase(),
) === index,
);
const labels = unique.map(readMoreLabel);
for (const label of labels) {
expect(label.startsWith('Lees meer over de ')).toBe(true);
}
expect(new Set(labels).size).toBe(labels.length);
}),
);
});
});
+7
View File
@@ -0,0 +1,7 @@
import type { ShootType } from '../content/types.ts';
// The text of the link from the overview to a shoot page (FR-ST-09). It
// differs per shoot, so no aria-label is needed to tell the links apart.
export function readMoreLabel(shoot: ShootType): string {
return `Lees meer over de ${shoot.shootLabel.toLowerCase()}`;
}
+75
View File
@@ -0,0 +1,75 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import shootTypes from '../content/shootTypes';
import { uniqueShootTypes } from '../test/arbitraries';
import { shootNavItems } from './shootNavItems';
import { SHOOT_TYPES_PATH, shootIdFromPath, shootPagePath } from './shootPages';
describe('shootNavItems', () => {
it('gives one item per shoot (invariant)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
expect(shootNavItems(shoots)).toHaveLength(shoots.length);
}),
);
});
it('keeps the order and uses the name as label (invariant)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
const items = shootNavItems(shoots);
expect(items.map((item) => item.label)).toEqual(
shoots.map((shoot) => shoot.name),
);
}),
);
});
it('links to the page of the same shoot (round trip)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
const items = shootNavItems(shoots);
items.forEach((item, index) => {
expect(shootIdFromPath(item.to)).toBe(shoots[index].id);
});
}),
);
});
it('links to a page below the overview (invariant)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
shootNavItems(shoots).forEach((item, index) => {
expect(item.to).toBe(shootPagePath(shoots[index].id));
expect(item.to.startsWith(`${SHOOT_TYPES_PATH}/`)).toBe(
true,
);
});
}),
);
});
it('has no other fields than to and label (invariant)', () => {
fc.assert(
fc.property(uniqueShootTypes, (shoots) => {
for (const item of shootNavItems(shoots)) {
expect(Object.keys(item).sort()).toEqual(['label', 'to']);
}
}),
);
});
it('gives the five names of the real shoot types in order', () => {
expect(shootNavItems(shootTypes).map((item) => item.label)).toEqual([
'Newborn',
'Zwangerschap',
'Gezin',
'Loveshoot',
'Portretten',
]);
});
it('gives an empty list for no shoots', () => {
expect(shootNavItems([])).toEqual([]);
});
});
+12
View File
@@ -0,0 +1,12 @@
import type { ShootType } from '../content/types.ts';
import type { NavItem } from '../navigation.ts';
import { shootPagePath } from './shootPages.ts';
// The submenu items of the shoot types, one per shoot in the given order:
// the label is the shoot name, the target its page (FR-ST-10, BR-NAV-10)
export function shootNavItems(shoots: readonly ShootType[]): NavItem[] {
return shoots.map((shoot) => ({
to: shootPagePath(shoot.id),
label: shoot.name,
}));
}
+95
View File
@@ -0,0 +1,95 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import shootPageShared from '@/content/shootPageShared';
import newbornPage from '@/content/shootPages/newborn';
import loveshootPage from '@/content/shootPages/loveshoot';
import packages from '@/content/packages';
import shootTypes from '@/content/shootTypes';
import siteContent from '@/content/siteContent';
import { shootPageViewArb } from '@/test/arbitraries';
import { shootPageBands } from './shootPageBands';
import { shootPageView } from './shootPageView';
import { storyLayout } from './storyLayout';
const sources = {
shootTypes,
packages,
shared: shootPageShared,
site: siteContent,
portfolioShoots: [],
};
describe('shootPageBands', () => {
it('gives the newborn page nine bands', () => {
const view = shootPageView('newborn', newbornPage, sources)!;
const bands = shootPageBands(view);
expect(bands).toHaveLength(9);
expect(bands.map((band) => band.id)).toEqual([
...view.stories.map((story) => `story-${story.id}`),
'process',
'photos',
'faq',
'offer',
'closing',
]);
expect(bands.map((band) => band.position)).toEqual([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(bands[0].tone).toBe('paper');
expect(bands[1].tone).toBe('alt');
});
it('leaves out the photos for loveshoot', () => {
const view = shootPageView('loveshoot', loveshootPage, sources)!;
const bands = shootPageBands(view);
expect(bands).toHaveLength(8);
expect(bands.map((band) => band.id)).not.toContain('photos');
});
it('leaves out the FAQ of a view without questions', () => {
const view = shootPageView(
'newborn',
{ ...newbornPage, faq: { ...newbornPage.faq, items: [] } },
sources,
)!;
const ids = shootPageBands(view).map((band) => band.id);
expect(ids).not.toContain('faq');
expect(ids).toContain('photos');
});
it('keeps the order, the alternation and the story tones for any view (invariant)', () => {
fc.assert(
fc.property(shootPageViewArb, (view) => {
const bands = shootPageBands(view);
expect(bands).toHaveLength(
view.stories.length +
1 +
(view.photos ? 1 : 0) +
(view.faq ? 1 : 0) +
2,
);
bands.forEach((band, index) => {
expect(band.position).toBe(index);
expect(band.tone).toBe(index % 2 === 0 ? 'paper' : 'alt');
});
const tail = bands.slice(view.stories.length).map((b) => b.id);
expect(tail).toEqual([
'process',
...(view.photos ? ['photos'] : []),
...(view.faq ? ['faq'] : []),
'offer',
'closing',
]);
expect(
bands.slice(0, view.stories.length).map((b) => b.id),
).toEqual(view.stories.map((story) => `story-${story.id}`));
const layout = storyLayout(view.stories);
layout.forEach((item, index) => {
expect(bands[index].tone).toBe(item.tone);
});
// Story ids are unique in the generated content
expect(new Set(bands.map((b) => b.id)).size).toBe(bands.length);
}),
);
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { ShootPageView } from './shootPageView.ts';
export interface SectionBand {
id: `story-${string}` | 'process' | 'photos' | 'faq' | 'offer' | 'closing';
// The band colour: paper at even positions, alt at odd ones
tone: 'paper' | 'alt';
// 0 for the first story; the intro above it is not a band
position: number;
}
// The bands of a shoot page in page order (BR-SP-70): the stories, the
// timeline, the photos and the FAQ when the view has them, the offer and
// the closing block. Tones alternate, so two bands never touch in the same
// colour; the intro above is always paper.
export function shootPageBands(view: ShootPageView): SectionBand[] {
const ids: SectionBand['id'][] = [
...view.stories.map((story) => `story-${story.id}` as const),
'process',
...(view.photos ? (['photos'] as const) : []),
...(view.faq ? (['faq'] as const) : []),
'offer',
'closing',
];
return ids.map((id, position) => ({
id,
tone: position % 2 === 0 ? 'paper' : 'alt',
position,
}));
}
+119
View File
@@ -0,0 +1,119 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import newbornPage from '@/content/shootPages/newborn';
import loveshootPage from '@/content/shootPages/loveshoot';
import type { StoryBlock } from '@/content/types';
import { imageWithOrientation, storyBlock } from '@/test/arbitraries';
import { LANDSCAPE_RATIO, storyLayout } from './storyLayout';
const story = (width?: number, height?: number): StoryBlock => ({
id: 's',
eyebrow: 'e',
title: 't',
paragraphs: [['p']],
...(width === undefined || height === undefined
? {}
: { image: { src: '/a.jpg', alt: 'a', width, height } }),
});
describe('storyLayout', () => {
it('lays out the four real newborn stories', () => {
const layout = storyLayout(newbornPage.stories);
expect(layout.map((item) => item.media)).toEqual([
{ aspectRatio: '4 / 5', mediaSize: 'medium' },
{ aspectRatio: '3 / 2', mediaSize: 'half' },
{ aspectRatio: '4 / 5', mediaSize: 'medium' },
{ aspectRatio: '4 / 5', mediaSize: 'medium' },
]);
expect(layout.map((item) => item.tone)).toEqual([
'paper',
'alt',
'paper',
'alt',
]);
expect(layout.map((item) => item.reverse)).toEqual([
false,
true,
false,
true,
]);
expect(layout.map((item) => item.priority)).toEqual([
true,
false,
false,
false,
]);
expect(layout[0].spacing).toBe('flushTop');
expect(layout[1].spacing).toBe('default');
});
it('gives text-only stories no media and no priority', () => {
const layout = storyLayout(loveshootPage.stories);
expect(layout[0].media).toBeDefined();
for (const item of layout.slice(1)) {
expect(item).not.toHaveProperty('media');
expect(item.priority).toBe(false);
}
expect(storyLayout([story()])[0].priority).toBe(false);
});
it('switches to landscape at exactly 1.2', () => {
expect(LANDSCAPE_RATIO).toBe(1.2);
expect(storyLayout([story(120, 100)])[0].media?.aspectRatio).toBe(
'3 / 2',
);
expect(storyLayout([story(119, 100)])[0].media?.aspectRatio).toBe(
'4 / 5',
);
});
it('gives nothing for no stories', () => {
expect(storyLayout([])).toEqual([]);
});
it('alternates, and decides ratio and width by the photo (invariant)', () => {
fc.assert(
fc.property(
fc.array(
fc.tuple(
storyBlock,
fc.option(imageWithOrientation, { nil: undefined }),
),
{ maxLength: 8 },
),
(pairs) => {
const stories = pairs.map(([block, image]) => ({
...block,
image,
}));
const layout = storyLayout(stories);
expect(layout).toHaveLength(stories.length);
layout.forEach((item, index) => {
const { image } = stories[index];
expect(item.tone).toBe(
index % 2 === 0 ? 'paper' : 'alt',
);
expect(item.reverse).toBe(index % 2 === 1);
expect(item.priority).toBe(
index === 0 && image !== undefined,
);
if (image === undefined) {
expect(item.media).toBeUndefined();
return;
}
const landscape =
image.width >= LANDSCAPE_RATIO * image.height;
expect(item.media).toEqual(
landscape
? { aspectRatio: '3 / 2', mediaSize: 'half' }
: {
aspectRatio: '4 / 5',
mediaSize: 'medium',
},
);
});
},
),
);
});
});
+44
View File
@@ -0,0 +1,44 @@
import type { StoryBlock } from '../content/types.ts';
// A photo is landscape when it is at least this much wider than it is high
export const LANDSCAPE_RATIO = 1.2;
export interface StoryLayout {
// Band colour; the same rule as shootPageBands gives the story bands
tone: 'paper' | 'alt';
// flushTop: no space above the first block, below the page head
spacing: 'flushTop' | 'default';
// Photo in the right-hand column from `lg`
reverse: boolean;
// Only the first story's photo may load with priority
priority: boolean;
// Absent for a story without a photo
media?: {
aspectRatio: '3 / 2' | '4 / 5';
mediaSize: 'half' | 'medium';
};
}
// How each story block is laid out (FR-ST-03): tone and side from the
// index, the photo's shape and column width from its proportions.
export function storyLayout(stories: readonly StoryBlock[]): StoryLayout[] {
return stories.map((story, index) => {
const { image } = story;
const landscape =
image !== undefined &&
image.width >= LANDSCAPE_RATIO * image.height;
return {
tone: index % 2 === 0 ? 'paper' : 'alt',
spacing: index === 0 ? 'flushTop' : 'default',
reverse: index % 2 === 1,
priority: index === 0 && image !== undefined,
...(image === undefined
? {}
: {
media: landscape
? { aspectRatio: '3 / 2', mediaSize: 'half' }
: { aspectRatio: '4 / 5', mediaSize: 'medium' },
}),
};
});
}
+226
View File
@@ -0,0 +1,226 @@
import { act, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shootTypes from '@/content/shootTypes';
import { shootPagePath } from '@/lib/shootPages';
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
import { mockViewport } from '@/test/navViewport';
import { renderApp } from '@/test/renderApp';
// The real route tree with the real navigation: current state (D4), closing
// on a route change and the mobile menu (FR-ST-10)
// The homepage's review carousel (Zag) needs an IntersectionObserver and
// Element.scrollTo, which jsdom lacks (as in app.test.tsx)
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
Element.prototype.scrollTo = () => {};
});
afterEach(() => {
vi.unstubAllGlobals();
FakeIntersectionObserver.reset();
// @ts-expect-error -- jsdom has no Element.scrollTo of its own
delete Element.prototype.scrollTo;
});
const PARENT = 'Soorten fotoshoots';
const TOGGLE = 'Submenu Soorten fotoshoots';
const header = () => screen.getByRole('banner');
const panel = () => document.getElementById('submenu-soorten-fotoshoots')!;
const footerNav = () => screen.getByRole('navigation', { name: 'Footermenu' });
const toggle = () => screen.getByRole('button', { name: TOGGLE });
const hamburger = () => screen.getByTestId('nav-menu-toggle');
// By text: the name of a link in a closed (hidden) panel is empty
const panelLinks = () => within(panel()).getAllByRole('link', { hidden: true });
const panelLink = (text: string) =>
panelLinks().find((link) => link.textContent === text)!;
const parentLink = () => within(header()).getByRole('link', { name: PARENT });
const footerLink = () =>
within(footerNav()).getByRole('link', { name: PARENT });
async function renderDesktop(path: string) {
mockViewport(1280);
const rendered = await renderApp(path);
// The shell is there once the lazy route has loaded
await screen.findByRole('main');
return { ...rendered, user: userEvent.setup() };
}
async function renderMobile(path: string) {
const viewport = mockViewport(375);
const rendered = await renderApp(path);
await screen.findByRole('main');
return { ...rendered, viewport, user: userEvent.setup() };
}
describe('current page in the navigation (D4)', () => {
it.each(shootTypes)(
'marks $name in the panel, the section on the parent and nothing in the footer',
async (shoot) => {
await renderDesktop(shootPagePath(shoot.id));
for (const link of panelLinks()) {
if (link.textContent === shoot.name) {
expect(link).toHaveAttribute('aria-current', 'page');
} else {
expect(link).not.toHaveAttribute('aria-current');
}
}
expect(parentLink()).not.toHaveAttribute('aria-current');
expect(parentLink()).toHaveAttribute('data-section-current');
expect(footerLink()).not.toHaveAttribute('aria-current');
},
);
it('marks the parent and the footer on the overview, and no panel link', async () => {
await renderDesktop('/soorten-fotoshoots');
expect(parentLink()).toHaveAttribute('aria-current', 'page');
expect(parentLink()).toHaveAttribute('data-section-current');
expect(footerLink()).toHaveAttribute('aria-current', 'page');
for (const link of panelLinks()) {
expect(link).not.toHaveAttribute('aria-current');
}
});
it('marks no panel link and no section on another page', async () => {
await renderDesktop('/portfolio');
for (const link of panelLinks()) {
expect(link).not.toHaveAttribute('aria-current');
}
expect(parentLink()).not.toHaveAttribute('data-section-current');
expect(parentLink()).not.toHaveAttribute('aria-current');
});
it('treats a trailing slash like the plain path (BR-NAV-04)', async () => {
await renderDesktop('/soorten-fotoshoots/newborn/');
expect(panelLink('Newborn')).toHaveAttribute('aria-current', 'page');
expect(parentLink()).toHaveAttribute('data-section-current');
expect(parentLink()).not.toHaveAttribute('aria-current');
expect(footerLink()).not.toHaveAttribute('aria-current');
});
it('shows the page on a case variant, underlines the section but marks no link (router case rule)', async () => {
await renderDesktop('/soorten-fotoshoots/Newborn');
// The router matches case-insensitively and renders the page, but
// its exact aria-current compares case-sensitively (Step 2). The
// only mark left is the breadcrumb's own current item (BR-SP-01).
const current = document.querySelectorAll('[aria-current="page"]');
expect(current).toHaveLength(1);
expect(current[0]).not.toHaveAttribute('href');
expect(current[0].closest('nav')).toHaveAccessibleName('Kruimelpad');
expect(parentLink()).toHaveAttribute('data-section-current');
});
it('keeps the panel in step with the shoot types (single source)', async () => {
await renderDesktop('/');
expect(panelLinks().map((link) => link.textContent)).toEqual(
shootTypes.map((shoot) => shoot.name),
);
expect(panelLinks().map((link) => link.getAttribute('href'))).toEqual(
shootTypes.map((shoot) => shootPagePath(shoot.id)),
);
});
});
describe('desktop submenu and the router', () => {
it('closes when the route changes', async () => {
const { router, user } = await renderDesktop('/');
await user.click(toggle());
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
await act(() => router.navigate({ to: '/portfolio' }));
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
});
it('closes on a link choice, opens the page and focuses main (BR-NAV-26)', async () => {
const { user } = await renderDesktop('/');
await user.click(toggle());
await user.click(
within(panel()).getByRole('link', { name: 'Zwangerschap' }),
);
await waitFor(() =>
expect(
screen.getByRole('heading', { level: 1 }),
).toBeInTheDocument(),
);
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
await waitFor(() =>
expect(document.getElementById('main')).toHaveFocus(),
);
expect(panelLink('Zwangerschap')).toHaveAttribute(
'aria-current',
'page',
);
});
it('does not close on the first render', async () => {
const { user } = await renderDesktop('/');
await user.click(toggle());
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
});
});
describe('mobile menu and the router', () => {
it('closes when the route changes without a menu click', async () => {
const { router, user } = await renderMobile('/contact');
await user.click(hamburger());
expect(hamburger()).toHaveAttribute('aria-expanded', 'true');
await act(() => router.navigate({ to: '/portfolio' }));
expect(hamburger()).toHaveAttribute('aria-expanded', 'false');
});
it('closes on the browser back button (BR-NAV-32)', async () => {
const { router, user } = await renderMobile('/contact');
await act(() => router.navigate({ to: '/portfolio' }));
await user.click(hamburger());
expect(hamburger()).toHaveAttribute('aria-expanded', 'true');
await act(async () => router.history.back());
await waitFor(() =>
expect(hamburger()).toHaveAttribute('aria-expanded', 'false'),
);
expect(router.state.location.pathname).toBe('/contact');
});
it('expands the group when it opens on a shoot page', async () => {
const { user } = await renderMobile('/soorten-fotoshoots/loveshoot');
await user.click(hamburger());
const group = within(document.getElementById('mobile-nav')!).getByRole(
'button',
{ name: TOGGLE },
);
expect(group).toHaveAttribute('aria-expanded', 'true');
expect(
within(document.getElementById('mobile-nav')!).getByRole('link', {
name: 'Loveshoot',
}),
).toHaveAttribute('aria-current', 'page');
});
});
describe('crossing the lg breakpoint', () => {
it('closes the mobile menu that no longer exists', async () => {
const { viewport, user } = await renderMobile('/contact');
await user.click(hamburger());
expect(hamburger()).toHaveAttribute('aria-expanded', 'true');
viewport.resize(1280);
viewport.resize(375);
await waitFor(() =>
expect(hamburger()).toHaveAttribute('aria-expanded', 'false'),
);
expect(document.body.style.overflow).toBe('');
});
it('closes the desktop submenu that no longer exists', async () => {
const rendered = await renderMobile('/contact');
rendered.viewport.resize(1280);
await waitFor(() => expect(toggle()).toBeInTheDocument());
await rendered.user.click(toggle());
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
rendered.viewport.resize(375);
rendered.viewport.resize(1280);
await waitFor(() =>
expect(toggle()).toHaveAttribute('aria-expanded', 'false'),
);
});
});
+72 -1
View File
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest';
import { footerNav, mainNav } from './navigation';
import shootTypes from './content/shootTypes';
import {
SHOOT_TYPE_IDS,
SHOOT_TYPES_PATH,
shootIdFromPath,
shootPagePath,
} from './lib/shootPages';
import { footerNav, hasChildren, mainNav } from './navigation';
import sitePages from './sitePages';
describe('menu', () => {
it('hoofdmenu heeft de vaste volgorde', () => {
@@ -35,3 +43,66 @@ describe('menu', () => {
}
});
});
describe('submenu Soorten fotoshoots', () => {
const parent = mainNav.find((item) => item.to === SHOOT_TYPES_PATH);
it('heeft de vijf shoots als kinderen, in de volgorde van de shoottypes', () => {
expect(parent?.children).toEqual(
shootTypes.map((shoot) => ({
to: shootPagePath(shoot.id),
label: shoot.name,
})),
);
expect(parent?.children?.map((child) => child.label)).toEqual([
'Newborn',
'Zwangerschap',
'Gezin',
'Loveshoot',
'Portretten',
]);
});
it('heeft een menu-item voor elk shoottype en niets extra', () => {
expect(
parent?.children
?.map((child) => shootIdFromPath(child.to))
.toSorted(),
).toEqual([...SHOOT_TYPE_IDS].toSorted());
});
it('geeft alleen het hoofditem kinderen, op één niveau', () => {
const others = [
...mainNav.filter((item) => item !== parent),
...footerNav,
];
for (const item of others) {
expect(item.children).toBeUndefined();
}
for (const child of parent?.children ?? []) {
expect(child.children).toBeUndefined();
}
});
it('hasChildren is alleen waar voor het hoofditem', () => {
expect(mainNav.filter(hasChildren)).toEqual([parent]);
expect(hasChildren({ to: '/', label: 'Home', children: [] })).toBe(
false,
);
expect(hasChildren({ to: '/', label: 'Home' })).toBe(false);
});
it('heeft geen dubbele routes in het hoofditem en zijn kinderen', () => {
const paths = [
parent?.to,
...(parent?.children ?? []).map((c) => c.to),
];
expect(new Set(paths).size).toBe(paths.length);
});
it('linkt alleen naar geregistreerde, geïndexeerde pagina’s', () => {
for (const child of parent?.children ?? []) {
expect(sitePages[child.to]?.indexed).toBe(true);
}
});
});
+17 -1
View File
@@ -1,3 +1,5 @@
import shootTypes from './content/shootTypes.ts';
import { shootNavItems } from './lib/shootNavItems.ts';
import type { FileRoutesByTo } from './routeTree.gen.ts';
// Menu's verwijzen naar routes, en routes zijn code: het CMS kan geen
@@ -7,6 +9,15 @@ export type RoutePath = keyof FileRoutesByTo;
export interface NavItem {
to: RoutePath;
label: string;
// Sub-pages, one level only; an empty array counts as none
children?: readonly NavItem[];
}
// Whether the item has a submenu (a non-empty list of children)
export function hasChildren(
item: NavItem,
): item is NavItem & { children: readonly NavItem[] } {
return (item.children?.length ?? 0) > 0;
}
// Hoofdmenu: desktopnavigatie en mobiel menu
@@ -14,7 +25,12 @@ export const mainNav: readonly NavItem[] = [
{ to: '/', label: 'Home' },
{ to: '/over-mij', label: 'Over mij' },
{ to: '/portfolio', label: 'Portfolio' },
{ to: '/soorten-fotoshoots', label: 'Soorten fotoshoots' },
{
to: '/soorten-fotoshoots',
label: 'Soorten fotoshoots',
// One source: a new shoot type shows up in the menu by itself (D5)
children: shootNavItems(shootTypes),
},
{ to: '/contact', label: 'Contact' },
];
+345
View File
@@ -0,0 +1,345 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { screen, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import packages from './content/packages';
import shootPageShared from './content/shootPageShared';
import shootTypes from './content/shootTypes';
import { formatPrice } from './lib/formatPrice';
import { readMoreLabel } from './lib/readMoreLabel';
import { shootPagePath } from './lib/shootPages';
import sitePages from './sitePages';
import { FakeIntersectionObserver } from './test/fakeIntersectionObserver';
import { axeResults } from './test/axe';
import { cssRulesFor } from './test/cssRules';
import { expectShell, renderApp } from './test/renderApp';
// The pages use IntersectionObserver (fade-in, deferred photos) and the
// homepage-style shell may use Element.scrollTo, which jsdom lacks
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
Element.prototype.scrollTo = () => {};
});
afterEach(() => {
vi.unstubAllGlobals();
FakeIntersectionObserver.reset();
// @ts-expect-error -- jsdom has no Element.scrollTo of its own
delete Element.prototype.scrollTo;
});
const withPackage = ['newborn', 'zwangerschap', 'gezin'];
const mosaicTiles: Record<string, number> = { newborn: 3 };
const renderShoot = async (id: string) => {
const path = shootPagePath(id as (typeof shootTypes)[number]['id']);
const result = await renderApp(path);
await screen.findByRole('heading', { level: 1 });
return result;
};
const isAlt = (element: Element) =>
cssRulesFor(element).join().includes('var(--slp-colors-paper-alt)');
describe('shoot pages', () => {
it.each(shootTypes.map((shoot) => shoot.id))(
'%s has a clean heading outline and the sections its data says',
async (id) => {
const { container } = await renderShoot(id);
expectShell();
const main = screen.getByRole('main');
expect(
within(main).getAllByRole('heading', { level: 1 }),
).toHaveLength(1);
// Six process steps; FAQ questions are summaries, not headings
expect(
within(main).getAllByRole('heading', { level: 3 }),
).toHaveLength(6);
const levels = [
...main.querySelectorAll('h1, h2, h3, h4, h5, h6'),
].map((heading) => Number(heading.tagName[1]));
levels.slice(1).forEach((level, index) => {
expect(level).toBeLessThanOrEqual(levels[index] + 1);
});
// Every section is named by an existing heading
for (const section of main.querySelectorAll('section')) {
const target = section.getAttribute('aria-labelledby')!;
expect(main.querySelector(`#${target}`)).not.toBeNull();
}
expect(main.querySelector('#zo-werkt-het')).not.toBeNull();
expect(main.querySelector('#vragen')).not.toBeNull();
expect(main.querySelector('#pakket')).not.toBeNull();
const tiles = mosaicTiles[id] ?? 0;
if (tiles > 0) {
expect(main.querySelector('#impressie')).not.toBeNull();
expect(
within(screen.getByTestId('photo-mosaic')).getAllByRole(
'listitem',
),
).toHaveLength(tiles);
} else {
expect(main.querySelector('#impressie')).toBeNull();
expect(screen.queryByTestId('photo-mosaic')).toBeNull();
}
expect(await axeResults(container)).toHaveNoViolations();
},
);
it.each(shootTypes)(
'$id has a breadcrumb that ends at the page itself, and nothing else in main is current',
async ({ id, name }) => {
await renderShoot(id);
const crumb = screen.getByRole('navigation', {
name: 'Kruimelpad',
});
expect(crumb).toBe(screen.getByTestId('shoot-breadcrumb'));
const items = within(crumb).getAllByRole('listitem');
// Three items and two separators
expect(
items.filter((item) => !item.hasAttribute('aria-hidden')),
).toHaveLength(3);
expect(
within(crumb).getByRole('link', { name: 'Home' }),
).toHaveAttribute('href', '/');
expect(
within(crumb).getByRole('link', { name: 'Soorten fotoshoots' }),
).toHaveAttribute('href', '/soorten-fotoshoots');
const current = within(crumb).getByText(name);
expect(current).toHaveAttribute('aria-current', 'page');
// The header and footer are checked on the whole page below
const marked = screen
.getByRole('main')
.querySelectorAll('[aria-current]');
expect([...marked]).toEqual([current]);
},
);
// Whole-page facet (BR-SP-03, application design D4). The header submenu
// child and the breadcrumb's last item both name the page itself, so the
// rule is "at most one in main and at most one in each menu", not one
// overall. The two menus (the header's, and the mobile menu which is a
// sibling of the header and only one of them shows at a time) each mark
// the shoot's own link; the parent link and the footer link are not
// current.
it.each(shootTypes)(
'$id marks only the page itself as current: once in main (breadcrumb) and once in each menu (submenu link)',
async ({ id, name }) => {
await renderShoot(id);
const header = screen.getByRole('banner');
const main = screen.getByRole('main');
const footer = screen.getByRole('contentinfo');
const crumbCurrent = within(
screen.getByTestId('shoot-breadcrumb'),
).getByText(name);
const inMain = [...main.querySelectorAll('[aria-current]')];
expect(inMain).toEqual([crumbCurrent]);
const inHeader = [...header.querySelectorAll('[aria-current]')];
expect(inHeader).toHaveLength(1);
expect(inHeader[0]).toHaveAttribute('aria-current', 'page');
expect(inHeader[0]).toHaveAttribute('href', shootPagePath(id));
// The parent stays unmarked for assistive technology
const parentLinks = [
...document.querySelectorAll(
'header a[href="/soorten-fotoshoots"], #mobile-nav a[href="/soorten-fotoshoots"]',
),
];
expect(parentLinks.length).toBeGreaterThan(0);
expect(
parentLinks.some((link) => link.hasAttribute('aria-current')),
).toBe(false);
expect(footer.querySelectorAll('[aria-current]')).toHaveLength(0);
const mobile = [
...document.querySelectorAll('#mobile-nav [aria-current]'),
];
expect(mobile).toHaveLength(1);
expect(mobile[0]).toHaveAttribute('aria-current', 'page');
expect(mobile[0]).toHaveAttribute('href', shootPagePath(id));
// Nothing outside breadcrumb, header menu and mobile menu
expect(
document.querySelectorAll('[aria-current="page"]'),
).toHaveLength(3);
},
);
it.each(shootTypes)(
'$id shows the right offer, with the deposit note and a closing band of another tone',
async ({ id }) => {
await renderShoot(id);
const offer = screen.getByTestId('package-block');
const note = shootPageShared.deposit.note.replace(
'{aanbetaling}',
formatPrice(shootPageShared.deposit.amount),
);
const noteElement = within(offer).getByText(
(_, element) =>
element?.textContent === note && element.tagName === 'P',
);
if (withPackage.includes(id)) {
const pkg = packages.find((item) => item.id === id)!;
expect(
within(offer).getByRole('link', {
name: 'Boek dit pakket',
}),
).toHaveAttribute('href', `/contact?pakket=${id}`);
expect(
within(offer).getByRole('link', {
name: shootPageShared.offer.askLabel,
}),
).toHaveAttribute('href', '/contact');
expect(
within(offer).getByText(
(_, element) =>
element?.tagName === 'P' &&
element.textContent === formatPrice(pkg.price),
),
).toBeInTheDocument();
} else {
expect(
within(offer).getByText('Prijs op aanvraag'),
).toBeInTheDocument();
expect(within(offer).queryByRole('list')).toBeNull();
const links = within(offer).getAllByRole('link');
expect(links).toHaveLength(1);
expect(links[0]).toHaveAttribute('href', '/contact');
}
// The note comes after the actions
const lastLink = within(offer).getAllByRole('link').at(-1)!;
expect(
lastLink.compareDocumentPosition(noteElement) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
const packageBand = screen
.getByRole('main')
.querySelector('#pakket')!;
const closingBand = screen.getByTestId('shoot-closing');
expect(isAlt(packageBand)).not.toBe(isAlt(closingBand));
},
);
it.each(shootTypes.map((shoot) => shoot.id))(
'%s loads only the first story photo with priority',
async (id) => {
await renderShoot(id);
const images = within(screen.getByRole('main')).getAllByRole('img');
const first = within(screen.getByTestId('shoot-page'))
.getAllByRole('img')
.at(0)!;
expect(images[0]).toBe(first);
expect(first).not.toHaveAttribute('loading', 'lazy');
expect(first).toHaveAttribute('fetchpriority', 'high');
for (const image of images.slice(1)) {
expect(image).not.toHaveAttribute('loading', 'eager');
expect(image).not.toHaveAttribute('fetchpriority');
}
},
);
});
describe('overview page', () => {
it('gives every shoot a "Lees meer" link to its page, first in its row, with a unique name', async () => {
await renderApp('/soorten-fotoshoots');
await screen.findByRole('heading', { level: 1 });
const names: string[] = [];
for (const shoot of shootTypes) {
const link = screen.getByRole('link', {
name: readMoreLabel(shoot),
});
expect(link).toHaveAttribute('href', shootPagePath(shoot.id));
const article = link.closest('article')!;
expect(article.id).toBe(shoot.id);
expect(within(article).getAllByRole('link')[0]).toBe(link);
names.push(link.textContent!);
}
expect(new Set(names).size).toBe(shootTypes.length);
});
it('keeps the anchors and the old links', async () => {
await renderApp('/soorten-fotoshoots');
await screen.findByRole('heading', { level: 1 });
for (const shoot of shootTypes) {
expect(
screen.getByRole('article', { name: shoot.name }),
).toHaveAttribute('id', shoot.id);
expect(
screen.getByTestId(`shoot-${shoot.id}-contact`),
).toBeInTheDocument();
}
});
it('links to each shoot page exactly once and to no other shoot path', async () => {
await renderApp('/soorten-fotoshoots');
await screen.findByRole('heading', { level: 1 });
const main = screen.getByRole('main');
const hrefs = within(main)
.getAllByRole('link')
.map((link) => link.getAttribute('href')!)
.filter((href) => href.startsWith('/soorten-fotoshoots/'));
expect([...hrefs].sort()).toEqual(
shootTypes.map((shoot) => shootPagePath(shoot.id)).sort(),
);
});
});
// The size of a JPEG, read from its start-of-frame marker (baseline,
// extended, progressive or lossless), without an image library
function jpegSize(bytes: Uint8Array) {
expect([bytes[0], bytes[1]]).toEqual([0xff, 0xd8]);
let offset = 2;
while (offset + 9 < bytes.length) {
expect(bytes[offset]).toBe(0xff);
const marker = bytes[offset + 1];
const length = (bytes[offset + 2] << 8) | bytes[offset + 3];
const isFrame =
marker >= 0xc0 &&
marker <= 0xcf &&
![0xc4, 0xc8, 0xcc].includes(marker);
if (isFrame) {
return {
height: (bytes[offset + 5] << 8) | bytes[offset + 6],
width: (bytes[offset + 7] << 8) | bytes[offset + 8],
};
}
offset += 2 + length;
}
throw new Error('no frame marker in the JPEG');
}
describe('preview images of the shoot pages', () => {
it.each(shootTypes.map((shoot) => shoot.id))(
'%s has a registered 1200 x 630 JPEG of at most 150 KB',
(id) => {
const og = sitePages[shootPagePath(id)].ogImage;
expect(og).toBeDefined();
expect(og!.path).toBe(`/og-${id}.jpg`);
expect(og!.width).toBe(1200);
expect(og!.height).toBe(630);
expect(og!.alt.trim()).not.toBe('');
const file = resolve(
import.meta.dirname,
'../public',
`og-${id}.jpg`,
);
const bytes = readFileSync(file);
expect(bytes.length).toBeLessThanOrEqual(150 * 1024);
expect(jpegSize(bytes)).toEqual({ width: 1200, height: 630 });
},
);
it('uses no preview image twice in the registry', () => {
const paths = Object.values(sitePages).flatMap((page) =>
page.ogImage ? [page.ogImage.path] : [],
);
expect(new Set(paths).size).toBe(paths.length);
});
});
+30
View File
@@ -68,6 +68,12 @@ const sitePages: Record<RoutePath, PageMeta> = {
description:
"Newbornshoot in Huizen en omgeving, bij jou thuis in het rustige ritme van je baby. Warme, spontane foto's van Andrea Slop Fotografie.",
indexed: true,
ogImage: {
path: '/og-newborn.jpg',
width: 1200,
height: 630,
alt: 'Babyvuistje tussen een gebreide deken en een geruite doek',
},
},
'/soorten-fotoshoots/zwangerschap': {
// DRAFT(CON-ST-03): awaiting Andrea's approval
@@ -76,6 +82,12 @@ const sitePages: Record<RoutePath, PageMeta> = {
description:
"Zwangerschapsshoot in Huizen en omgeving: leg deze bijzondere periode vast in spontane foto's. Ontdek de mogelijkheden van Andrea Slop Fotografie.",
indexed: true,
ogImage: {
path: '/og-zwangerschap.jpg',
width: 1200,
height: 630,
alt: 'Zwangere buik in een zwarte jurk, omarmd door twee handen',
},
},
'/soorten-fotoshoots/gezin': {
// DRAFT(CON-ST-03): awaiting Andrea's approval
@@ -84,6 +96,12 @@ const sitePages: Record<RoutePath, PageMeta> = {
description:
'Gezinsshoot in Huizen en omgeving: echte momenten die laten zien hoe jullie nu samen zijn. Ontdek de mogelijkheden van Andrea Slop Fotografie.',
indexed: true,
ogImage: {
path: '/og-gezin.jpg',
width: 1200,
height: 630,
alt: 'Jonge ouders kijken samen naar hun slapende pasgeboren baby',
},
},
'/soorten-fotoshoots/loveshoot': {
// DRAFT(CON-ST-03): awaiting Andrea's approval
@@ -92,6 +110,12 @@ const sitePages: Record<RoutePath, PageMeta> = {
description:
"Loveshoot in Huizen en omgeving: leg jullie liefde vast in spontane, kleurrijke foto's. Ontdek de mogelijkheden van Andrea Slop Fotografie.",
indexed: true,
ogImage: {
path: '/og-loveshoot.jpg',
width: 1200,
height: 630,
alt: 'Een stel ligt in de zon op een plaid in het gras, met de hoofden tegen elkaar',
},
},
'/soorten-fotoshoots/portret': {
// DRAFT(CON-ST-03): awaiting Andrea's approval
@@ -100,6 +124,12 @@ const sitePages: Record<RoutePath, PageMeta> = {
description:
"Portretshoot in Huizen en omgeving, in de natuur of zakelijk. Spontane portretfoto's van Andrea Slop Fotografie.",
indexed: true,
ogImage: {
path: '/og-portret.jpg',
width: 1200,
height: 630,
alt: 'Een vrouw met lang bruin haar in een witte blouse kijkt glimlachend omlaag, met bomen op de achtergrond',
},
},
'/contact': {
title: 'Contact – fotoshoot boeken in Huizen',
+72
View File
@@ -2,6 +2,7 @@ import fc from 'fast-check';
import type { ContactField, ContactValues } from '../contact/types';
import type { ContactFormEvent } from '../lib/contactFormReducer';
import type { LightboxEvent } from '../lib/lightboxReducer';
import { shootPageView, type ShootPageView } from '../lib/shootPageView';
import type { Point } from '../lib/swipeDirection';
import type {
ContentImage,
@@ -673,3 +674,74 @@ export const slugInput: fc.Arbitrary<unknown> = fc.oneof(
fc.object(),
),
);
// --- Shoot page UI (unit 2) ---
// A photo whose proportions sit around the landscape threshold of 1.2:
// exactly on it, just below and just above, and anywhere else
export const imageWithOrientation: fc.Arbitrary<ContentImage> = fc
.tuple(
contentImage,
fc.integer({ min: 20, max: 1500 }),
fc.constantFrom('exact', 'below', 'above', 'any'),
fc.integer({ min: 20, max: 4000 }),
)
.map(([base, step, kind, anyWidth]) => {
// A height divisible by 5, so that 1.2 x height is a whole number
const height = step * 5;
const edge = step * 6;
const width =
kind === 'exact'
? edge
: kind === 'below'
? edge - 1
: kind === 'above'
? edge + 1
: anyWidth;
return { ...base, width, height };
});
// Counts around the mosaic sizes, below zero included
export const mosaicCount = fc.integer({ min: -3, max: 12 });
// One step of a timeline with hostile strings
const hostileText = fc.oneof(
fc.string({ minLength: 1, maxLength: 30 }),
fc.constantFrom(
'</script>',
'<',
'>',
'&',
'x'.repeat(120),
' ',
' ',
'a<b>c&d',
),
);
// 1 to 8 timeline steps with unique ids
export const timelineSteps = fc.uniqueArray(
fc.record({ id: slug, title: hostileText, text: hostileText }),
{ selector: (step) => step.id, minLength: 1, maxLength: 8 },
);
// A shoot page view built the way the route builds it: stories 0 to 6, the
// photos present or not, the FAQ present or not, a package or none
export const shootPageViewArb: fc.Arbitrary<ShootPageView> = fc
.tuple(shootType, uniquePackages, shootPageShared, anySiteContent)
.chain(([shoot, packages, shared, site]) =>
shootPageContent(shoot.id, [
shoot.image,
...(shoot.detailImage ? [shoot.detailImage] : []),
]).map((page) => {
const view = shootPageView(shoot.id, page, {
shootTypes: [shoot],
packages,
shared,
site,
portfolioShoots: [shoot.id],
});
if (view === undefined) throw new Error('no view for a valid case');
return view;
}),
);
+115
View File
@@ -0,0 +1,115 @@
import fc from 'fast-check';
import {
initialNavMenuState,
navMenuReducer,
type NavMenuEvent,
type NavMenuState,
} from '../lib/navMenuState';
import { shootPagePath } from '../lib/shootPages';
import { knownRoutePath, shootTypeId } from './arbitraries';
// Generators of the navigation submenu unit (unit 3). Kept apart from
// arbitraries.ts, which other units edit as well.
// Any menu event with a random payload; viewport, toggles and escape are
// weighted up so sequences actually open and close things
export const navMenuEvent: fc.Arbitrary<NavMenuEvent> = fc.oneof(
{
weight: 4,
arbitrary: fc
.boolean()
.map((isDesktop) => ({ type: 'viewport' as const, isDesktop })),
},
{
weight: 4,
arbitrary: fc
.boolean()
.map((inSection) => ({ type: 'toggleMenu' as const, inSection })),
},
{ weight: 3, arbitrary: fc.constant({ type: 'toggleGroup' as const }) },
{ weight: 4, arbitrary: fc.constant({ type: 'toggleSubmenu' as const }) },
{
weight: 4,
arbitrary: fc
.boolean()
.map((focusInside) => ({ type: 'escape' as const, focusInside })),
},
{ weight: 2, arbitrary: fc.constant({ type: 'outside' as const }) },
{ weight: 2, arbitrary: fc.constant({ type: 'focusLeave' as const }) },
{ weight: 1, arbitrary: fc.constant({ type: 'linkChosen' as const }) },
{ weight: 1, arbitrary: fc.constant({ type: 'routeChanged' as const }) },
{ weight: 2, arbitrary: fc.constant({ type: 'focusHandled' as const }) },
);
// A sequence of up to 40 menu events
export const navMenuEvents: fc.Arbitrary<NavMenuEvent[]> = fc.array(
navMenuEvent,
{ maxLength: 40 },
);
// A state reached from the initial one by random events, so it satisfies the
// invariants by construction (I1-I4 are checked on it by the tests)
export const navMenuState: fc.Arbitrary<NavMenuState> = navMenuEvents.map(
(events) => events.reduce(navMenuReducer, initialNavMenuState),
);
// The same, restricted to a viewport: a state that has seen that width
export const navMenuStateOn = (
isDesktop: boolean,
): fc.Arbitrary<NavMenuState> =>
navMenuEvents.map((events) =>
[{ type: 'viewport', isDesktop } as const, ...events].reduce(
navMenuReducer,
initialNavMenuState,
),
);
// Strings that must never break a path comparison
const hostilePathname = fc.constantFrom(
'',
'/',
'//',
'///',
' ',
'/ soorten-fotoshoots',
'/soorten-fotoshoots%2F',
'/soorten-fotoshoots/%2e%2e/',
'/soorten-fotoshoots\newborn',
'/soorten-fotoshoots?x=1',
'/soorten-fotoshoots#top',
'\u0000',
'/İNDEX',
'a'.repeat(5000),
);
// Prefix look-alikes of the overview: not the overview, not a shoot page
const lookAlike = fc.constantFrom(
'/soorten-fotoshoots-extra',
'/soorten-fotoshootsX',
'/soorten-fotoshoot',
'/soorten-fotoshoots/newborns',
'/soorten-fotoshoots/newborn/extra',
'/x/soorten-fotoshoots',
);
// The ways a visitor or the router may spell a path
const spelling = (path: string) =>
fc.constantFrom(
path,
`${path}/`,
path.toUpperCase(),
`${path.toUpperCase()}/`,
);
// A pathname: known routes and shoot pages in several spellings (trailing
// slash, letter case), prefix look-alikes and hostile strings
export const pathname: fc.Arbitrary<string> = fc.oneof(
{ weight: 4, arbitrary: knownRoutePath.chain(spelling) },
{
weight: 4,
arbitrary: shootTypeId.chain((id) => spelling(shootPagePath(id))),
},
{ weight: 2, arbitrary: lookAlike },
{ weight: 2, arbitrary: hostilePathname },
{ weight: 1, arbitrary: fc.string() },
);
+74
View File
@@ -0,0 +1,74 @@
import { act } from '@testing-library/react';
import { afterEach, vi } from 'vitest';
// Makes window.matchMedia answer for a viewport of `width` px, so Chakra's
// breakpoint hooks (min-width queries) and prefers-reduced-motion behave as
// in a browser. jsdom has no layout and ignores @media rules, so the
// responsive display of the desktop list and the mobile menu is applied by a
// style element here (the browser check is Step 17). The stub is undone by
// vi.restoreAllMocks() in the global afterEach.
const styleId = 'nav-viewport-style';
afterEach(() => document.getElementById(styleId)?.remove());
export function mockViewport(width: number, { reducedMotion = false } = {}) {
type Listener = (event: { media: string; matches: boolean }) => void;
const listeners: { query: string; listener: Listener }[] = [];
let current = width;
const matches = (query: string) => {
if (query.includes('prefers-reduced-motion')) return reducedMotion;
const min = /min-width:\s*([\d.]+)(px|em|rem)/.exec(query);
if (!min) return false;
return current >= parseFloat(min[1]) * (min[2] === 'px' ? 1 : 16);
};
vi.spyOn(window, 'matchMedia').mockImplementation(
(query: string) =>
({
get matches() {
return matches(query);
},
media: query,
onchange: null,
addEventListener: (_type: string, listener: Listener) => {
listeners.push({ query, listener });
},
removeEventListener: (_type: string, listener: Listener) => {
const index = listeners.findIndex(
(entry) => entry.listener === listener,
);
if (index >= 0) listeners.splice(index, 1);
},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as unknown as MediaQueryList,
);
// At lg and up the desktop list shows and the mobile menu is gone
const applyLayout = () => {
document.getElementById(styleId)?.remove();
if (current < 992) return;
const style = document.createElement('style');
style.id = styleId;
style.textContent =
'nav[aria-label="Hoofdmenu"] > ul { display: flex !important; }' +
'#mobile-nav { display: none !important; }';
document.head.append(style);
};
applyLayout();
return {
// Resizes the "window" and tells every listener, like a browser does
resize(next: number) {
current = next;
applyLayout();
act(() => {
for (const { query, listener } of [...listeners]) {
listener({ media: query, matches: matches(query) });
}
});
},
};
}