Adds the shared gallery building blocks

A masonry photo grid that keeps the reading order (pure CSS, no measuring
in the browser), an accessible lightbox on Chakra's Dialog with wrap-around
browsing, keys, swipe and preloading, and a filter bar of toggle buttons.
They work on generic gallery items, so other pages can use them. The swipe
logic moves out of the hero into a shared hook; the hero behaves as before.
The rules behind them live in pure helpers with property-based tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-25 23:22:43 +01:00
co-authored by Claude Opus 5.5
parent e013f1436b
commit 18bf0311ef
38 changed files with 2392 additions and 43 deletions
@@ -0,0 +1,104 @@
import { screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import FilterBar from './FilterBar';
const options = [
{ id: 'alles', label: 'Alles' },
{ id: 'newborn', label: 'Newborn' },
{ id: 'gezin', label: 'Gezin' },
];
const LABEL = 'Filter op soort shoot';
describe('FilterBar', () => {
it('shows a named group of toggle buttons in order, with the chosen one pressed', async () => {
const { container } = await renderWithProviders(
<FilterBar
options={options}
value="newborn"
onChange={() => {}}
label={LABEL}
/>,
);
const group = screen.getByRole('group', { name: LABEL });
const buttons = within(group).getAllByRole('button');
expect(buttons.map((b) => b.textContent)).toEqual([
'Alles',
'Newborn',
'Gezin',
]);
expect(
screen.getByRole('button', { name: 'Newborn', pressed: true }),
).toBeInTheDocument();
expect(screen.getAllByRole('button', { pressed: false })).toHaveLength(
2,
);
expect(await axeResults(container)).toHaveNoViolations();
});
it('reports a new choice, but not a click on the chosen one', async () => {
const onChange = vi.fn();
await renderWithProviders(
<FilterBar
options={options}
value="alles"
onChange={onChange}
label={LABEL}
/>,
);
const user = userEvent.setup();
await user.click(screen.getByTestId('filter-alles'));
expect(onChange).not.toHaveBeenCalled();
await user.click(screen.getByTestId('filter-gezin'));
expect(onChange).toHaveBeenCalledWith('gezin');
// Focus stays on the button that was used
expect(screen.getByTestId('filter-gezin')).toHaveFocus();
});
it('can be used with the keyboard, one tab stop per button', async () => {
const onChange = vi.fn();
await renderWithProviders(
<FilterBar
options={options}
value="alles"
onChange={onChange}
label={LABEL}
/>,
);
const user = userEvent.setup();
await user.tab();
expect(screen.getByTestId('filter-alles')).toHaveFocus();
await user.tab();
expect(screen.getByTestId('filter-newborn')).toHaveFocus();
await user.keyboard('{Enter}');
expect(onChange).toHaveBeenCalledWith('newborn');
});
it('shows nothing with fewer than two options', async () => {
await renderWithProviders(
<FilterBar
options={[options[0]]}
value="alles"
onChange={() => {}}
label={LABEL}
/>,
);
expect(screen.queryByTestId('filter-bar')).not.toBeInTheDocument();
});
it('presses no button for an unknown value', async () => {
await renderWithProviders(
<FilterBar
options={options}
value="portret"
onChange={() => {}}
label={LABEL}
/>,
);
expect(screen.queryAllByRole('button', { pressed: true })).toHaveLength(
0,
);
});
});
@@ -0,0 +1,55 @@
import { chakra, useRecipe } from '@chakra-ui/react';
import type { FilterOption } from '@/content/types';
type FilterBarProps = {
options: readonly FilterOption[];
// The id of the chosen option
value: string;
onChange: (id: string) => void;
// Name of the group for assistive technology, e.g. "Filter op soort shoot"
label: string;
};
// A row of single-choice toggle buttons (portfolio filters): every button is
// its own tab stop and the chosen one is aria-pressed. With fewer than two
// options there is nothing to choose, so nothing is shown.
export default function FilterBar({
options,
value,
onChange,
label,
}: FilterBarProps) {
const filterControl = useRecipe({ key: 'filterControl' });
if (options.length < 2) return null;
return (
<chakra.div
role="group"
aria-label={label}
data-testid="filter-bar"
display="flex"
flexWrap="wrap"
justifyContent="center"
columnGap={{ base: 4, md: 6 }}
>
{options.map((option) => {
const pressed = option.id === value;
return (
<chakra.button
key={option.id}
type="button"
css={filterControl()}
aria-pressed={pressed}
data-testid={`filter-${option.id}`}
onClick={() => {
if (!pressed) onChange(option.id);
}}
>
{option.label}
</chakra.button>
);
})}
</chakra.div>
);
}
+7 -28
View File
@@ -1,8 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
import { useMediaQuery } from '@chakra-ui/react';
// Minimale horizontale afstand in px voordat een veeg als swipe telt
const SWIPE_THRESHOLD = 50;
import useSwipe from '@/hooks/useSwipe';
import { wrapIndex } from '@/lib/wrapIndex';
// Houdt de actieve slide bij en of autoplay mag lopen. Het doorschuiven zelf
// gebeurt via de animatie van de voortgangsbalk (zie Hero.tsx), zodat pauzeren
@@ -27,7 +26,6 @@ export default function useHeroSlider(count: number) {
ssr: false,
},
);
const touchStart = useRef<{ x: number; y: number } | null>(null);
useEffect(() => {
const onVisibilityChange = () => setHidden(document.hidden);
@@ -43,11 +41,13 @@ export default function useHeroSlider(count: number) {
const active = index < count ? index : 0;
const go = (to: number, visitor: boolean) => {
setIndex((to + count) % count);
setIndex(wrapIndex(to, count));
setAnnouncement(visitor ? 'slide' : null);
};
const next = () => go(active + 1, true);
const prev = () => go(active - 1, true);
// Swiping only makes sense with something to swipe to
const swipe = useSwipe({ onPrev: prev, onNext: next, enabled: count > 1 });
return {
active,
@@ -85,28 +85,7 @@ export default function useHeroSlider(count: number) {
setFocused(false);
}
},
onTouchStart: (event: React.TouchEvent<HTMLElement>) => {
const touch = event.touches[0];
touchStart.current = { x: touch.clientX, y: touch.clientY };
},
onTouchEnd: (event: React.TouchEvent<HTMLElement>) => {
const start = touchStart.current;
touchStart.current = null;
if (!start || count < 2) return;
const touch = event.changedTouches[0];
const dx = touch.clientX - start.x;
const dy = touch.clientY - start.y;
// Horizontaal genoeg, en niet bedoeld als verticaal scrollen
if (
Math.abs(dx) < SWIPE_THRESHOLD ||
Math.abs(dx) < Math.abs(dy)
)
return;
if (dx < 0) next();
else prev();
},
...swipe,
},
};
}
@@ -0,0 +1,220 @@
import { useState } from 'react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { GalleryItem } from '@/content/types';
import { axeResults } from '@/test/axe';
import { galleryItems } from '@/test/galleryFixtures';
import { renderWithProviders } from '@/test/renderWithProviders';
import Lightbox from './Lightbox';
// A parent that owns the index, like the portfolio page will
function Harness({
items = galleryItems,
start = 0,
onClose = () => {},
}: {
items?: GalleryItem[];
start?: number | null;
onClose?: () => void;
}) {
const [index, setIndex] = useState<number | null>(start);
return (
<Lightbox
items={items}
index={index}
onIndexChange={setIndex}
onClose={() => {
setIndex(null);
onClose();
}}
/>
);
}
async function openAt(start = 0, items?: GalleryItem[], onClose?: () => void) {
const result = await renderWithProviders(
<Harness start={start} items={items} onClose={onClose} />,
);
await screen.findByTestId('lightbox');
return result;
}
const counter = () => screen.getByTestId('lightbox-counter');
const image = () => screen.getByTestId('lightbox-image');
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('Lightbox', () => {
it('renders nothing while closed', async () => {
await renderWithProviders(<Harness start={null} />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('shows the chosen photo large in a named dialog, with caption and counter', async () => {
await openAt(0);
const dialog = screen.getByRole('dialog', {
name: 'Foto groot bekijken',
});
expect(dialog).toBeInTheDocument();
expect(image()).toHaveAttribute('src', galleryItems[0].full.src);
expect(screen.getByTestId('lightbox-caption')).toHaveTextContent(
'Newbornshoot',
);
expect(counter()).toHaveTextContent(`1 / ${galleryItems.length}`);
});
it('moves focus to the close button when it opens', async () => {
// The dialog's focus trap only focuses elements with a layout box;
// jsdom has no layout, so give elements the box a browser would
vi.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue([
{ width: 52, height: 52 },
] as unknown as DOMRectList);
await openAt(0);
await waitFor(() =>
expect(screen.getByTestId('lightbox-close')).toHaveFocus(),
);
});
it('browses with the buttons and wraps around', async () => {
await openAt(0);
const user = userEvent.setup();
await user.click(screen.getByTestId('lightbox-prev'));
expect(counter()).toHaveTextContent(
`${galleryItems.length} / ${galleryItems.length}`,
);
await user.click(screen.getByTestId('lightbox-next'));
expect(counter()).toHaveTextContent(`1 / ${galleryItems.length}`);
});
it('browses with the arrow keys, Home and End, and announces where it is', async () => {
await openAt(1);
const user = userEvent.setup();
await user.keyboard('{ArrowRight}');
expect(counter()).toHaveTextContent(`3 / ${galleryItems.length}`);
expect(screen.getByTestId('lightbox-announcement')).toHaveTextContent(
`Foto 3 van ${galleryItems.length}, Newbornshoot`,
);
await user.keyboard('{End}');
expect(counter()).toHaveTextContent(
`${galleryItems.length} / ${galleryItems.length}`,
);
await user.keyboard('{Home}');
expect(counter()).toHaveTextContent(`1 / ${galleryItems.length}`);
await user.keyboard('{ArrowLeft}');
expect(screen.getByTestId('lightbox-announcement')).toHaveTextContent(
`Foto ${galleryItems.length} van ${galleryItems.length}`,
);
});
it('browses with a swipe', async () => {
await openAt(0);
const figure = image().closest('figure') as HTMLElement;
fireEvent.touchStart(figure, {
touches: [{ clientX: 300, clientY: 100 }],
});
fireEvent.touchEnd(figure, {
changedTouches: [{ clientX: 150, clientY: 100 }],
});
expect(counter()).toHaveTextContent(`2 / ${galleryItems.length}`);
});
it('closes with the close button', async () => {
const onClose = vi.fn();
await openAt(0, undefined, onClose);
const user = userEvent.setup();
await user.click(screen.getByTestId('lightbox-close'));
expect(onClose).toHaveBeenCalledTimes(1);
// Closing: Chakra removes it after the fade-out, which needs real
// animation events that jsdom does not have
expect(screen.getByTestId('lightbox')).toHaveAttribute(
'data-state',
'closed',
);
});
it('closes with Escape', async () => {
const onClose = vi.fn();
await openAt(0, undefined, onClose);
await userEvent.setup().keyboard('{Escape}');
expect(onClose).toHaveBeenCalledTimes(1);
});
it('closes on the dark area, but not on the photo itself', async () => {
const onClose = vi.fn();
await openAt(0, undefined, onClose);
fireEvent.click(image());
expect(onClose).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('lightbox'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('shows no browsing controls for a single photo', async () => {
await openAt(0, [galleryItems[0]]);
expect(screen.queryByTestId('lightbox-prev')).not.toBeInTheDocument();
expect(screen.queryByTestId('lightbox-next')).not.toBeInTheDocument();
expect(
screen.queryByTestId('lightbox-counter'),
).not.toBeInTheDocument();
const user = userEvent.setup();
await user.keyboard('{ArrowRight}');
expect(
screen.getByTestId('lightbox-announcement'),
).toBeEmptyDOMElement();
});
it('shows the grid photo while the large one loads, then swaps', async () => {
await openAt(0);
const thumb = screen.getByTestId('lightbox-thumb');
expect(thumb).toHaveAttribute('src', galleryItems[0].thumb.src);
expect(thumb).toHaveAttribute('alt', galleryItems[0].thumb.alt);
expect(image()).toHaveAttribute('aria-hidden', 'true');
fireEvent.load(image());
expect(image()).toHaveAttribute('alt', galleryItems[0].thumb.alt);
expect(thumb).toHaveAttribute('aria-hidden', 'true');
expect(screen.getAllByRole('img')).toHaveLength(1);
});
it('keeps the grid photo and says so when the large one fails', async () => {
await openAt(1);
fireEvent.error(image());
expect(screen.queryByTestId('lightbox-image')).not.toBeInTheDocument();
expect(screen.getByTestId('lightbox-thumb')).toHaveAttribute(
'alt',
galleryItems[1].thumb.alt,
);
expect(screen.getByTestId('lightbox-caption')).toHaveTextContent(
'Deze foto kon niet groot geladen worden',
);
// The next photo starts fresh
const user = userEvent.setup();
await user.click(screen.getByTestId('lightbox-next'));
expect(screen.getByTestId('lightbox-image')).toBeInTheDocument();
});
it('loads two photos ahead on each side', async () => {
const requested: string[] = [];
vi.stubGlobal(
'Image',
class {
set src(value: string) {
requested.push(value);
}
},
);
await openAt(0);
const n = galleryItems.length;
const expected = [1, n - 1, 2, n - 2].map(
(i) => galleryItems[i].full.src,
);
expect(new Set(requested)).toEqual(new Set(expected));
});
it('has no accessibility violations while open', async () => {
await openAt(0);
expect(await axeResults(document.body)).toHaveNoViolations();
});
});
+366
View File
@@ -0,0 +1,366 @@
import {
useEffect,
useRef,
useState,
type KeyboardEvent,
type MouseEvent,
} from 'react';
import { Box, chakra, Dialog, Portal, Text, useRecipe } from '@chakra-ui/react';
import { Icon } from '@iconify/react/offline';
import closeOutlined from '@iconify-icons/ant-design/close-outlined';
import leftOutlined from '@iconify-icons/ant-design/left-outlined';
import rightOutlined from '@iconify-icons/ant-design/right-outlined';
import type { GalleryItem } from '@/content/types';
import useSwipe from '@/hooks/useSwipe';
import { neighbourIndexes } from '@/lib/neighbourIndexes';
import { wrapIndex } from '@/lib/wrapIndex';
type LightboxProps = {
items: readonly GalleryItem[];
// The photo on screen, or null when closed
index: number | null;
onIndexChange: (index: number) => void;
onClose: () => void;
// Name of the dialog for assistive technology
label?: string;
// Where focus goes on close: the grid tile of the photo shown last
finalFocusEl?: () => HTMLElement | null;
};
// Large photos loaded ahead on each side of the one on screen (FD Q8 = B)
const PRELOAD_RADIUS = 2;
type LoadState = 'loading' | 'loaded' | 'failed';
// Shows one photo of a list large, in a modal dialog (design .lightbox).
// Chakra's Dialog traps focus, closes on Escape, makes the page behind it
// inert and stops it scrolling; this component adds browsing (buttons,
// arrow keys, Home/End, swipe), the counter, the caption and loading.
// Default export, so the page can load it lazily on first use.
export default function Lightbox({
items,
index,
onIndexChange,
onClose,
label = 'Foto groot bekijken',
finalFocusEl,
}: LightboxProps) {
const count = items.length;
const open = index !== null && count > 0;
const current = open ? wrapIndex(index, count) : 0;
const item = items[current];
const browsable = count > 1;
const closeButton = useRef<HTMLButtonElement>(null);
// Said after the visitor browses; not on opening (the dialog name and
// the focused close button are announced then)
const [announcement, setAnnouncement] = useState('');
// Clear the announcement when the dialog closes, so reopening is quiet.
// Adjusted during render, as React advises for state that follows a prop.
const [wasOpen, setWasOpen] = useState(open);
if (wasOpen !== open) {
setWasOpen(open);
if (!open) setAnnouncement('');
}
// Load the photos around this one, so browsing shows them at once
useEffect(() => {
if (!open) return;
for (const i of neighbourIndexes(current, count, PRELOAD_RADIUS)) {
const preload = new Image();
preload.src = items[i].full.src;
}
}, [open, current, count, items]);
const show = (to: number) => {
const next = wrapIndex(to, count);
onIndexChange(next);
const caption = items[next].caption;
setAnnouncement(
`Foto ${next + 1} van ${count}` + (caption ? `, ${caption}` : ''),
);
};
const swipe = useSwipe({
onPrev: () => show(current - 1),
onNext: () => show(current + 1),
enabled: browsable,
});
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!browsable) return;
const target: Record<string, number> = {
ArrowRight: current + 1,
ArrowLeft: current - 1,
Home: 0,
End: count - 1,
};
if (event.key in target) {
event.preventDefault();
show(target[event.key]);
}
};
// A click on the dark area around the photo closes; on the photo itself
// it does nothing (FD Q3)
const closeOnBackground = (event: MouseEvent<HTMLElement>) => {
if (event.target === event.currentTarget) onClose();
};
return (
<Dialog.Root
unstyled
open={open}
onOpenChange={(details) => {
if (!details.open) onClose();
}}
initialFocusEl={() => closeButton.current}
finalFocusEl={finalFocusEl}
lazyMount
unmountOnExit
>
<Portal>
<Dialog.Backdrop
position="fixed"
inset={0}
zIndex="modal"
bg="rgba(20, 19, 18, 0.94)"
_open={{
animationName: 'fade-in',
animationDuration: 'swap',
}}
_closed={{
animationName: 'fade-out',
animationDuration: 'swap',
}}
_motionReduce={{ animation: 'none' }}
/>
<Dialog.Positioner position="fixed" inset={0} zIndex="modal">
{item && (
<Dialog.Content
data-testid="lightbox"
position="absolute"
inset={0}
display="flex"
alignItems="center"
justifyContent="center"
px={{ base: 3, md: 24 }}
pt={{ base: 16, md: 12 }}
pb={{ base: 24, md: 16 }}
color="white"
outline="none"
onKeyDown={handleKeyDown}
onClick={closeOnBackground}
_open={{
animationName: 'fade-in',
animationDuration: 'swap',
}}
_closed={{
animationName: 'fade-out',
animationDuration: 'swap',
}}
_motionReduce={{ animation: 'none' }}
>
<Dialog.Title srOnly>{label}</Dialog.Title>
{/* Keyed per photo: a new photo starts loading
from scratch */}
<Photo
key={`${current}-${item.full.src}`}
item={item}
swipe={swipe}
onBackground={closeOnBackground}
/>
<Dialog.CloseTrigger asChild>
<ControlButton
ref={closeButton}
aria-label="Sluiten"
data-testid="lightbox-close"
position="absolute"
top={{ base: 2, md: 4 }}
right={{ base: 2, md: 4 }}
>
<Icon icon={closeOutlined} aria-hidden />
</ControlButton>
</Dialog.CloseTrigger>
{browsable && (
// Phones: one bar at the bottom, within reach of
// the thumb and never over the photo (FD Q2).
// Larger screens: the bar dissolves and each
// control takes its place from the design.
<Box
display={{ base: 'flex', md: 'contents' }}
position="absolute"
insetX={0}
bottom={0}
px={2}
pb="max(0.5rem, env(safe-area-inset-bottom))"
alignItems="center"
justifyContent="space-between"
>
<ControlButton
aria-label="Vorige foto"
data-testid="lightbox-prev"
onClick={() => show(current - 1)}
position={{ md: 'absolute' }}
left={{ md: 4 }}
top={{ md: '50%' }}
transform={{ md: 'translateY(-50%)' }}
>
<Icon icon={leftOutlined} aria-hidden />
</ControlButton>
<Text
data-testid="lightbox-counter"
fontSize="sm"
letterSpacing="0.06em"
color="whiteAlpha.800"
fontVariantNumeric="tabular-nums"
position={{ md: 'absolute' }}
bottom={{ md: 5 }}
left={{ md: '50%' }}
transform={{ md: 'translateX(-50%)' }}
>
{current + 1} / {count}
</Text>
<ControlButton
aria-label="Volgende foto"
data-testid="lightbox-next"
onClick={() => show(current + 1)}
position={{ md: 'absolute' }}
right={{ md: 4 }}
top={{ md: '50%' }}
transform={{ md: 'translateY(-50%)' }}
>
<Icon
icon={rightOutlined}
aria-hidden
/>
</ControlButton>
</Box>
)}
<chakra.p
srOnly
aria-live="polite"
data-testid="lightbox-announcement"
>
{announcement}
</chakra.p>
</Dialog.Content>
)}
</Dialog.Positioner>
</Portal>
</Dialog.Root>
);
}
type PhotoProps = {
item: GalleryItem;
swipe: ReturnType<typeof useSwipe>;
onBackground: (event: MouseEvent<HTMLElement>) => void;
};
// The photo with its caption. Until the large version has loaded, the grid
// version (already in the browser cache) stands in at the same size; if
// the large one fails, the grid version stays and a short note says so.
function Photo({ item, swipe, onBackground }: PhotoProps) {
const [load, setLoad] = useState<LoadState>('loading');
const onLoad = () => setLoad('loaded');
const onError = () => setLoad('failed');
const caption =
load === 'failed'
? 'Deze foto kon niet groot geladen worden'
: item.caption;
return (
<chakra.figure
m={0}
display="flex"
flexDirection="column"
alignItems="center"
maxW="min(1100px, 100%)"
maxH="100%"
onClick={onBackground}
animationName="fade-in"
animationDuration="swap"
_motionReduce={{ animation: 'none' }}
{...swipe}
>
<Box position="relative" maxH="100%" minH={0}>
<chakra.img
src={item.thumb.src}
alt={load === 'loaded' ? '' : item.thumb.alt}
aria-hidden={load === 'loaded' ? true : undefined}
width={item.full.width}
height={item.full.height}
data-testid="lightbox-thumb"
display="block"
maxW="100%"
maxH={{ base: 'calc(100dvh - 10rem)', md: '80svh' }}
w="auto"
h="auto"
objectFit="contain"
/>
{load !== 'failed' && (
<chakra.img
src={item.full.src}
alt={load === 'loaded' ? item.thumb.alt : ''}
aria-hidden={load === 'loaded' ? undefined : true}
width={item.full.width}
height={item.full.height}
data-testid="lightbox-image"
decoding="async"
onLoad={onLoad}
onError={onError}
position="absolute"
inset={0}
w="100%"
h="100%"
objectFit="contain"
opacity={load === 'loaded' ? 1 : 0}
transitionProperty="opacity"
transitionDuration="swap"
_motionReduce={{ transition: 'none' }}
/>
)}
</Box>
{caption && (
<chakra.figcaption
data-testid="lightbox-caption"
aria-live={load === 'failed' ? 'polite' : undefined}
mt={4}
fontSize="sm"
letterSpacing="0.06em"
textAlign="center"
color="whiteAlpha.800"
>
{caption}
</chakra.figcaption>
)}
</chakra.figure>
);
}
type ControlButtonProps = React.ComponentProps<typeof chakra.button>;
// Buttons over the dark backdrop: the iconControl look (white, half
// transparent, full on hover/focus, white focus ring) with a hairline
// square around it as in the design (.lightbox__btn)
function ControlButton(props: ControlButtonProps) {
const iconControl = useRecipe({ key: 'iconControl' });
return (
<chakra.button
type="button"
css={iconControl()}
w="52px"
h="52px"
borderWidth="1px"
borderColor="whiteAlpha.400"
fontSize="1.1rem"
{...props}
/>
);
}
@@ -0,0 +1,109 @@
import { fireEvent, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { masonryRowSpan } from '@/lib/masonryRowSpan';
import { axeResults } from '@/test/axe';
import { galleryItems } from '@/test/galleryFixtures';
import { renderWithProviders } from '@/test/renderWithProviders';
import PortfolioGrid from './PortfolioGrid';
describe('PortfolioGrid', () => {
it('lists the photos in order as links to their large version', async () => {
const { container } = await renderWithProviders(
<PortfolioGrid items={galleryItems} onOpen={() => {}} />,
);
const items = within(screen.getByTestId('portfolio-grid')).getAllByRole(
'listitem',
);
expect(items).toHaveLength(galleryItems.length);
galleryItems.forEach((item, index) => {
const tile = screen.getByTestId(`portfolio-tile-${index + 1}`);
expect(items[index]).toContainElement(tile);
expect(tile).toHaveAttribute('href', item.full.src);
expect(tile).toHaveAccessibleName(
`${item.thumb.alt} (groot bekijken)`,
);
expect(items[index]).toHaveAttribute(
'data-row-span',
String(masonryRowSpan(item.thumb)),
);
});
expect(await axeResults(container)).toHaveNoViolations();
});
it('loads the first photos straight away and defers the rest', async () => {
await renderWithProviders(
<PortfolioGrid
items={galleryItems}
eagerCount={3}
onOpen={() => {}}
/>,
);
const images = screen.getAllByRole('img');
images.forEach((image, index) => {
if (index < 3) {
expect(image).toHaveAttribute('fetchpriority', 'high');
expect(image).toHaveAttribute(
'src',
galleryItems[index].thumb.src,
);
} else {
expect(image).not.toHaveAttribute('fetchpriority');
expect(image).toHaveAttribute('loading', 'lazy');
}
expect(image).toHaveAttribute(
'width',
String(galleryItems[index].thumb.width),
);
});
});
it('asks to open the lightbox on a plain click or Enter', async () => {
const onOpen = vi.fn();
await renderWithProviders(
<PortfolioGrid items={galleryItems} onOpen={onOpen} />,
);
const user = userEvent.setup();
await user.click(screen.getByTestId('portfolio-tile-2'));
expect(onOpen).toHaveBeenLastCalledWith(1);
screen.getByTestId('portfolio-tile-4').focus();
await user.keyboard('{Enter}');
expect(onOpen).toHaveBeenLastCalledWith(3);
});
it('leaves a click with a modifier key to the browser', async () => {
const onOpen = vi.fn();
await renderWithProviders(
<PortfolioGrid items={galleryItems} onOpen={onOpen} />,
);
const tile = screen.getByTestId('portfolio-tile-1');
const ctrlClick = fireEvent.click(tile, { ctrlKey: true });
const metaClick = fireEvent.click(tile, { metaKey: true });
expect(onOpen).not.toHaveBeenCalled();
// Not prevented: the browser follows the link
expect(ctrlClick).toBe(true);
expect(metaClick).toBe(true);
expect(fireEvent.click(tile)).toBe(false);
});
it('reports the first hover or focus once', async () => {
const onIntent = vi.fn();
await renderWithProviders(
<PortfolioGrid
items={galleryItems}
onOpen={() => {}}
onIntent={onIntent}
/>,
);
fireEvent.pointerEnter(screen.getByTestId('portfolio-tile-1'));
fireEvent.focus(screen.getByTestId('portfolio-tile-2'));
expect(onIntent).toHaveBeenCalledTimes(1);
});
it('renders an empty list without photos', async () => {
await renderWithProviders(
<PortfolioGrid items={[]} onOpen={() => {}} />,
);
expect(screen.getByTestId('portfolio-grid')).toBeEmptyDOMElement();
});
});
@@ -0,0 +1,164 @@
import { useRef, type MouseEvent } from 'react';
import { Box, chakra, Image, VisuallyHidden } from '@chakra-ui/react';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import Reveal from '@/components/Reveal/Reveal';
import type { GalleryItem } from '@/content/types';
import {
GAP_ROWS,
masonryRowSpan,
ROWS_PER_COLUMN_WIDTH,
} from '@/lib/masonryRowSpan';
type PortfolioGridProps = {
items: readonly GalleryItem[];
// How many photos at the start load straight away (the first row on
// desktop); the rest wait until the page has loaded and they are near
eagerCount?: number;
onOpen: (index: number) => void;
// First hover or focus on a photo: a good moment to load the lightbox
onIntent?: () => void;
'data-testid'?: string;
};
// Masonry grid of photos in reading order (design .portfolio-grid): every
// photo is shown whole in its own shape, row by row, so keyboard and screen
// reader follow the order Andrea chose. Pure CSS: the implicit rows are a
// fraction of the column width (container units) and each photo spans as
// many as its aspect ratio needs, so nothing shifts while photos load.
// Every photo is a link to its large version; a plain click asks the page
// to open the lightbox instead.
export default function PortfolioGrid({
items,
eagerCount = 3,
onOpen,
onIntent,
'data-testid': testId = 'portfolio-grid',
}: PortfolioGridProps) {
const intentReported = useRef(false);
const reportIntent = () => {
if (intentReported.current) return;
intentReported.current = true;
onIntent?.();
};
const handleClick = (
event: MouseEvent<HTMLAnchorElement>,
index: number,
) => {
// Ctrl/Cmd/Shift/Alt or middle click: let the browser open the link
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
event.preventDefault();
onOpen(index);
};
return (
<Box containerType="inline-size">
<Reveal>
<chakra.ul
data-testid={testId}
listStyleType="none"
display="grid"
gridTemplateColumns={{
base: '1fr',
md: 'repeat(2, 1fr)',
lg: 'repeat(3, 1fr)',
}}
columnGap="gridGap"
// One implicit row = column width / ROWS_PER_COLUMN_WIDTH
gridAutoRows="var(--row)"
css={{
'--cols': '1',
md: { '--cols': '2' },
lg: { '--cols': '3' },
'--row': `calc((100cqi - (var(--cols) - 1) * {spacing.gridGap}) / var(--cols) / ${ROWS_PER_COLUMN_WIDTH})`,
}}
>
{items.map((item, index) => {
const span = masonryRowSpan(item.thumb);
const imageStyle = {
display: 'block',
w: '100%',
h: '100%',
objectFit: 'cover',
transitionProperty: 'transform',
transitionDuration: 'interaction',
transitionTimingFunction: 'smooth',
_groupHover: { transform: 'scale(1.05)' },
_groupFocusVisible: { transform: 'scale(1.05)' },
_motionReduce: { transform: 'none !important' },
} as const;
return (
<chakra.li
key={item.id}
gridRowEnd={`span ${span}`}
data-row-span={span}
>
<chakra.a
href={item.full.src}
data-testid={`portfolio-tile-${index + 1}`}
className="group"
display="block"
position="relative"
overflow="hidden"
bg="paper.deep"
cursor="zoom-in"
// The photo; the last rows are the gap
h={`calc(100% - ${GAP_ROWS} * var(--row))`}
// Keeps the focus ring above neighbours
_focusVisible={{ zIndex: 1 }}
// Darkening overlay (design ::after)
_after={{
content: '""',
position: 'absolute',
inset: 0,
bg: 'ink',
opacity: 0,
transitionProperty: 'opacity',
transitionDuration: 'interaction',
pointerEvents: 'none',
}}
_hover={{ _after: { opacity: 0.25 } }}
onClick={(event) =>
handleClick(event, index)
}
onPointerEnter={reportIntent}
onFocus={reportIntent}
>
{index < eagerCount ? (
<Image
src={item.thumb.src}
alt={item.thumb.alt}
htmlWidth={item.thumb.width}
htmlHeight={item.thumb.height}
fetchPriority="high"
decoding="async"
{...imageStyle}
/>
) : (
<DeferredImage
image={item.thumb}
{...imageStyle}
/>
)}
{/* The alt names the photo; this says what
the link does */}{' '}
<VisuallyHidden>
(groot bekijken)
</VisuallyHidden>
</chakra.a>
</chakra.li>
);
})}
</chakra.ul>
</Reveal>
</Box>
);
}
+24
View File
@@ -48,6 +48,30 @@ export interface ContentImage {
height: number;
}
// An image file with its intrinsic size, without its own description (the
// larger size of a photo whose ContentImage already carries the alt text)
export interface ImageSource {
src: string;
width: number;
height: number;
}
// One photo for the shared gallery blocks (PortfolioGrid, Lightbox): a grid
// size with the description, a large size for the lightbox, and an optional
// visible caption. The blocks know nothing about where the photos come from.
export interface GalleryItem {
id: string;
thumb: ContentImage;
full: ImageSource;
caption?: string;
}
// One choice in a FilterBar
export interface FilterOption {
id: string;
label: string;
}
// A priced shoot offer. id is a stable slug: it goes into ?pakket= and is
// the shoot value the contact form sends.
export interface PricingPackage {
+68
View File
@@ -0,0 +1,68 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import useSwipe from './useSwipe';
function Target({
onPrev,
onNext,
enabled,
}: {
onPrev: () => void;
onNext: () => void;
enabled?: boolean;
}) {
const handlers = useSwipe({ onPrev, onNext, enabled });
return <div data-testid="swipe-target" {...handlers} />;
}
function swipe(target: HTMLElement, from: number, to: number, dy = 0) {
fireEvent.touchStart(target, {
touches: [{ clientX: from, clientY: 100 }],
});
fireEvent.touchEnd(target, {
changedTouches: [{ clientX: to, clientY: 100 + dy }],
});
}
function setup(enabled?: boolean) {
const onPrev = vi.fn();
const onNext = vi.fn();
render(<Target onPrev={onPrev} onNext={onNext} enabled={enabled} />);
return { onPrev, onNext, target: screen.getByTestId('swipe-target') };
}
describe('useSwipe', () => {
it('calls onNext for a swipe to the left and onPrev for one to the right', () => {
const { onPrev, onNext, target } = setup();
swipe(target, 300, 200);
expect(onNext).toHaveBeenCalledTimes(1);
swipe(target, 200, 300);
expect(onPrev).toHaveBeenCalledTimes(1);
});
it('ignores short and vertical touches', () => {
const { onPrev, onNext, target } = setup();
swipe(target, 300, 270);
swipe(target, 300, 200, 150);
expect(onNext).not.toHaveBeenCalled();
expect(onPrev).not.toHaveBeenCalled();
});
it('ignores a touch end without a start, and clears the start after each end', () => {
const { onNext, target } = setup();
fireEvent.touchEnd(target, {
changedTouches: [{ clientX: 0, clientY: 100 }],
});
swipe(target, 300, 200);
fireEvent.touchEnd(target, {
changedTouches: [{ clientX: 0, clientY: 100 }],
});
expect(onNext).toHaveBeenCalledTimes(1);
});
it('does nothing while disabled', () => {
const { onNext, target } = setup(false);
swipe(target, 300, 200);
expect(onNext).not.toHaveBeenCalled();
});
});
+40
View File
@@ -0,0 +1,40 @@
import { useRef, type TouchEvent } from 'react';
import { type Point, swipeDirection } from '@/lib/swipeDirection';
type SwipeOptions = {
onPrev: () => void;
onNext: () => void;
// Off: touches are ignored (e.g. a slider with a single slide)
enabled?: boolean;
};
// Horizontal swipes on touch screens: a swipe to the left calls onNext, to
// the right onPrev. Shared by the hero slider and the lightbox, so both
// react to the same distance and ignore vertical scrolling the same way.
export default function useSwipe({
onPrev,
onNext,
enabled = true,
}: SwipeOptions) {
const start = useRef<Point | null>(null);
return {
onTouchStart: (event: TouchEvent<HTMLElement>) => {
const touch = event.touches[0];
start.current = { x: touch.clientX, y: touch.clientY };
},
onTouchEnd: (event: TouchEvent<HTMLElement>) => {
const from = start.current;
start.current = null;
if (!from || !enabled) return;
const touch = event.changedTouches[0];
const direction = swipeDirection(from, {
x: touch.clientX,
y: touch.clientY,
});
if (direction === 'next') onNext();
if (direction === 'prev') onPrev();
},
};
}
+130
View File
@@ -0,0 +1,130 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { lightboxEvent } from '../test/arbitraries';
import {
closedLightbox,
type LightboxEvent,
lightboxReducer,
type LightboxState,
} from './lightboxReducer';
const open = (index: number, count: number): LightboxState => ({
open: true,
index,
count,
});
describe('lightboxReducer', () => {
it('opens at the chosen photo', () => {
expect(
lightboxReducer(closedLightbox, {
type: 'open',
index: 2,
count: 5,
}),
).toEqual(open(2, 5));
});
it('stays closed when there are no photos', () => {
expect(
lightboxReducer(closedLightbox, {
type: 'open',
index: 0,
count: 0,
}),
).toEqual(closedLightbox);
});
it('wraps around when browsing past either end', () => {
expect(lightboxReducer(open(4, 5), { type: 'next' })).toEqual(
open(0, 5),
);
expect(lightboxReducer(open(0, 5), { type: 'prev' })).toEqual(
open(4, 5),
);
});
it('jumps to the first and the last photo', () => {
expect(lightboxReducer(open(3, 5), { type: 'first' })).toEqual(
open(0, 5),
);
expect(lightboxReducer(open(1, 5), { type: 'last' })).toEqual(
open(4, 5),
);
});
it('closes on close and when the list changes', () => {
expect(lightboxReducer(open(1, 5), { type: 'close' })).toEqual(
closedLightbox,
);
expect(
lightboxReducer(open(1, 5), { type: 'listChanged', count: 3 }),
).toEqual(closedLightbox);
});
it('ignores browsing while closed', () => {
for (const type of [
'next',
'prev',
'first',
'last',
'close',
] as const) {
expect(lightboxReducer(closedLightbox, { type })).toBe(
closedLightbox,
);
}
});
// Stateful property: any sequence of events gives the same result as a
// simple model that counts positions on a clock face
it('follows the model for any sequence of events (stateful)', () => {
type Model = { open: boolean; index: number; count: number };
const step = (model: Model, event: LightboxEvent): Model => {
if (event.type === 'open') {
return event.count < 1
? { open: false, index: 0, count: 0 }
: {
open: true,
index:
((event.index % event.count) + event.count) %
event.count,
count: event.count,
};
}
if (!model.open) return model;
if (event.type === 'next')
return { ...model, index: (model.index + 1) % model.count };
if (event.type === 'prev')
return {
...model,
index: (model.index + model.count - 1) % model.count,
};
if (event.type === 'first') return { ...model, index: 0 };
if (event.type === 'last')
return { ...model, index: model.count - 1 };
return { open: false, index: 0, count: 0 };
};
fc.assert(
fc.property(
fc.array(lightboxEvent, { maxLength: 40 }),
(events) => {
let state: LightboxState = closedLightbox;
let model: Model = { open: false, index: 0, count: 0 };
for (const event of events) {
state = lightboxReducer(state, event);
model = step(model, event);
expect(state.open).toBe(model.open);
if (state.open) {
expect(state.index).toBe(model.index);
expect(state.count).toBe(model.count);
expect(state.index).toBeGreaterThanOrEqual(0);
expect(state.index).toBeLessThan(state.count);
}
}
},
),
);
});
});
+49
View File
@@ -0,0 +1,49 @@
import { wrapIndex } from './wrapIndex';
// Whether the lightbox is open, and if so which photo of how many it shows
export type LightboxState =
{ open: false } | { open: true; index: number; count: number };
export type LightboxEvent =
| { type: 'open'; index: number; count: number }
| { type: 'next' }
| { type: 'prev' }
| { type: 'first' }
| { type: 'last' }
| { type: 'close' }
// The list of photos changed, e.g. another filter: the photo on screen
// may no longer be in it, so the lightbox closes
| { type: 'listChanged'; count: number };
export const closedLightbox: LightboxState = { open: false };
// The lightbox's transitions (functional design, state machine). Browsing
// wraps around; anything but opening leaves a closed lightbox closed.
export function lightboxReducer(
state: LightboxState,
event: LightboxEvent,
): LightboxState {
if (event.type === 'open') {
if (event.count < 1) return closedLightbox;
return {
open: true,
index: wrapIndex(event.index, event.count),
count: event.count,
};
}
if (!state.open) return state;
switch (event.type) {
case 'next':
return { ...state, index: wrapIndex(state.index + 1, state.count) };
case 'prev':
return { ...state, index: wrapIndex(state.index - 1, state.count) };
case 'first':
return { ...state, index: 0 };
case 'last':
return { ...state, index: state.count - 1 };
case 'close':
case 'listChanged':
return closedLightbox;
}
}
+80
View File
@@ -0,0 +1,80 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { imageSize } from '../test/arbitraries';
import {
GAP_ROWS,
masonryRowSpan,
ROWS_PER_COLUMN_WIDTH,
} from './masonryRowSpan';
const K = ROWS_PER_COLUMN_WIDTH;
describe('masonryRowSpan', () => {
it('spans rows by aspect ratio plus the gap', () => {
// Portrait 2:3, landscape 3:2, square
expect(masonryRowSpan({ width: 800, height: 1200 })).toBe(
60 + GAP_ROWS,
);
expect(masonryRowSpan({ width: 1200, height: 800 })).toBe(
27 + GAP_ROWS,
);
expect(masonryRowSpan({ width: 800, height: 800 })).toBe(40 + GAP_ROWS);
});
it('gives even a very wide photo at least one row', () => {
expect(masonryRowSpan({ width: 10000, height: 10 })).toBe(1 + GAP_ROWS);
});
it('is at least one row plus the gap (invariant)', () => {
fc.assert(
fc.property(imageSize, (size) => {
expect(masonryRowSpan(size)).toBeGreaterThanOrEqual(
GAP_ROWS + 1,
);
}),
);
});
it('grows with the photo height relative to its width (invariant)', () => {
fc.assert(
fc.property(imageSize, imageSize, (a, b) => {
const ratioA = a.height / a.width;
const ratioB = b.height / b.width;
if (ratioA <= ratioB) {
expect(masonryRowSpan(a)).toBeLessThanOrEqual(
masonryRowSpan(b),
);
}
}),
);
});
it('depends on the shape, not the file size (invariant)', () => {
fc.assert(
fc.property(
imageSize,
fc.integer({ min: 2, max: 4 }),
(size, factor) => {
expect(
masonryRowSpan({
width: size.width * factor,
height: size.height * factor,
}),
).toBe(masonryRowSpan(size));
},
),
);
});
it('crops at most half a row (easy verification)', () => {
fc.assert(
fc.property(imageSize, (size) => {
const exact = (K * size.height) / size.width;
if (exact >= 1) {
const rows = masonryRowSpan(size) - GAP_ROWS;
expect(Math.abs(rows - exact)).toBeLessThanOrEqual(0.5);
}
}),
);
});
});
+22
View File
@@ -0,0 +1,22 @@
// The masonry grid is a CSS grid with very small implicit rows: one row is
// 1/ROWS_PER_COLUMN_WIDTH of the column width, so a photo's height in rows
// follows from its aspect ratio alone, at any screen width. No measuring in
// the browser, so nothing shifts while photos load.
export const ROWS_PER_COLUMN_WIDTH = 40;
// Vertical space between two photos, in rows (about 5% of the column width)
export const GAP_ROWS = 2;
// How many implicit rows a photo spans: its height at the column width, in
// rows, plus the gap below it. Rounding crops at most half a row.
export function masonryRowSpan(
image: { width: number; height: number },
rowsPerColumnWidth: number = ROWS_PER_COLUMN_WIDTH,
gapRows: number = GAP_ROWS,
): number {
const photoRows = Math.max(
1,
Math.round((rowsPerColumnWidth * image.height) / image.width),
);
return photoRows + gapRows;
}
+56
View File
@@ -0,0 +1,56 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { neighbourIndexes } from './neighbourIndexes';
import { wrapIndex } from './wrapIndex';
// A list position together with the list length it belongs to
const position = fc.integer({ min: 1, max: 30 }).chain((count) =>
fc.record({
count: fc.constant(count),
index: fc.integer({ min: 0, max: count - 1 }),
radius: fc.integer({ min: 0, max: 4 }),
}),
);
describe('neighbourIndexes', () => {
it('lists the two photos on each side, nearest first', () => {
expect(neighbourIndexes(5, 10)).toEqual([6, 4, 7, 3]);
expect(neighbourIndexes(0, 10)).toEqual([1, 9, 2, 8]);
});
it('lists each photo once in a short list', () => {
expect(neighbourIndexes(0, 1)).toEqual([]);
expect(neighbourIndexes(0, 2)).toEqual([1]);
expect(neighbourIndexes(1, 3)).toEqual([2, 0]);
});
it('never repeats a photo or includes the current one (invariant)', () => {
fc.assert(
fc.property(position, ({ index, count, radius }) => {
const result = neighbourIndexes(index, count, radius);
expect(new Set(result).size).toBe(result.length);
expect(result).not.toContain(index);
for (const i of result) {
expect(i).toBeGreaterThanOrEqual(0);
expect(i).toBeLessThan(count);
}
expect(result).toHaveLength(Math.min(2 * radius, count - 1));
}),
);
});
it('matches all positions within the radius (oracle)', () => {
fc.assert(
fc.property(position, ({ index, count, radius }) => {
const expected = new Set<number>();
for (let d = -radius; d <= radius; d++) {
expected.add(wrapIndex(index + d, count));
}
expected.delete(index);
expect(new Set(neighbourIndexes(index, count, radius))).toEqual(
expected,
);
}),
);
});
});
+24
View File
@@ -0,0 +1,24 @@
import { wrapIndex } from './wrapIndex';
// The positions around `index` whose large photos the lightbox loads ahead,
// nearest first and alternating next/previous (next, previous, next+1, …).
// The list wraps around, so in a short list each photo appears once and the
// current one never.
export function neighbourIndexes(
index: number,
count: number,
radius: number = 2,
): number[] {
const result: number[] = [];
for (let distance = 1; distance <= radius; distance++) {
for (const candidate of [
wrapIndex(index + distance, count),
wrapIndex(index - distance, count),
]) {
if (candidate !== index && !result.includes(candidate)) {
result.push(candidate);
}
}
}
return result;
}
+63
View File
@@ -0,0 +1,63 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { point } from '../test/arbitraries';
import { SWIPE_THRESHOLD, swipeDirection } from './swipeDirection';
const origin = { x: 200, y: 300 };
describe('swipeDirection', () => {
it('reads a swipe to the left as next and to the right as previous', () => {
expect(swipeDirection(origin, { x: 120, y: 310 })).toBe('next');
expect(swipeDirection(origin, { x: 280, y: 290 })).toBe('prev');
});
it('ignores short and mostly vertical touches', () => {
expect(swipeDirection(origin, { x: 160, y: 300 })).toBeNull();
expect(swipeDirection(origin, { x: 120, y: 420 })).toBeNull();
expect(swipeDirection(origin, origin)).toBeNull();
});
it('counts a swipe of exactly the threshold', () => {
expect(
swipeDirection(origin, { x: origin.x - SWIPE_THRESHOLD, y: 300 }),
).toBe('next');
});
it('flips direction when the swipe is mirrored (invariant)', () => {
fc.assert(
fc.property(point, point, (start, end) => {
const mirrored = { x: 2 * start.x - end.x, y: end.y };
const flip = { next: 'prev', prev: 'next' } as const;
const result = swipeDirection(start, end);
expect(swipeDirection(start, mirrored)).toBe(
result === null ? null : flip[result],
);
}),
);
});
it('does not depend on where on the screen the swipe happens (invariant)', () => {
fc.assert(
fc.property(point, point, point, (start, end, offset) => {
const moved = (p: { x: number; y: number }) => ({
x: p.x + offset.x,
y: p.y + offset.y,
});
expect(swipeDirection(moved(start), moved(end))).toBe(
swipeDirection(start, end),
);
}),
);
});
it('is no swipe when too short or more vertical than horizontal (invariant)', () => {
fc.assert(
fc.property(point, point, (start, end) => {
const dx = Math.abs(end.x - start.x);
const dy = Math.abs(end.y - start.y);
const result = swipeDirection(start, end);
expect(result === null).toBe(dx < SWIPE_THRESHOLD || dx < dy);
}),
);
});
});
+21
View File
@@ -0,0 +1,21 @@
export interface Point {
x: number;
y: number;
}
// Minimum horizontal travel in px before a touch counts as a swipe
export const SWIPE_THRESHOLD = 50;
// Which way a touch from `start` to `end` browses: a swipe to the left shows
// the next photo, to the right the previous one. Too short, or more vertical
// than horizontal (the visitor is scrolling), is no swipe.
export function swipeDirection(
start: Point,
end: Point,
threshold: number = SWIPE_THRESHOLD,
): 'next' | 'prev' | null {
const dx = end.x - start.x;
const dy = end.y - start.y;
if (Math.abs(dx) < threshold || Math.abs(dx) < Math.abs(dy)) return null;
return dx < 0 ? 'next' : 'prev';
}
+78
View File
@@ -0,0 +1,78 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { wrapIndex } from './wrapIndex';
const count = fc.integer({ min: 1, max: 50 });
const index = fc.integer({ min: -1000, max: 1000 });
describe('wrapIndex', () => {
it('wraps past either end of the list', () => {
expect(wrapIndex(0, 5)).toBe(0);
expect(wrapIndex(5, 5)).toBe(0);
expect(wrapIndex(-1, 5)).toBe(4);
expect(wrapIndex(-6, 5)).toBe(4);
expect(wrapIndex(12, 5)).toBe(2);
expect(wrapIndex(3, 1)).toBe(0);
});
it('always lands inside the list (invariant)', () => {
fc.assert(
fc.property(index, count, (i, c) => {
const result = wrapIndex(i, c);
expect(Number.isInteger(result)).toBe(true);
expect(result).toBeGreaterThanOrEqual(0);
expect(result).toBeLessThan(c);
}),
);
});
it('is periodic in the list length (invariant)', () => {
fc.assert(
fc.property(
index,
count,
fc.integer({ min: -5, max: 5 }),
(i, c, k) => {
expect(wrapIndex(i + k * c, c)).toBe(wrapIndex(i, c));
},
),
);
});
it('changes nothing when applied twice (idempotence)', () => {
fc.assert(
fc.property(index, count, (i, c) => {
expect(wrapIndex(wrapIndex(i, c), c)).toBe(wrapIndex(i, c));
}),
);
});
it('returns to the same photo after next then previous (round-trip)', () => {
fc.assert(
fc.property(index, count, (i, c) => {
const start = wrapIndex(i, c);
const next = wrapIndex(start + 1, c);
expect(wrapIndex(next - 1, c)).toBe(start);
}),
);
});
it('matches stepping one by one through the list (oracle)', () => {
fc.assert(
fc.property(fc.integer({ min: -60, max: 60 }), count, (i, c) => {
let position = 0;
for (let step = 0; step < Math.abs(i); step++) {
position =
i > 0
? position === c - 1
? 0
: position + 1
: position === 0
? c - 1
: position - 1;
}
expect(wrapIndex(i, c)).toBe(position);
}),
);
});
});
+6
View File
@@ -0,0 +1,6 @@
// A position in a list of `count` items that wraps around both ways: one
// past the last is the first, one before the first is the last. Used for
// browsing photos in the hero and the lightbox.
export function wrapIndex(index: number, count: number): number {
return ((index % count) + count) % count;
}
+35
View File
@@ -0,0 +1,35 @@
import { defineRecipe } from '@chakra-ui/react';
// The buttons of a FilterBar: small caps in the eyebrow style, the chosen
// one in accent.deep with an underline (aria-pressed). ink.soft and
// accent.deep both reach 4.5:1 on paper; the 2px underline marks the choice
// for those who cannot tell the colours apart.
const filterControlRecipe = defineRecipe({
className: 'filter-control',
base: {
display: 'inline-flex',
alignItems: 'center',
// 44px touch target (BR-RWD-04)
minH: '44px',
px: 1,
bg: 'transparent',
textStyle: 'eyebrow',
color: 'ink.soft',
cursor: 'pointer',
textDecoration: 'underline',
textDecorationColor: 'transparent',
textDecorationThickness: '2px',
textUnderlineOffset: '0.55em',
transitionProperty: 'color, text-decoration-color',
transitionDuration: 'interaction',
transitionTimingFunction: 'smooth',
_hover: { color: 'ink' },
_pressed: {
color: 'accent.deep',
textDecorationColor: 'currentColor',
cursor: 'default',
},
},
});
export default filterControlRecipe;
+61
View File
@@ -1,8 +1,11 @@
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 type { Point } from '../lib/swipeDirection';
import type {
EmailAddress,
GalleryItem,
FrameColor,
PricingPackage,
ShootType,
@@ -317,3 +320,61 @@ export const contactEvent: fc.Arbitrary<ContactFormEvent> = fc.oneof(
fc.constant({ type: 'resolved' as const }),
fc.constant({ type: 'rejected' as const }),
);
// --- Gallery (portfolio) ---
// A touch position on a screen, in CSS pixels
export const point: fc.Arbitrary<Point> = fc.record({
x: fc.integer({ min: 0, max: 2000 }),
y: fc.integer({ min: 0, max: 3000 }),
});
// The intrinsic size of a photo: realistic pixel sizes, from very wide
// panoramas to tall portraits
export const imageSize = fc.record({
width: fc.integer({ min: 200, max: 4000 }),
height: fc.integer({ min: 200, max: 4000 }),
});
export const galleryItem: fc.Arbitrary<GalleryItem> = fc
.tuple(
fc.stringMatching(/^[a-z0-9-]{1,12}$/),
imageSize,
fc.integer({ min: 2, max: 3 }),
nonBlank,
fc.option(nonBlank, { nil: undefined }),
)
.map(([id, size, factor, alt, caption]) => ({
id,
thumb: { src: `/${id}-thumb.jpg`, alt, ...size },
full: {
src: `/${id}.jpg`,
width: size.width * factor,
height: size.height * factor,
},
caption,
}));
export const galleryItems = fc.uniqueArray(galleryItem, {
selector: (item) => item.id,
minLength: 1,
maxLength: 12,
});
// Anything that can happen to the lightbox, for the state machine test
export const lightboxEvent: fc.Arbitrary<LightboxEvent> = fc.oneof(
fc.record({
type: fc.constant('open' as const),
index: fc.integer({ min: -3, max: 15 }),
count: fc.integer({ min: 0, max: 12 }),
}),
fc.constant({ type: 'next' as const }),
fc.constant({ type: 'prev' as const }),
fc.constant({ type: 'first' as const }),
fc.constant({ type: 'last' as const }),
fc.constant({ type: 'close' as const }),
fc.record({
type: fc.constant('listChanged' as const),
count: fc.integer({ min: 0, max: 12 }),
}),
);
+15
View File
@@ -0,0 +1,15 @@
import { introPhotos } from '../content/homeContent';
import type { GalleryItem } from '../content/types';
// Gallery items for component tests, built from photos the site already
// has. The large size is a stand-in: same file, twice the stated size.
export const galleryItems: GalleryItem[] = introPhotos.map((photo, i) => ({
id: `foto-${i + 1}`,
thumb: photo,
full: {
src: `${photo.src}?groot`,
width: photo.width * 2,
height: photo.height * 2,
},
caption: i % 2 === 0 ? 'Newbornshoot' : undefined,
}));
+3
View File
@@ -1,6 +1,7 @@
import { createSystem, defaultConfig, defineConfig } from '@chakra-ui/react';
import carouselControlRecipe from './recipes/carouselControl';
import containerRecipe from './recipes/container';
import filterControlRecipe from './recipes/filterControl';
import formControlRecipe from './recipes/formControl';
import iconControlRecipe from './recipes/iconControl';
import linkRecipe from './recipes/link';
@@ -101,6 +102,7 @@ const config = defineConfig({
interaction: { value: '0.45s' }, // hover, focus
fade: { value: '1.2s' }, // overvloeien van foto's
reveal: { value: '0.8s' }, // fade-in of sections on scroll
swap: { value: '0.3s' }, // crossfade between photos in the lightbox
},
// Stapelvolgorde van de vaste shell-onderdelen, van laag naar hoog
zIndex: {
@@ -236,6 +238,7 @@ const config = defineConfig({
iconControl: iconControlRecipe,
carouselControl: carouselControlRecipe,
formControl: formControlRecipe,
filterControl: filterControlRecipe,
},
},
});