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:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user