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,37 @@
# Code Summary — Unit 2: Gallery building blocks
Plan: [gallery-blocks-code-generation-plan.md](../../plans/gallery-blocks-code-generation-plan.md) · Design: [functional-design/](../functional-design/)
## Created (`web/src/`)
| File | What |
|---|---|
| `lib/wrapIndex.ts` (+ test) | Position that wraps both ways; PBT: range, periodicity, idempotence, round-trip, oracle (step-by-step) |
| `lib/swipeDirection.ts` (+ test) | `next`/`prev`/`null` from two touch points, `SWIPE_THRESHOLD = 50`; PBT: mirror, translation, threshold rule |
| `lib/masonryRowSpan.ts` (+ test) | Row span from aspect ratio (`ROWS_PER_COLUMN_WIDTH = 40`, `GAP_ROWS = 2`); PBT: minimum, monotonic, scale invariance, ≤ ½ row crop |
| `lib/neighbourIndexes.ts` (+ test) | Large photos to preload around the current one; PBT: unique, excludes current, size, oracle (brute force) |
| `lib/lightboxReducer.ts` (+ test) | Lightbox state machine; stateful PBT against a model |
| `hooks/useSwipe.ts` (+ test) | Touch handlers on top of `swipeDirection` |
| `recipes/filterControl.ts` | Eyebrow-style toggle button, pressed = `accent.deep` + 2 px underline |
| `components/FilterBar/` (+ test) | Group of toggle buttons with `aria-pressed`; nothing for < 2 options |
| `components/PortfolioGrid/` (+ test) | CSS-only masonry in reading order (`--cols`, `--row` in container units), first 3 eager with `fetchPriority="high"`, tile = link to the large photo, modifier clicks left to the browser, `onIntent` once |
| `components/Lightbox/` (+ test) | Chakra `Dialog` (unstyled), wrap-around browsing with buttons/arrows/Home/End/swipe, counter, caption, announcement, thumb while loading, error note, preload 2 each side, phone bottom bar, crossfade (0.3 s, off under reduced motion); default export for `React.lazy` |
| `test/galleryFixtures.ts` | Gallery items from the homepage intro photos |
## Modified
| File | Change |
|---|---|
| `content/types.ts` | `ImageSource`, `GalleryItem`, `FilterOption` |
| `test/arbitraries.ts` | `point`, `imageSize`, `galleryItem`, `galleryItems`, `lightboxEvent` |
| `theme.ts` | Duration token `swap` (0.3 s); recipe `filterControl` registered (typegen run) |
| `components/Hero/useHeroSlider.ts` | Uses `useSwipe` (enabled with more than one slide) and `wrapIndex`; inline touch handlers and local threshold removed. Hero tests unchanged and passing |
Docs: own RE lines (code-structure, architecture, api-documentation).
## Verification
- `tsc`, ESLint, Prettier: clean. ESLint flagged `setState` inside effects in the first Lightbox version; fixed at the cause (load state lives in the keyed `Photo`; announcement reset during render when `open` changes), not by disabling the rule.
- Tests: ✅ 80 files, 426 tests (coverage thresholds met).
- Generated masonry CSS checked in jsdom: `--cols` 1/2/3 per breakpoint, `--row` uses `var(--slp-spacing-grid-gap)`, tiles `span n`, photo height `100% - 2 × --row`.
- jsdom limits, handled in the tests with comments: the focus trap needs layout boxes (focus test stubs `getClientRects`); Chakra unmounts after the fade-out, which needs real animation events, so the close test checks `data-state="closed"` and `onClose`.
- Lighthouse desktop: ✅ all 7 URLs.
- Lighthouse mobile: ❌ `/` (0.75, rerun 0.79; budget 0.8) and `/contact` (0.88; budget 0.9). **Pre-existing, not caused by this unit**: master measured right before on the same machine gives `/` 0.78 and `/contact` 0.88; this unit adds 0.54 kB (0.12 kB gzip) to the main bundle and no route of these pages renders the new components. Known open item (memory note "Open follow-ups", owner chose to handle it separately). Portfolio itself was not measured as a real page yet (still the placeholder until unit 3).
- Visual check: deferred to unit 3 (the components are on no page yet).
@@ -0,0 +1,68 @@
# Business Logic Model — Unit 2: Gallery building blocks
## Flow — open, browse, close
```mermaid
sequenceDiagram
box rgba(246,224,94,0.4) Visitor
participant V as Visitor
end
box rgba(99,179,237,0.4) Components
participant G as PortfolioGrid
participant P as Parent
participant L as Lightbox
end
V->>G: hover or focus a tile
G->>P: onIntent once
P->>P: start loading the lightbox code
V->>G: click tile n
G->>P: onOpen with index n
P->>L: render with index n
L->>L: focus close button, show thumb, load full, preload two each side
V->>L: arrow, Home, End or swipe
L->>P: onIndexChange with the wrapped index
L->>V: announce position and caption
V->>L: Escape, close button or backdrop
L->>P: onClose
P->>G: focus the tile of the last shown item
```
Text alternative: hovering or focusing a tile asks the parent to load the lightbox code; clicking a tile opens the lightbox at that index; the lightbox focuses its close button, shows the thumb while the large image and its neighbours load; browsing reports the wrapped index to the parent and announces the position; closing returns focus to the tile of the last shown item.
## Lightbox State Machine
The parent owns the state (application design: `PortfolioGallery` owns the open item). A pure reducer `lightboxReducer(state, event)` makes the transitions testable.
```mermaid
graph TD
Closed["closed"] -->|"open(i, count), count at least 1"| Open["open at index i"]
Open -->|"next / prev"| Open
Open -->|"first / last"| Open
Open -->|"close"| Closed
Open -->|"listChanged(count)"| Closed
Closed -->|"next, prev, first, last, close, listChanged"| Closed
classDef state fill:#2196F3,stroke:#0d47a1,color:#000;
class Closed,Open state;
```
Text alternative: a closed lightbox opens at an index when the list is not empty; while open, next/prev/first/last stay open at a new index and close or a list change closes it; every other event leaves a closed lightbox closed.
Rules: `open(i, count)` clamps `i` into range with `wrapIndex`; `count = 0` keeps it closed. `next`/`prev` use `wrapIndex(index ± 1, count)`; `first` → 0; `last` → count − 1.
## Pure Helpers and Testable Properties (PBT-01)
All in `web/src/lib/`, 100% coverage threshold, example-based tests plus property-based tests with generators in `src/test/arbitraries.ts` (PBT-07).
| Helper | Purpose | Properties (category) |
|---|---|---|
| `wrapIndex(index, count)` | Position in `0..count−1`, wrapping both ways | Result in range for any integer index and count ≥ 1 (invariant); `wrapIndex(wrapIndex(i)+1)−1` returns to `wrapIndex(i)` (round-trip); `wrapIndex(i + k·count) = wrapIndex(i)` (invariant, periodicity); `wrapIndex(wrapIndex(i)) = wrapIndex(i)` (idempotence); equals `((i % c) + c) % c` (oracle) |
| `swipeDirection(start, end, threshold = 50)` | `'next'`, `'prev'` or `null` | Mirroring dx flips `next` ↔ `prev` (invariant); below threshold or more vertical than horizontal → `null` (invariant); translating both points by the same offset does not change the result (invariant) |
| `masonryRowSpan({ width, height }, K = 40, gapRows = 2)` | Implicit rows an item spans | Always ≥ gapRows + 1 (range); non-decreasing in height/width (invariant, monotonic); scaling width and height by the same factor gives the same span (invariant); `|span − gapRows − K·h/w| ≤ 0.5` (easy verification) |
| `neighbourIndexes(index, count, radius = 2)` | Large images to preload | No duplicates, never contains `index`, all in range (invariant); size = `min(2·radius, count − 1)` (invariant); symmetric: contains `wrapIndex(index ± d)` for d ≤ radius when count is large enough (oracle against a brute-force set) |
| `lightboxReducer(state, event)` | Lightbox transitions | Stateful PBT: random event sequences against a simple model (`{open, index}` with modular arithmetic) — after every event the states match and an open index is in range (PBT-06) |
Components with no extra properties beyond these helpers: `PortfolioGrid`, `Lightbox`, `FilterBar` (presentational; example-based tests and axe cover them — PBT-10 complementary).
## Hero Refactor
- `useHeroSlider.go(to)` uses `wrapIndex(to, count)` instead of `(to + count) % count` (same results for the values it receives).
- Its inline `onTouchStart`/`onTouchEnd` are replaced by `useSwipe({ onPrev: prev, onNext: next, enabled: count > 1 })`. Existing hero tests must pass unchanged (oracle: today's behaviour).
@@ -0,0 +1,71 @@
# Business Rules — Unit 2: Gallery building blocks
Decisions: [gallery-blocks-fd-questions.md](../../plans/gallery-blocks-fd-questions.md) (answered 2026-10-25), requirements FR-PF-03, 05–07, NFR-PF-01/02/05, application design Q1–Q7.
## Grid (`PortfolioGrid`)
- **BR-GR-01 Order**: items render in the given order as `ul > li`; DOM, tab and reading order follow it (row order, left to right).
- **BR-GR-02 Columns**: 1 column on phones, 2 from `md`, 3 from `lg` (the design's 2/3 steps on the theme breakpoints); column gap `gridGap`.
- **BR-GR-03 Row span**: each item spans `masonryRowSpan(thumb) = round(K × height / width) + GAP_ROWS` implicit rows, with implicit row height = column width / K (container units). The photo fills the item minus the gap rows with `object-fit: cover`; the crop from rounding is at most half a row (≤ 1.25% of the height). No JavaScript measuring (Q6/6a).
- **BR-GR-04 Loading**: the first `EAGER_COUNT` (3) items of the list as given load immediately with `fetchPriority="high"`; the rest use `DeferredImage`. Intrinsic width/height on every image.
- **BR-GR-05 Tile = link**: each tile is `<a href={full.src}>`. A plain click or Enter calls `onOpen(index)` and prevents navigation. A click with Ctrl/Cmd/Shift/Alt or the middle button is left to the browser (opens the large image as a normal link). Without JavaScript the link opens the large image.
- **BR-GR-06 Name**: accessible name = alt text + " (groot bekijken)" (visually hidden suffix). *Q6 = A*
- **BR-GR-07 Intent**: the first pointer enter or focus on any tile calls `onIntent()` once per mount (preload the lightbox code).
- **BR-GR-08 Hover/focus**: zoom 1.05 + dark overlay (design `.portfolio-item`), `cursor: zoom-in`; under reduced motion no zoom, overlay only. The focus ring sits above neighbouring tiles.
- **BR-GR-09 List change**: when the list changes (another filter), tiles swap immediately without animation; tiles that were never in view show at once (no fade-in replay). *Q9 = A*
- **BR-GR-10 Empty list**: renders an empty list (no tiles, no error); the page decides whether to show the grid at all.
## Lightbox (`Lightbox`)
- **BR-LB-01 Dialog**: Chakra `Dialog`, modal, named "Foto groot bekijken" (overridable); background inert, page does not scroll; dark backdrop.
- **BR-LB-02 Image**: the current item's `full` image, whole (`object-fit: contain`), within the viewport; alt text from `thumb.alt`.
- **BR-LB-03 Navigation**: next/previous wrap around (`wrapIndex`); Home → first, End → last (*Q10 = A*); ← → as previous/next; swipe left = next, swipe right = previous (`swipeDirection`, threshold 50 px, |dx| ≥ |dy|). No swipe-down to close (*Q4 = A*).
- **BR-LB-04 Closing**: close button, Escape, click on the backdrop. Click/tap on the image itself does nothing (*Q3 = A*).
- **BR-LB-05 Controls layout**: phones: bottom bar "vorige · teller · volgende", close top right; from `md`: previous/next at the left and right edges halfway, close top right, counter under the image (design). Controls never cover the image on phones. All targets ≥ 44 × 44 px. *Q2 = A*
- **BR-LB-06 Counter and caption**: counter "n / total" (1-based); caption = `item.caption` when present. With one item: no previous/next, no counter, no Home/End/arrow handling.
- **BR-LB-07 Announcement**: after every navigation (not on open), a polite live region says "Foto n van total" plus ", {caption}" when there is a caption. *Q5 = A*
- **BR-LB-08 Focus**: on open, focus goes to the close button; Tab cycles inside the dialog; on close, focus returns to the grid tile of the item shown last (via the parent's `finalFocus`).
- **BR-LB-09 List change while open**: if the list changes (another filter) while open, the lightbox closes (the parent resets `index` to `null`). The state reducer treats `listChanged` the same way.
- **BR-LB-10 Transition**: a short crossfade (~0.3 s) on open, close and item change; none under `prefers-reduced-motion`. *Q1 = A*
- **BR-LB-11 Loading**: while the large image loads, the thumb (already cached) is shown in its place at the same size; no empty flash, no layout jump.
- **BR-LB-12 Load error**: if the large image fails, the thumb stays and a short message "Deze foto kon niet groot geladen worden" appears under it (in the caption area, polite live region); browsing keeps working and the message disappears on the next item. *Q7 = B*
- **BR-LB-13 Preloading**: while open, the large images of up to `PRELOAD_RADIUS` (2) items on each side (wrapping, no duplicates, never the current one) are requested. *Q8 = B*
## Filter bar (`FilterBar`)
- **BR-FB-01 Options**: one toggle button per option in the given order; exactly one is pressed (`aria-pressed="true"`), the one whose `id` equals `value`.
- **BR-FB-02 Group**: `role="group"` with an accessible name (prop `label`); every button is a tab stop.
- **BR-FB-03 Fewer than two options**: render nothing.
- **BR-FB-04 Choosing**: clicking (or Enter/Space on) a button that is not pressed calls `onChange(id)`; clicking the pressed one does nothing. Focus stays on the button.
- **BR-FB-05 Style**: eyebrow text style; pressed = `accent.deep` with a 2 px underline; others `ink.soft`; hover darkens to `ink`. Contrast ≥ 4.5:1 for text, ≥ 3:1 for the underline against `paper`. Targets ≥ 44 px high.
- **BR-FB-06 Unknown value**: if `value` matches no option, no button is pressed (the page must pass a valid value; unit 3 guarantees it).
## Swipe (`useSwipe`, `swipeDirection`)
- **BR-SW-01**: a swipe counts when |dx| ≥ 50 px and |dx| ≥ |dy|; dx < 0 → `next`, dx > 0 → `prev`; otherwise nothing.
- **BR-SW-02**: a touch end without a recorded start does nothing; the start is cleared after every touch end.
- **BR-SW-03 Hero**: `useHeroSlider` uses `useSwipe` and `wrapIndex`; its swipe and wrap behaviour are unchanged (existing hero tests pass unchanged). The hero keeps its own rule that swiping does nothing with fewer than two slides (`enabled`).
## Decision Flow — a key press in the open lightbox
```mermaid
graph TD
Key["Key press"] --> Esc{"Escape?"}
Esc -->|"yes"| Close["Close (Chakra)"]
Esc -->|"no"| Many{"More than one item?"}
Many -->|"no"| Ignore["Ignore"]
Many -->|"yes"| Which{"Which key?"}
Which -->|"ArrowRight"| Next["wrapIndex(index + 1)"]
Which -->|"ArrowLeft"| Prev["wrapIndex(index - 1)"]
Which -->|"Home"| First["index 0"]
Which -->|"End"| Last["index count - 1"]
Which -->|"other"| Ignore
Next --> Announce["Announce position and caption"]
Prev --> Announce
First --> Announce
Last --> Announce
classDef decision fill:#FF9800,stroke:#e65100,color:#000;
classDef action fill:#2196F3,stroke:#0d47a1,color:#000;
classDef stop fill:#e2e8f0,stroke:#4a5568,color:#000;
class Esc,Many,Which decision;
class Close,Next,Prev,First,Last,Announce action;
class Ignore stop;
```
Text alternative: Escape always closes; with a single item other keys are ignored; otherwise the arrow keys wrap to the next or previous item, Home and End jump to the first and last, any other key is ignored, and every move is announced with position and caption.
@@ -0,0 +1,66 @@
# Domain Entities — Unit 2: Gallery building blocks
Generic entities only; nothing here knows about shoot types, filters on the portfolio, or the URL (that is unit 3).
## Relationships
```mermaid
graph TD
Item["GalleryItem"] -->|"thumb"| Thumb["ContentImage (grid size, alt)"]
Item -->|"full"| Full["ImageSource (lightbox size)"]
Item -->|"caption?"| Caption["visible caption text"]
Grid["PortfolioGrid"] -->|"shows list of"| Item
Box["Lightbox"] -->|"shows one of"| Item
Box -->|"driven by"| State["LightboxState"]
Filter["FilterBar"] -->|"offers list of"| Option["FilterOption"]
Swipe["useSwipe"] -->|"compares"| Points["two Points"]
classDef entity fill:#2196F3,stroke:#0d47a1,color:#000;
classDef comp fill:#4CAF50,stroke:#2e7d32,color:#000;
classDef value fill:#e2e8f0,stroke:#4a5568,color:#000;
class Item,State,Option entity;
class Grid,Box,Filter,Swipe comp;
class Thumb,Full,Caption,Points value;
```
Text alternative: a GalleryItem has a grid image with alt text, a large image and an optional caption; the grid shows a list of items, the lightbox shows one item at a time driven by a LightboxState; the filter bar offers FilterOptions; useSwipe compares two touch points.
## Entities
### GalleryItem
| Field | Type | Rule |
|---|---|---|
| `id` | `string` | Unique within a list; used as React key and test id suffix |
| `thumb` | `ContentImage` (`src`, `alt`, `width`, `height`) | Grid size (~800 px wide), photo's own aspect ratio; `alt` is the description for both sizes |
| `full` | `ImageSource` (`src`, `width`, `height`) | Lightbox size (~1600–2000 px); same aspect ratio as `thumb` (± rounding) |
| `caption?` | `string` | Visible under the large image; empty or missing → no caption element |
### ImageSource
`{ src: string; width: number; height: number }` — `width`, `height` positive integers (intrinsic size).
### FilterOption
| Field | Type | Rule |
|---|---|---|
| `id` | `string` | Unique within the options |
| `label` | `string` | Visible text (Dutch) |
### LightboxState
A closed lightbox, or an open one at a position in the current list.
| Variant | Shape | Meaning |
|---|---|---|
| closed | `{ open: false }` | No dialog |
| open | `{ open: true; index: number; count: number }` | Showing item `index` of a list of `count` (0 ≤ index < count, count ≥ 1) |
Events: `open(index, count)`, `next`, `prev`, `first`, `last`, `close`, `listChanged(count)` (see business-rules BR-LB-09).
### Point
`{ x: number; y: number }` — a touch position in CSS pixels (start and end of a swipe).
### Masonry dimensions
| Name | Value | Meaning |
|---|---|---|
| `ROWS_PER_COLUMN_WIDTH` (K) | 40 | One implicit grid row is 1/40 of the column width |
| `GAP_ROWS` | 2 | Vertical gap between photos, in rows (≈ 5% of the column width) |
| `EAGER_COUNT` | 3 | First items in the list that load immediately |
| `PRELOAD_RADIUS` | 2 | Large images preloaded on each side of the current one |
| `SWIPE_THRESHOLD` | 50 px | Minimum horizontal travel for a swipe (same as the hero today) |
@@ -0,0 +1,62 @@
# Frontend Components — Unit 2: Gallery building blocks
## Component Hierarchy (unit 2 parts, with the unit 3 parent for context)
```mermaid
graph TD
Parent["PortfolioGallery (unit 3, owns index)"] --> Filter["FilterBar"]
Parent --> Grid["PortfolioGrid"]
Parent --> Lazy["Suspense + lazy Lightbox"]
Grid --> Tile["tile link per item"]
Tile --> Deferred["DeferredImage or eager Image"]
Lazy --> Box["Lightbox"]
Box --> Dialog["Chakra Dialog"]
Box --> Figure["figure: image, caption, error message"]
Box --> Controls["close, previous, next, counter"]
Box --> Live["live region"]
Box --> SwipeHook["useSwipe"]
Hero["Hero / useHeroSlider"] --> SwipeHook
classDef root fill:#4CAF50,stroke:#2e7d32,color:#000;
classDef ui fill:#2196F3,stroke:#0d47a1,color:#000;
classDef hook fill:#9C27B0,stroke:#4a148c,color:#000;
class Parent root;
class Filter,Grid,Tile,Deferred,Lazy,Box,Dialog,Figure,Controls,Live,Hero ui;
class SwipeHook hook;
```
Text alternative: the unit 3 parent renders the FilterBar, the PortfolioGrid with one link tile per item, and the lazily loaded Lightbox inside Suspense; the Lightbox wraps a Chakra Dialog with the figure, the controls and a live region and uses useSwipe, which the hero also uses.
## PortfolioGrid
- **Props**: `items: readonly GalleryItem[]`, `eagerCount = 3`, `onOpen(index)`, `onIntent?()`, `'data-testid'?` (default `portfolio-grid`)
- **State**: none except a ref "intent already reported"
- **Markup**: wrapper with `container-type: inline-size`; `ul` grid (columns per BR-GR-02, `grid-auto-rows` = column width / 40 via `cqi`); `li` with `gridRowEnd: span {masonryRowSpan}`; `a` (`data-testid="portfolio-tile-{n}"`, 1-based) → image (`Image` with `fetchPriority="high"` for n ≤ eagerCount, else `DeferredImage`) + `VisuallyHidden` " (groot bekijken)"
- **Styling**: overlay via `_after`, zoom via `_groupHover`/`_groupFocusVisible` like `InstagramGrid`; `_motionReduce` removes zoom; `Reveal` around the list (not per tile, so a filter change does not replay fades — BR-GR-09)
## Lightbox
- **Props**: `items`, `index: number | null`, `onIndexChange(index)`, `onClose()`, `label = 'Foto groot bekijken'`, `finalFocusEl?: () => HTMLElement | null`
- **Internal state**: `loaded`/`failed` for the current full image (reset on index change); announcement text
- **Markup**: `Dialog.Root` (controlled `open={index !== null}`, `onOpenChange` → `onClose`, `initialFocusEl` → close button, `finalFocusEl`), `Dialog.Backdrop` (dark), `Dialog.Positioner` → `Dialog.Content` (`data-testid="lightbox"`) with: `figure` (image, `figcaption` with caption or the error message), close button (`lightbox-close`), previous (`lightbox-prev`), next (`lightbox-next`), counter (`lightbox-counter`), visually hidden live region (`aria-live="polite"`)
- **Buttons**: `iconControl` recipe on the dark backdrop (white, focus ring white), 44 px min; labels "Sluiten", "Vorige foto", "Volgende foto"; icons from `@iconify-icons/ant-design` (already a dependency)
- **Keyboard**: per the decision flow in business-rules (Escape via Chakra)
- **Swipe**: `useSwipe` handlers on the figure
- **Preloading**: `new Image().src = full.src` for `neighbourIndexes(index, count, 2)` while open
- **Theme**: a new duration token `swap` (0.3 s) for the crossfade; the dialog's z-index from Chakra's `modal` layer, above the header (verified in tests/visually)
## FilterBar
- **Props**: `options: readonly FilterOption[]`, `value: string`, `onChange(id)`, `label: string`
- **Markup**: `div role="group" aria-label={label}` (`data-testid="filter-bar"`) → `button type="button" aria-pressed` per option (`data-testid="filter-{id}"`)
- **Styling**: new recipe `filterControl` (eyebrow text style, pressed state per BR-FB-05)
## useSwipe
- **Signature**: `useSwipe({ onPrev, onNext, enabled = true }) → { onTouchStart, onTouchEnd }`
- **State**: a ref with the start point
## Accessibility Summary
| Element | Name | Role/state |
|---|---|---|
| Grid tile | alt + " (groot bekijken)" | link |
| Lightbox | "Foto groot bekijken" | dialog, modal |
| Lightbox buttons | "Sluiten", "Vorige foto", "Volgende foto" | button |
| Counter | visible "3 / 10" | text (announcement carries "Foto 3 van 10") |
| Live region | — | `aria-live="polite"`: position + caption, or the load error |
| Filter group | prop `label` | group of buttons with `aria-pressed` |
@@ -0,0 +1,63 @@
# Code Generation Plan — Unit 2: Gallery building blocks
Single source of truth for code generation of this unit. Workspace root: `K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-portfolio` (worktree); all code in `web/src/`. Branch `feature/portfolio-page` (on master 1bf28cb).
## Unit Context
- **Requirements**: FR-PF-03 (filter bar), FR-PF-05 (masonry grid), FR-PF-06 (lightbox), FR-PF-07 (image loading), NFR-PF-01 (accessibility), NFR-PF-02 (reuse, generic APIs, helpers in `lib/`), NFR-PF-03 (example + property-based tests), NFR-PF-05 (performance)
- **Design**: [application design](../../inception/application-design/application-design.md) (unit 2 row), [functional design](../gallery-blocks/functional-design/) — business rules BR-GR/LB/FB/SW, state machine, helper properties
- **Dependencies**: none on unit 3 or other features. Unit 3 (`PortfolioGallery`, route) builds on everything here. Components are tested with fixture data; they are not on a page yet
- **Touches existing code**: `components/Hero/useHeroSlider.ts` (swipe + wrap extracted; behaviour unchanged), `theme.ts` (one duration token, one recipe), `content/types.ts`, `test/arbitraries.ts`
- **Comments in English** in new code and in new comments in existing files
## Steps
### Types and pure helpers (`lib/`, 100% coverage, example + PBT)
- [x] **Step 1** — `content/types.ts`: `ImageSource`, `GalleryItem`, `FilterOption` (domain-entities.md).
- [x] **Step 2** — `lib/wrapIndex.ts` + `wrapIndex.test.ts`: examples (−1, count, large negatives) and properties: range, periodicity, idempotence, next-then-previous round-trip, oracle `((i % c) + c) % c`.
- [x] **Step 3** — `lib/swipeDirection.ts` (exports `SWIPE_THRESHOLD = 50`) + test: examples (left, right, short, vertical, exactly 50) and properties: mirror flips, translation invariance, below threshold / more vertical → `null`.
- [x] **Step 4** — `lib/masonryRowSpan.ts` (exports `ROWS_PER_COLUMN_WIDTH = 40`, `GAP_ROWS = 2`) + test: examples (portrait 2:3, landscape 3:2, square) and properties: minimum, monotonic in h/w, scale invariance, `|span − gapRows − K·h/w| ≤ 0.5`.
- [x] **Step 5** — `lib/neighbourIndexes.ts` + test: examples (count 1, 2, 3, 10) and properties: no duplicates, excludes index, in range, size `min(2·radius, count − 1)`, oracle against a brute-force set.
- [x] **Step 6** — `lib/lightboxReducer.ts` (`LightboxState`, `LightboxEvent`, `closedLightbox`) + test: examples per transition and a stateful property: random event sequences against a model; open index always in range.
- [x] **Step 7** — `test/arbitraries.ts`: `imageSize` (positive integer width/height within realistic photo bounds), `galleryItem` / `galleryItems` (unique ids), `lightboxEvent`.
### Hook and hero refactor
- [x] **Step 8** — `hooks/useSwipe.ts` + `useSwipe.test.tsx`: calls `onNext`/`onPrev` per `swipeDirection`, nothing when `enabled` is false or without a start, start cleared after each end.
- [x] **Step 9** — `components/Hero/useHeroSlider.ts`: use `useSwipe({ onPrev: prev, onNext: next, enabled: count > 1 })` and `wrapIndex` in `go`; remove the inline touch handlers and the local threshold. Existing hero tests pass unchanged.
### Theme
- [x] **Step 10** — `theme.ts`: duration token `swap` (0.3 s, lightbox crossfade); new recipe `recipes/filterControl.ts` (eyebrow style, pressed state `accent.deep` + 2 px underline, hover `ink`, min height 44 px) registered under `recipes`; run `pnpm typegen`.
### Components (example-based tests + axe)
- [x] **Step 11** — `components/FilterBar/FilterBar.tsx` + test: group name, one pressed button, order, `onChange` only for a non-pressed button, nothing rendered for < 2 options, no button pressed for an unknown value, axe clean.
- [x] **Step 12** — `components/PortfolioGrid/PortfolioGrid.tsx` + test: list in order, tile names (alt + " (groot bekijken)"), href = full image, first 3 eager with `fetchpriority="high"` and the rest deferred, row spans from `masonryRowSpan`, plain click → `onOpen(index)` + prevented, Ctrl/Meta click not intercepted, `onIntent` once, empty list, axe clean.
- [x] **Step 13** — `components/Lightbox/Lightbox.tsx` (default export, for `React.lazy`) + test: closed renders nothing; open shows the item's full image with alt, caption, counter; next/prev buttons and keys wrap; Home/End; Escape and close button call `onClose`; image click does nothing; single item hides prev/next/counter; announcement text after navigation; load error shows the message and keeps the thumb; neighbours preloaded (2 each side); focus on the close button when opened; axe clean while open.
- [x] **Step 14** — `test/galleryFixtures.ts`: a few `GalleryItem`s built from existing assets (home intro photos) for the component tests.
### Verification and docs
- [x] **Step 15** — Search: no leftover inline swipe code or `SWIPE_THRESHOLD` duplicate in the hero; no duplicate component files.
- [x] **Step 16** — Check ListAgents for parallel sessions and follow the 4173 protocol if any is active; run `pnpm check` in `web/` (lint, format, build, tests with coverage, audits, Lighthouse). Fix and rerun until green. *Outcome: all green except mobile Lighthouse on `/` and `/contact`, which fail identically on master (pre-existing budget issue); see code summary.*
- [x] **Step 17** — Visual check: the components are not on a page yet; their look is verified in unit 3 (browser check on the portfolio page). The hero swipe is covered by its unchanged tests.
- [x] **Step 18** — Update the reverse engineering lines for the new shared components, hook and helpers (code-structure, architecture, api-documentation; own lines only).
- [x] **Step 19** — Write `aidlc-docs/features/portfolio-page/construction/gallery-blocks/code/code-summary.md`.
- [x] **Step 20** — Commit on `feature/portfolio-page` ("Adds the shared gallery building blocks"), together with the unit 2 functional design docs. No push until asked.
## Files
- **Created**: `lib/{wrapIndex,swipeDirection,masonryRowSpan,neighbourIndexes,lightboxReducer}.ts` + tests; `hooks/useSwipe.ts` + test; `recipes/filterControl.ts`; `components/{FilterBar,PortfolioGrid,Lightbox}/*.tsx` + tests; `test/galleryFixtures.ts`
- **Modified**: `content/types.ts`, `test/arbitraries.ts`, `theme.ts` (+ generated Chakra types), `components/Hero/useHeroSlider.ts`
- **Docs**: RE own lines, unit code summary
## Extension Compliance (unit 2)
| Rule | Status | Rationale |
|---|---|---|
| SECURITY-10 | Compliant | No new dependencies (Chakra `Dialog`, `@iconify-icons/ant-design` and fast-check are already present) |
| SECURITY-13 | Compliant | Lazy chunk is our own bundle; no external resources |
| Other SECURITY rules | N/A | Presentational components and pure helpers; no data, endpoints, headers or input from outside (the URL parameter is unit 3) |
| PBT-01 | Compliant | Properties identified in business-logic-model.md, mapped to steps 2–6 |
| PBT-02 | Planned | Round-trip: `wrapIndex` next-then-previous (step 2) |
| PBT-03 | Planned | Invariants: steps 2–5 |
| PBT-04 | Planned | Idempotence: `wrapIndex` (step 2) |
| PBT-05 | Planned | Oracles: `wrapIndex` modular formula, `neighbourIndexes` brute force, hero behaviour via unchanged tests |
| PBT-06 | Planned | Stateful: `lightboxReducer` against a model (step 6) |
| PBT-07 | Planned | Domain generators in `test/arbitraries.ts` (step 7) |
| PBT-08 / 09 | Compliant | Existing seed logging and fast-check |
| PBT-10 | Planned | Every helper and component also has example-based tests |
@@ -0,0 +1,103 @@
# Functional Design-vragen — Unit 2: Galerijbouwstenen
Al vastgelegd (geen vraag nodig):
- **Bladeren** loopt rond: na de laatste foto komt de eerste, en andersom. Escape en een klik op de donkere achtergrond sluiten; ← en → bladeren; vegen naar links of rechts bladert (zelfde drempel als de hero: 50 px, en meer horizontaal dan verticaal).
- **Eén foto in de lijst**: geen vorige/volgende-knoppen en geen teller.
- **Focus**: bij openen in het venster, bij sluiten terug naar de tegel van de foto die als laatste te zien was.
- **Direct laden** geldt voor de eerste 3 tegels van de lijst die op dat moment getoond wordt.
- **De hero** werkt na het uitlichten van de veeglogica precies zoals nu.
- Deze bouwstenen kennen geen shoottypes, filters of URL; dat komt in unit 3.
*Beantwoord in de chat op 2026-10-25 en hier vastgelegd.* Vul per vraag de letter in na `[Answer]:`. Past geen enkele optie, kies dan de laatste (Anders) en licht toe.
---
## Vraag 1: Overgang tussen foto's in de lightbox
- A) **Korte overvloeier** (ongeveer 0,3 s) bij openen, sluiten en bladeren; bij "beweging beperken" in het besturingssysteem geen animatie (aanbevolen)
- B) **Geen animatie**: de foto wisselt direct
- C) **Schuiven** naar links of rechts, in de richting van het bladeren
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 2: Plaats van de knoppen op een telefoon
In het ontwerp staan vorige en volgende halverwege links en rechts over de foto, en sluiten rechtsboven. Op een smal scherm liggen de knoppen dan over de foto heen.
- A) **Op telefoons een balk onderaan** (vorige · teller · volgende) en sluiten rechtsboven; **vanaf tablet** zoals het ontwerp, links en rechts naast de foto. Zo bedekken de knoppen de foto nergens en zitten ze binnen bereik van de duim (aanbevolen)
- B) **Overal zoals het ontwerp**: links en rechts halverwege, ook op telefoons
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 3: Klikken of tikken op de grote foto zelf
- A) **Niets**: alleen de knoppen, toetsen, vegen en de achtergrond doen iets. Voorkomt per ongeluk sluiten of bladeren (aanbevolen)
- B) **Volgende foto**
- C) **Sluiten**
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 4: Naar beneden vegen
- A) **Niet ondersteund**: sluiten gaat met de knop, Escape of de achtergrond (aanbevolen: eenvoudiger, geen conflict met scrollen of inzoomen)
- B) **Naar beneden vegen sluit** de lightbox, zoals in veel foto-apps
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 5: Wat een screenreader hoort bij het bladeren
- A) **Positie en bijschrift**, bijvoorbeeld "Foto 3 van 10, Newbornshoot". De alt-tekst wordt voorgelezen als de focus op de foto komt (aanbevolen)
- B) **Positie, bijschrift en alt-tekst** in één keer. Volledig, maar lang bij snel bladeren
- C) **Alleen de positie**: "Foto 3 van 10"
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 6: Naam van een tegel in het raster
Een tegel is een link die de lightbox opent. Zijn naam is de alt-tekst plus een aanwijzing.
- A) Alt-tekst + **"(groot bekijken)"**, bijvoorbeeld "Moeder met pasgeboren baby op bed (groot bekijken)" (aanbevolen)
- B) Alt-tekst + **"(vergroten)"**
- C) Alleen de alt-tekst
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 7: Als de grote foto niet laadt
- A) De kleine foto uit het raster blijft staan (die is er al), zonder melding; bladeren blijft werken (aanbevolen)
- B) De kleine foto blijft staan met een korte melding "Deze foto kon niet groot geladen worden"
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: B
## Vraag 8: Vooruit laden in de lightbox
- A) **De vorige en de volgende** grote foto (1 aan elke kant) (aanbevolen: snel bladeren, weinig extra data op een telefoon)
- B) **Twee aan elke kant**
- C) **Niets vooruit**; elke grote foto laadt pas als hij getoond wordt
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: B
## Vraag 9: Het raster bij een ander filter
- A) **Direct wisselen** zonder animatie; nieuwe tegels verschijnen meteen, ook als ze nog niet in beeld waren geweest (aanbevolen: rustig, geen verspringende fade-ins)
- B) **Kort overvloeien** van het raster bij elke wissel
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
## Vraag 10: Home en End in de lightbox
- A) **Ja**: Home springt naar de eerste foto, End naar de laatste (aanbevolen: handig en volgt het gebruikelijke patroon voor galerijen)
- B) **Nee**: alleen ← en →
- X) Anders (beschrijf hieronder na de [Answer]:-tag)
[Answer]: A
@@ -0,0 +1,10 @@
# Functional Design Plan — Unit 2: Gallery building blocks
Depth: standard. Scope from the execution plan: the rules and states of the generic `PortfolioGrid`, `Lightbox`, `FilterBar` and `useSwipe`, and the pure helpers behind them (`wrapIndex`, `swipeDirection`, `masonryRowSpan`, `neighbourIndexes`), with their testable properties (PBT-01). Questions: [gallery-blocks-fd-questions.md](gallery-blocks-fd-questions.md).
- [x] Collect and analyse the answers in `gallery-blocks-fd-questions.md`
- [x] `domain-entities.md` — `GalleryItem`, `ImageSource`, `FilterOption`, lightbox state (open index or closed), swipe points; how they relate
- [x] `business-rules.md` — grid rules (order, columns, row spans, eager count, link fallback, intent), lightbox rules (open/close, wrap, keys, swipe, counter, caption, focus return, preloading, single item, loading and error states, reduced motion), filter bar rules (options, active state, fewer than two options), swipe rules (threshold, direction), hero behaviour unchanged
- [x] `business-logic-model.md` — event flows (open from tile, browse, close, swipe) and the lightbox state machine; the pure helpers with their properties per PBT category (round-trip, invariant, idempotence, oracle, stateful)
- [x] `frontend-components.md` — component hierarchy, props and state per component, accessible names and live regions, keyboard map, test ids, recipes and tokens
- [x] Validate against requirements.md, application-design.md and the extension rules (Security Baseline, PBT)