From 18bf0311ef0c7096c2db41675d9c23b045faaf1e Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Sun, 25 Oct 2026 23:22:43 +0100 Subject: [PATCH] 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 --- .../reverse-engineering/api-documentation.md | 5 +- .../reverse-engineering/architecture.md | 4 +- .../reverse-engineering/code-structure.md | 3 +- aidlc-docs/active-features.md | 2 +- .../features/portfolio-page/aidlc-state.md | 29 +- aidlc-docs/features/portfolio-page/audit.md | 84 ++++ .../gallery-blocks/code/code-summary.md | 37 ++ .../functional-design/business-logic-model.md | 68 ++++ .../functional-design/business-rules.md | 71 ++++ .../functional-design/domain-entities.md | 66 ++++ .../functional-design/frontend-components.md | 62 +++ .../gallery-blocks-code-generation-plan.md | 63 +++ .../plans/gallery-blocks-fd-questions.md | 103 +++++ .../gallery-blocks-functional-design-plan.md | 10 + .../components/FilterBar/FilterBar.test.tsx | 104 +++++ web/src/components/FilterBar/FilterBar.tsx | 55 +++ web/src/components/Hero/useHeroSlider.ts | 35 +- web/src/components/Lightbox/Lightbox.test.tsx | 220 +++++++++++ web/src/components/Lightbox/Lightbox.tsx | 366 ++++++++++++++++++ .../PortfolioGrid/PortfolioGrid.test.tsx | 109 ++++++ .../PortfolioGrid/PortfolioGrid.tsx | 164 ++++++++ web/src/content/types.ts | 24 ++ web/src/hooks/useSwipe.test.tsx | 68 ++++ web/src/hooks/useSwipe.ts | 40 ++ web/src/lib/lightboxReducer.test.ts | 130 +++++++ web/src/lib/lightboxReducer.ts | 49 +++ web/src/lib/masonryRowSpan.test.ts | 80 ++++ web/src/lib/masonryRowSpan.ts | 22 ++ web/src/lib/neighbourIndexes.test.ts | 56 +++ web/src/lib/neighbourIndexes.ts | 24 ++ web/src/lib/swipeDirection.test.ts | 63 +++ web/src/lib/swipeDirection.ts | 21 + web/src/lib/wrapIndex.test.ts | 78 ++++ web/src/lib/wrapIndex.ts | 6 + web/src/recipes/filterControl.ts | 35 ++ web/src/test/arbitraries.ts | 61 +++ web/src/test/galleryFixtures.ts | 15 + web/src/theme.ts | 3 + 38 files changed, 2392 insertions(+), 43 deletions(-) create mode 100644 aidlc-docs/features/portfolio-page/construction/gallery-blocks/code/code-summary.md create mode 100644 aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-logic-model.md create mode 100644 aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-rules.md create mode 100644 aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/domain-entities.md create mode 100644 aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/frontend-components.md create mode 100644 aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-code-generation-plan.md create mode 100644 aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-fd-questions.md create mode 100644 aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-functional-design-plan.md create mode 100644 web/src/components/FilterBar/FilterBar.test.tsx create mode 100644 web/src/components/FilterBar/FilterBar.tsx create mode 100644 web/src/components/Lightbox/Lightbox.test.tsx create mode 100644 web/src/components/Lightbox/Lightbox.tsx create mode 100644 web/src/components/PortfolioGrid/PortfolioGrid.test.tsx create mode 100644 web/src/components/PortfolioGrid/PortfolioGrid.tsx create mode 100644 web/src/hooks/useSwipe.test.tsx create mode 100644 web/src/hooks/useSwipe.ts create mode 100644 web/src/lib/lightboxReducer.test.ts create mode 100644 web/src/lib/lightboxReducer.ts create mode 100644 web/src/lib/masonryRowSpan.test.ts create mode 100644 web/src/lib/masonryRowSpan.ts create mode 100644 web/src/lib/neighbourIndexes.test.ts create mode 100644 web/src/lib/neighbourIndexes.ts create mode 100644 web/src/lib/swipeDirection.test.ts create mode 100644 web/src/lib/swipeDirection.ts create mode 100644 web/src/lib/wrapIndex.test.ts create mode 100644 web/src/lib/wrapIndex.ts create mode 100644 web/src/recipes/filterControl.ts create mode 100644 web/src/test/galleryFixtures.ts diff --git a/aidlc-docs/_shared/reverse-engineering/api-documentation.md b/aidlc-docs/_shared/reverse-engineering/api-documentation.md index ea65e5e..35b0337 100644 --- a/aidlc-docs/_shared/reverse-engineering/api-documentation.md +++ b/aidlc-docs/_shared/reverse-engineering/api-documentation.md @@ -42,13 +42,15 @@ None. There is no back-end yet (`api/` is empty). The static design README antic - `IntroGallery({ content })`, `AboutBlock({ content })`, `Pricing({ content, packages })`, `PriceCard(...)`, `Testimonials({ content, testimonials })`, `ContactSection({ content, packages, enabled, email, pakket? })`, `InstagramGrid({ content: InstagramContent, profileUrl })` (shared, `components/InstagramGrid/`) - `ContactForm(...)`, `ContactFormGate({ enabled, email, ... })` - `PhotoDuo({ photos: [ContentImage, ContentImage], label, 'data-testid'? })` +- `PortfolioGrid({ items: GalleryItem[], eagerCount = 3, onOpen(index), onIntent?(), 'data-testid'? })`, `Lightbox({ items, index: number | null, onIndexChange, onClose, label?, finalFocusEl? })` (default export, lazy-loadable), `FilterBar({ options: FilterOption[], value, onChange, label })` - `about/AboutIntro({ content })`, `about/StorySection({ content, titleId, tone?, spacing?, children? })`, `shoots/ShootList({ shoots, packages, portfolioLive })`, `shoots/ShootBlock({ shoot, packages, reverse, priority, portfolioLive })` - `StatusPage({ title, children, actions? })`, `ErrorPage({ error, reset })` - `LinkButton(RouterLink props & { variant?: 'outline' | 'accent' | 'light' })` - `UmamiAnalytics({ hostname? })` ### Hooks -- `useHeroSlider(count)` → slider state, controls, handlers, `HeroAnnouncement` +- `useHeroSlider(count)` → slider state, controls, handlers, `HeroAnnouncement` (swipe via `useSwipe`, wrap via `wrapIndex`) +- `useSwipe({ onPrev, onNext, enabled? })` → `{ onTouchStart, onTouchEnd }` (threshold and direction from `lib/swipeDirection`) - `useScrolledPast(getThreshold)` → boolean (stable `getThreshold` required) - `useRouteFocus()` — focuses `
` after navigation - `useInView({ rootMargin, skip })` → `{ ref, inView }`; `usePageLoaded()` → boolean; `useReveal()` → `{ ref, visible }` @@ -60,6 +62,7 @@ None. There is no back-end yet (`api/` is empty). The static design README antic - `slidesToLoad(active, count): number[]` - `backToTopThreshold(viewportHeight): number` - `slideLabel`, `formatPrice`, `bookLabel`, `visiblePackages`, `visibleTestimonials`, `packageFromSearch`, `shootOptions`, `mailSubject`/`mailtoLink`, `validateField`/`validateContact`, `isLikelySpam`, `toContactPayload`, `contactFormReducer` +- Gallery (portfolio-page): `wrapIndex(index, count)`, `swipeDirection(start, end, threshold = 50)`, `masonryRowSpan({ width, height }, K = 40, gapRows = 2)`, `neighbourIndexes(index, count, radius = 2)`, `lightboxReducer(state, event)` (+ `LightboxState`, `LightboxEvent`) ### Monitoring - `monitoringFor(hostname): Monitoring | null`, `startSentry(hostname?)`, `reportError(error)` diff --git a/aidlc-docs/_shared/reverse-engineering/architecture.md b/aidlc-docs/_shared/reverse-engineering/architecture.md index 042cede..4707805 100644 --- a/aidlc-docs/_shared/reverse-engineering/architecture.md +++ b/aidlc-docs/_shared/reverse-engineering/architecture.md @@ -20,7 +20,7 @@ graph TD Outlet --> Placeholders["portfolio, contact, privacyverklaring: PageIntro"] Home --> Hero["Hero (HeroArrows, HeroPauseButton, HeroSocials, useHeroSlider)"] Home --> Sections["components/home/: IntroGallery, AboutBlock, Pricing, Testimonials, ContactSection; shared InstagramGrid"] - Sections --> Blocks["Shared blocks: PageSection, MediaText, CallToAction, RichParagraph, Eyebrow, SectionHeading, FramedImage, DeferredImage, Reveal"] + Sections --> Blocks["Shared blocks: PageSection, MediaText, CallToAction, RichParagraph, Eyebrow, SectionHeading, FramedImage, DeferredImage, Reveal; gallery: PortfolioGrid, Lightbox, FilterBar"] Sections --> Form["ContactForm + ContactFormGate (lazy), contact/"] Content["content/: siteContent, heroContent, homeContent, packages, testimonials, types"] -.-> Shell Content -.-> Home @@ -79,7 +79,7 @@ Text alternative: main.tsx starts Sentry and mounts the router; the root route r ### Shared section building blocks - **Purpose**: Reusable pieces extracted during homepage-sections; `HomeSection` was renamed to `PageSection` and `MediaText`/`Eyebrow` were extracted in over-mij-page -- **Responsibilities**: `PageSection` (section frame: `aria-labelledby`, tone `paper`/`alt`, width `default`/`narrow`/`full`, spacing `default`/`tight`/`flushTop`, anchor offset), `MediaText` (framed photo next to a text column, design `.about`), `Eyebrow` (accent label, optionally a heading), `SectionHeading` (eyebrow + h2 + lead, align start/center, compact spacing), `FramedImage` (photo with a coloured offset block, sand by default, design `.about__media`), `CallToAction` (closing block: h2, lead, action; added in soorten-fotoshoots-page), `RichParagraph` (paragraph with inline links), `DeferredImage` (loads after page load and near the viewport, reserves space), `Reveal` (fade-in on scroll, content always in the DOM, reduced motion respected) +- **Responsibilities**: `PageSection` (section frame: `aria-labelledby`, tone `paper`/`alt`, width `default`/`narrow`/`full`, spacing `default`/`tight`/`flushTop`, anchor offset), `MediaText` (framed photo next to a text column, design `.about`), `Eyebrow` (accent label, optionally a heading), `SectionHeading` (eyebrow + h2 + lead, align start/center, compact spacing), `FramedImage` (photo with a coloured offset block, sand by default, design `.about__media`), `CallToAction` (closing block: h2, lead, action; added in soorten-fotoshoots-page), `RichParagraph` (paragraph with inline links), `DeferredImage` (loads after page load and near the viewport, reserves space), `Reveal` (fade-in on scroll, content always in the DOM, reduced motion respected); gallery blocks from portfolio-page: `PortfolioGrid` (CSS-only masonry in reading order, first 3 photos eager), `Lightbox` (Chakra `Dialog`, wrap-around browsing, keys, swipe, preloading, load-error note), `FilterBar` (toggle buttons, `filterControl` recipe) - **Type**: Application (shared UI) ### components/PageIntro/, StatusPage/ diff --git a/aidlc-docs/_shared/reverse-engineering/code-structure.md b/aidlc-docs/_shared/reverse-engineering/code-structure.md index 02ce72a..f51c267 100644 --- a/aidlc-docs/_shared/reverse-engineering/code-structure.md +++ b/aidlc-docs/_shared/reverse-engineering/code-structure.md @@ -85,7 +85,8 @@ Candidates for modification are marked with ★ for the over-mij-page feature. - ★ `web/src/content/types.ts` — content interfaces (API shape) - ★ `web/src/content/*.ts` — static content (`siteContent`, `heroContent`, `homeContent` (exports `introPhotos`), `instagramContent`, `packages`, `testimonials`, `socialPlatforms`) - `web/src/contact/*` — contact form types and placeholder submit -- `web/src/hooks/*` — `useRouteFocus`, `useScrolledPast`, `useInView`, `usePageLoaded`, `useReveal` +- `web/src/hooks/*` — `useRouteFocus`, `useScrolledPast`, `useInView`, `usePageLoaded`, `useReveal`, `useSwipe` (shared by the hero and the lightbox) +- `web/src/components/{PortfolioGrid,Lightbox,FilterBar}/` — gallery building blocks (portfolio-page unit 2): masonry grid in reading order (CSS only), lightbox on Chakra `Dialog` (lazy-loadable default export), single-choice toggle buttons; generic over `GalleryItem` / `FilterOption` - `web/src/lib/*.ts` — pure helpers with tests - `web/src/monitoring/*` — Sentry/Umami config and loader - `web/src/navigation.ts` — `RoutePath`, `mainNav`, `footerNav` diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index f39cc5a..47fd624 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -8,4 +8,4 @@ | Feature | over-mij-page | ✅ Complete | feature/over-mij-page | web/src/routes/over-mij.tsx, web/src/content, possibly shared components (PageIntro, FramedImage, SectionHeading) and web/src/seo.ts | 2026-10-22 | | Feature | soorten-fotoshoots-page | ✅ Complete | feature/soorten-fotoshoots-page | web/src/routes/soorten-fotoshoots.tsx, new web/src/content/shootTypes.ts, new web/src/assets/shoots/, new shared CallToAction, MediaText (reverse prop), Pricing (id="prijzen" only), siteContent (service area), own entries in sitePages.ts / lighthouserc.cjs, JSON-LD via the shared webPage() helper in seo.ts | 2026-10-24 | | Feature | contact-page | ✅ Complete | feature/contact-page | web/src/routes/contact.tsx, web/src/content, possibly ContactForm/ContactSection, PageIntro, MediaText/FramedImage, web/src/seo.ts, sitePages/sitemap | 2026-10-24 | -| Feature | portfolio-page | 🔵 Inception | feature/portfolio-page (based on master after over-mij merge; worktree ../AndreaSlopFotografie-portfolio) | web/src/routes/portfolio.tsx, web/src/content, new PortfolioGrid + Lightbox, InstagramGrid (moved to shared), own entries in sitePages.ts / lighthouserc.cjs, ImageGallery JSON-LD via the shared webPage() helper | 2026-10-24 | +| Feature | portfolio-page | 🟢 Construction | feature/portfolio-page (based on master after over-mij merge; worktree ../AndreaSlopFotografie-portfolio) | web/src/routes/portfolio.tsx, web/src/content, new PortfolioGrid + Lightbox, InstagramGrid (moved to shared), own entries in sitePages.ts / lighthouserc.cjs, ImageGallery JSON-LD via the shared webPage() helper | 2026-10-24 | diff --git a/aidlc-docs/features/portfolio-page/aidlc-state.md b/aidlc-docs/features/portfolio-page/aidlc-state.md index b290854..c07d3ee 100644 --- a/aidlc-docs/features/portfolio-page/aidlc-state.md +++ b/aidlc-docs/features/portfolio-page/aidlc-state.md @@ -5,8 +5,8 @@ - **Feature Slug**: portfolio-page - **Project Type**: Brownfield - **Start Date**: 2026-10-24T19:30:00Z -- **Current Stage**: CONSTRUCTION - Code Generation (Unit 1 Shared Instagram block, generated, awaiting approval) -- **Branch**: feature/portfolio-page (fast-forwarded onto master 11a5224 after the over-mij-page merge, PR #7) +- **Current Stage**: CONSTRUCTION - Code Generation (Unit 2 Gallery building blocks, generated, awaiting approval) +- **Branch**: feature/portfolio-page (rebased onto master 1bf28cb after contact-page PR #10) - **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-portfolio ## Workspace State @@ -45,18 +45,27 @@ - **Delivery**: branch feature/portfolio-page, commits per unit, full `pnpm check` (incl. Lighthouse) per unit, one PR at the end ## Parallel Work Agreements -Parallel features, each in its own worktree (originally stacked on feature/over-mij-page, merged to master as 11a5224): contact-page (session andreaslopfotografie-91), soorten-fotoshoots-page (session andreaslopfotografie-3f). Over-mij session ("Over mij pagina") notifies when merged. +Parallel features, each in its own worktree (originally stacked on feature/over-mij-page, merged to master as 11a5224): contact-page (✅ merged as 8b70f23, PR #9; session ended. Was: next: siteContent.socials reordered to Instagram, Facebook; new shared ContactDetails, PrivacyNote, ContactPanel; unit 2 on origin/feature/contact-page 26a8bd9, not on master yet. After the next rebase: `SocialLink.label?` and `SiteContent.contactForm.replyTime` — SiteContent fixtures in tests need `replyTime`), soorten-fotoshoots-page (✅ merged as a58bc1c; session ended); session names change on restart, check ListAgents. Over-mij session ("Over mij pagina") notifies when merged. - No full RE refresh; each feature only updates the RE lines about its own route/components - Hot files: own entry only in sitePages.ts, lighthouserc.cjs, active-features.md +- **Test environment (single, last deploy wins)**: send "claim test" with the reason (who reviews what) before a `deploy_test` dispatch, and "test free" once that review is done. A merge to master also deploys to test, so check that test is not claimed before merging - **Lighthouse / `pnpm check` (port 4173)**: send "claim 4173" to the other two sessions before a run and "4173 free" after; avoid CPU-heavy work (full vitest with coverage, build) while another session runs Lighthouse - **Peer commits to cherry-pick at the start of unit 3**: - - soorten-fotoshoots: `eb23536` "Adds the shoot types and their photos" (content/types.ts ShootTypeId/FrameColor/ShootType, content/shootTypes.ts + test, assets/shoots/*.jpg 960×1200, theme.ts frame.* tokens, test/arbitraries.ts shootTypeId/shootType/uniqueShootTypes). Run `pnpm typegen` afterwards (theme change). Their Gezin photo is F41A7138 (also portfolio photo 9; overlap accepted by their user; different derivatives) - - contact-page: `webPage()` — hash pending + - soorten-fotoshoots: **on master since a58bc1c (PR #8) — no cherry-pick needed**. Was `eb23536` "Adds the shoot types and their photos" (content/types.ts ShootTypeId/FrameColor/ShootType, content/shootTypes.ts + test, assets/shoots/*.jpg 960×1200, theme.ts frame.* tokens, test/arbitraries.ts shootTypeId/shootType/uniqueShootTypes). Run `pnpm typegen` afterwards (theme change). Their Gezin photo is F41A7138 (also portfolio photo 9; overlap accepted by their user; different derivatives) + - If soorten-fotoshoots PR #8 (or contact's PR) is merged to master before unit 3 starts: rebase onto master instead of cherry-picking that commit + - contact-page: **`webPage()` on master since a58bc1c (as 3c7d00e) — no cherry-pick needed**; 790495d no longer exists after contact's rebase - seo.ts: contact-page builds generic `webPage(type, path, extra)` (aboutPage refactored onto it) in a separate commit; portfolio cherry-picks it and uses it for ImageGallery/CollectionPage JSON-LD. No own xxxPage() helper. Proposed signature: `webPage(type: WebPageType, path: RoutePath, extra: Record = {})` with `WebPageType = 'WebPage' | 'AboutPage' | 'ContactPage' | 'ImageGallery' | 'CollectionPage'` (add a type to the union in an own one-line commit if needed) → `{ @context, @type: type, @id + url: canonicalUrl(path), name/description from sitePages[path], inLanguage: 'nl-NL', ...extra }` (extra last). Commit hash follows once contact's user approves; design against this signature until then - Claims: portfolio — PortfolioGrid, Lightbox, InstagramGrid moved from components/home/ to shared; contact — ContactForm generalisation, contact-details block; soorten-fotoshoots — content/shootTypes.ts, CallToAction band, optional MediaText `reverse` prop - PageIntro is used by all; announce before changing it - Photos: soorten-fotoshoots owns the shoot photos (newborn, zwangerschap, loveshoot, portret, gezin) in `web/src/assets/shoots/`, delivered as an assets-only commit; portfolio cherry-picks it if the user picks any of them. Portfolio-only photos go in `web/src/assets/portfolio/`. Photos already in `web/src/assets/home/` (intro-2, intro-4) are imported from there. Send the final photo list to soorten-fotoshoots after Requirements Analysis. **Update**: user chose the 10 live photos (Q1 A), no overlap with the shoot photos; list sent -- Shoot types: portfolio reuses soorten-fotoshoots' list for filters and captions. Proposed shape in `content/types.ts`: `ShootTypeId = 'newborn' | 'zwangerschap' | 'gezin' | 'loveshoot' | 'portret'`; `ShootType { id; name ('Newborn', …, 'Portretten'); shootLabel ('Newbornshoot', …, 'Portretshoot'); paragraphs; image; packageId? }`; order newborn, zwangerschap, gezin, loveshoot, portret. Delivered as a separate commit (types + shootTypes.ts + assets/shoots/) at the start of their unit 1; hash follows. Portfolio photo data references `ShootTypeId` only. `?shoot=` link from their page: confirmed by their user; shown only once `/portfolio` is `indexed: true` (no message needed at merge). Portfolio route: `validateSearch` returns typed `{ shoot?: ShootTypeId }` so their `search: { shoot }` type-checks. Types without portfolio photos fall back to "Alles"; portfolio exports a pure helper (working name `shootTypesWithPhotos`) in unit 3 and sends its name. ShootType gains `photosLabel` and `frameColor` (theirs, additive). RichParagraph moves to `components/` (theirs) +- Shoot types: portfolio reuses soorten-fotoshoots' list for filters and captions. Proposed shape in `content/types.ts`: `ShootTypeId = 'newborn' | 'zwangerschap' | 'gezin' | 'loveshoot' | 'portret'`; `ShootType { id; name ('Newborn', …, 'Portretten'); shootLabel ('Newbornshoot', …, 'Portretshoot'); paragraphs; image; packageId? }`; order newborn, zwangerschap, gezin, loveshoot, portret. Delivered as a separate commit (types + shootTypes.ts + assets/shoots/) at the start of their unit 1; hash follows. Portfolio photo data references `ShootTypeId` only. `?shoot=` link from their page: confirmed by their user; shown only once `/portfolio` is `indexed: true` (no message needed at merge). Portfolio route: `validateSearch` returns typed `{ shoot?: ShootTypeId }` so their `search: { shoot }` type-checks. Types without portfolio photos fall back to "Alles"; portfolio exports a pure helper (working name `shootTypesWithPhotos`) in unit 3 and sends its name. ShootType gains `photosLabel` and `frameColor` (theirs, additive). RichParagraph moves to `components/` (theirs). Their shoot blocks render "Bekijk meer {photosLabel}" → `/portfolio?shoot=` once `sitePages['/portfolio'].indexed === true`; their app.test.tsx expects 5 portfolio links when indexed, else 0 (check after rebase). Their session has ended: wiring the helper into their ShootList/ShootBlock (`portfolioLive && hasPhotos`) is now a follow-up for this feature (unit 3 or a small follow-up commit). `ShootType.detailImage` added (optional, theirs) + +## Known Risks +- **Lighthouse mobile performance ≈ 0.9 threshold** (from soorten-fotoshoots, 2026-10-25): pages whose LCP is an image land at LCP ≈ 3.22 s ≈ score 0.895 in the simulated mobile run (over-mij and soorten-fotoshoots); fewer image bytes do not help, the cost is main bundle + route chunk. Relevant for NFR-PF-05 in unit 3: keep the route chunk small (Lightbox lazy, Q7), measure early, and align with soorten-fotoshoots' user decision on the budget before changing `lighthouserc*.cjs` +- **Soorten-fotoshoots' rule (their unit 2 commit, decided by their user)**: `lighthouserc.cjs` exports `photoPagePaths = ['/over-mij', '/soorten-fotoshoots']` with `photoPageMobilePerformance = 0.85` (mobile only); assertMatrix order home (0.8) → photo pages (0.85) → other indexed → noindex → 404; `lighthouserc.desktop.cjs` maps every entry to 0.9. Suggested for portfolio: add `/portfolio` to `photoPagePaths` once indexed. **Open for this feature**: that lowers NFR-PF-05 (≥ 0.9 mobile, approved) for `/portfolio` to 0.85 — needs this user's decision; decide in unit 3 after measuring (if `/portfolio` reaches 0.9 it stays in the default budget) + +- **Accent button contrast** (from contact-page, 2026-10-25): `linkButton` variant `accent` (white on accent #7f8b76) is 3.58:1 < 4.5:1; Lighthouse only flags it when visible on first load (Reveal hides it elsewhere). Decided by the user, **on master since 8b70f23**: accent button bg → `accent.deep` (#5f6a58), hover → new token `accent.deeper` (#475042); changes theme.ts and recipes/linkButton.ts — keep both on a rebase. Portfolio does not plan an accent button; the filter bar uses `accent.deep` for its active state (≥ 4.5:1) — verify contrast of every new colour pair in unit 2 anyway +- **Homepage mobile performance** sits at 0.79–0.80 against its 0.8 threshold on current builds (contact, 3 runs). A failing `/` in a portfolio Lighthouse run is probably this, not a portfolio regression; compare against master before acting ## Stage Progress @@ -70,11 +79,11 @@ Parallel features, each in its own worktree (originally stacked on feature/over- - [ ] Units Generation - SKIP ### 🟢 CONSTRUCTION PHASE -- [ ] Functional Design - EXECUTE (units 2 and 3) / SKIP (unit 1) +- [~] Functional Design - EXECUTE (units 2 and 3) / SKIP (unit 1) — Unit 2 ✅ - [ ] NFR Requirements - SKIP - [ ] NFR Design - SKIP - [ ] Infrastructure Design - SKIP -- [~] Code Generation - EXECUTE (per unit) — Unit 1 Shared Instagram block: generated, awaiting approval +- [~] Code Generation - EXECUTE (per unit) — Unit 1 Shared Instagram block ✅ (e013f14 after rebases); Unit 2 Gallery building blocks: generated, awaiting approval - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE @@ -82,5 +91,5 @@ Parallel features, each in its own worktree (originally stacked on feature/over- ## Current Status - **Lifecycle Phase**: CONSTRUCTION -- **Current Stage**: Code Generation — Unit 1 Shared Instagram block (awaiting approval) -- **Next Stage**: Functional Design — Unit 2 Gallery building blocks +- **Current Stage**: Functional Design — Unit 2 Gallery building blocks +- **Next Stage**: Code Generation — Unit 2 diff --git a/aidlc-docs/features/portfolio-page/audit.md b/aidlc-docs/features/portfolio-page/audit.md index 3cb6a37..e455b08 100644 --- a/aidlc-docs/features/portfolio-page/audit.md +++ b/aidlc-docs/features/portfolio-page/audit.md @@ -184,3 +184,87 @@ Feature "portfolio-page" may affect components also touched by active feature "o **Context**: CONSTRUCTION - Code Generation Unit 1 (generated, awaiting approval) --- + +## Code Generation — Unit 1 — Approval + +**Timestamp**: 2026-10-25T07:40:00Z + +**User Input**: "Ga verder" + +**AI Response**: "Unit 1 approved (commits 4de0885, 996cc32). active-features.md status → 🟢 Construction. Recorded contact-page commit 790495d (webPage) for unit 3. Started Functional Design for unit 2 (gallery-blocks): created construction/plans/gallery-blocks-functional-design-plan.md and gallery-blocks-fd-questions.md (10 questions: lightbox transition, phone button layout, tap on image, swipe down, announcement, tile name, large image failure, preload count, grid on filter change, Home/End)." + +**Context**: CONSTRUCTION - Functional Design Unit 2 (awaiting answers) + +--- + +## Branch Update — soorten-fotoshoots-page merged + +**Timestamp**: 2026-10-25T10:30:00Z + +**User Input**: (none — notification from the soorten-fotoshoots session: PR #8 merged as a58bc1c) + +**AI Response**: "Stashed the uncommitted docs under a named stash, rebased feature/portfolio-page (2 commits) onto origin/master a58bc1c. Conflicts: aidlc-docs/active-features.md (kept the soorten ✅ row and the portfolio row) and _shared/reverse-engineering/architecture.md (merged the shared InstagramGrid line with soorten's CallToAction/RichParagraph blocks). Popped and dropped the own stash by name (contact's stash left untouched). New hashes 236123d (plans), cce11a8 (unit 1). Verified: tsc clean, vitest 65 files / 326 tests passed (Lighthouse not run). shootTypes.ts now comes via master; the eb23536 cherry-pick is no longer needed. Soorten's session ended, so wiring the 'types with photos' helper into their ShootList/ShootBlock becomes a follow-up of this feature." + +**Context**: CONSTRUCTION - Functional Design Unit 2 (awaiting answers) + +--- + +## Branch Update — contact-page merged + +**Timestamp**: 2026-10-25T19:00:00Z + +**User Input**: (none — notification from the contact-page session: PR #9 merged as 8b70f23, test free) + +**AI Response**: "Stashed docs under a named stash, rebased feature/portfolio-page onto origin/master 8b70f23 (new hashes ad567bb plans, ec48bd7 unit 1). Conflicts only in aidlc-docs/active-features.md (kept all master rows incl. contact-page as on master, portfolio row with status 🟢 Construction). Popped and dropped the own stash by name; stash list empty. Verified: tsc clean, vitest 71 files / 368 tests passed. Parallel sessions (soorten-fotoshoots, contact) have both ended; portfolio is the only active feature." + +**Context**: CONSTRUCTION - Functional Design Unit 2 (awaiting answers) + +--- + +## Branch Update — contact-page PR #10 merged (docs) + +**Timestamp**: 2026-10-25T19:20:00Z + +**User Input**: (none — notification from the contact-page session: PR #10 merged as 1bf28cb, docs only) + +**AI Response**: "Rebased onto origin/master 1bf28cb. Mistake and fix: when resolving the active-features.md conflict I removed the conflict markers and kept both sides, so the old 'contact-page 🟢 Construction' row stayed next to master's '✅ Complete' row and was committed in the rebased planning commit. Cause: blindly keeping both sides of a hunk where one side replaced a line. Fixed in history (local, unpushed) with a fixup commit + autosquash; the stash conflict was then resolved from the committed file with only the portfolio status changed. Verified the restored state, audit and FD files byte-equal to the stash before dropping it by name. New hashes b35b1c2 (plans), e013f14 (unit 1); web/ unchanged by this rebase." + +**Context**: CONSTRUCTION - Functional Design Unit 2 (awaiting answers) + +--- + +## Functional Design — Unit 2 — Answers and Artifacts + +**Timestamp**: 2026-10-25T19:40:00Z + +**User Input**: "Stuur de vragen hier" — then answered in chat: Q1 Korte overvloeier, Q2 Balk onderaan op telefoon, Q3 Niets, Q4 Nee, Q5 Positie en bijschrift, Q6 Alt + (groot bekijken), Q7 Kleine foto met melding, Q8 2 aan elke kant, Q9 Direct wisselen, Q10 Ja. + +**AI Response**: "Asked the 10 FD questions in chat (user request) and recorded the answers in gallery-blocks-fd-questions.md (A A A A A A B B A A). No ambiguities. Generated construction/gallery-blocks/functional-design/{domain-entities, business-rules, business-logic-model, frontend-components}.md: masonry spans K=40 rows per column width + 2 gap rows (CSS only), eager first 3, tile = link with modifier-click passthrough, lightbox rules (wrap, Home/End, swipe, phone bottom bar, crossfade 0.3 s, thumb while loading, visible error message, preload 2 each side, close on list change), filter bar rules, swipe rules, hero refactor. Added a pure lightboxReducer (not named in Application Design) so the open/close/browse state can be tested statefully (PBT-06). Properties per helper documented for PBT-01." + +**Context**: CONSTRUCTION - Functional Design Unit 2 (awaiting approval) + +--- + +## Functional Design — Unit 2 — Approval + +**Timestamp**: 2026-10-25T19:50:00Z + +**User Input**: "Ga verder" + +**AI Response**: "Functional design of unit 2 approved. Created construction/plans/gallery-blocks-code-generation-plan.md (20 steps: types, five pure helpers with example and property-based tests incl. a stateful reducer test, arbitraries, useSwipe + hero refactor, theme token and filterControl recipe, FilterBar, PortfolioGrid, Lightbox, fixtures, pnpm check, own RE lines, summary, one local commit)." + +**Context**: CONSTRUCTION - Code Generation Unit 2 (plan awaiting approval) + +--- + +## Code Generation — Unit 2 — Plan Approval and Generation + +**Timestamp**: 2026-10-25T21:30:00Z + +**User Input**: "Approve plan" + +**AI Response**: "Executed gallery-blocks-code-generation-plan.md steps 1–20: types, five pure helpers with example and property-based tests (incl. stateful lightboxReducer test), arbitraries, useSwipe + hero refactor (hero tests unchanged), theme token swap + filterControl recipe, FilterBar, PortfolioGrid (CSS-only masonry, verified generated CSS), Lightbox (Chakra Dialog), fixtures. ESLint set-state-in-effect errors fixed at the cause. jsdom limits handled explicitly in tests (focus trap needs layout boxes; exit needs animation events). Claimed/freed port 4173 with the remaining idle sessions. pnpm check: tests 80 files / 426 passed, desktop Lighthouse green; mobile Lighthouse failed on / (0.75, rerun 0.79 vs 0.8) and /contact (0.88 vs 0.9). Root cause checked: master on the same machine gives / 0.78 and /contact 0.88, main bundle grows 0.12 kB gzip — pre-existing budget issue, not a regression; surfaced to the user. Own RE lines updated; code summary written; committed locally (no push)." + +**Context**: CONSTRUCTION - Code Generation Unit 2 (generated, awaiting approval) + +--- diff --git a/aidlc-docs/features/portfolio-page/construction/gallery-blocks/code/code-summary.md b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/code/code-summary.md new file mode 100644 index 0000000..b68e9c2 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/code/code-summary.md @@ -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). diff --git a/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-logic-model.md b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-logic-model.md new file mode 100644 index 0000000..1ac91d8 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-logic-model.md @@ -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). diff --git a/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-rules.md b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-rules.md new file mode 100644 index 0000000..b892fd9 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/business-rules.md @@ -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 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. diff --git a/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/domain-entities.md b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/domain-entities.md new file mode 100644 index 0000000..f5f7d9e --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/domain-entities.md @@ -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) | diff --git a/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/frontend-components.md b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/frontend-components.md new file mode 100644 index 0000000..7b03558 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/gallery-blocks/functional-design/frontend-components.md @@ -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` | diff --git a/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-code-generation-plan.md b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-code-generation-plan.md new file mode 100644 index 0000000..33a08d5 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-code-generation-plan.md @@ -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 | diff --git a/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-fd-questions.md b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-fd-questions.md new file mode 100644 index 0000000..564fb18 --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-fd-questions.md @@ -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 diff --git a/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-functional-design-plan.md b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-functional-design-plan.md new file mode 100644 index 0000000..d880bcb --- /dev/null +++ b/aidlc-docs/features/portfolio-page/construction/plans/gallery-blocks-functional-design-plan.md @@ -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) diff --git a/web/src/components/FilterBar/FilterBar.test.tsx b/web/src/components/FilterBar/FilterBar.test.tsx new file mode 100644 index 0000000..7d79a0d --- /dev/null +++ b/web/src/components/FilterBar/FilterBar.test.tsx @@ -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( + {}} + 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( + , + ); + 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( + , + ); + 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( + {}} + label={LABEL} + />, + ); + expect(screen.queryByTestId('filter-bar')).not.toBeInTheDocument(); + }); + + it('presses no button for an unknown value', async () => { + await renderWithProviders( + {}} + label={LABEL} + />, + ); + expect(screen.queryAllByRole('button', { pressed: true })).toHaveLength( + 0, + ); + }); +}); diff --git a/web/src/components/FilterBar/FilterBar.tsx b/web/src/components/FilterBar/FilterBar.tsx new file mode 100644 index 0000000..9f2a5a3 --- /dev/null +++ b/web/src/components/FilterBar/FilterBar.tsx @@ -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 ( + + {options.map((option) => { + const pressed = option.id === value; + return ( + { + if (!pressed) onChange(option.id); + }} + > + {option.label} + + ); + })} + + ); +} diff --git a/web/src/components/Hero/useHeroSlider.ts b/web/src/components/Hero/useHeroSlider.ts index bac7f6f..f3e3941 100644 --- a/web/src/components/Hero/useHeroSlider.ts +++ b/web/src/components/Hero/useHeroSlider.ts @@ -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) => { - const touch = event.touches[0]; - touchStart.current = { x: touch.clientX, y: touch.clientY }; - }, - onTouchEnd: (event: React.TouchEvent) => { - 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, }, }; } diff --git a/web/src/components/Lightbox/Lightbox.test.tsx b/web/src/components/Lightbox/Lightbox.test.tsx new file mode 100644 index 0000000..a471605 --- /dev/null +++ b/web/src/components/Lightbox/Lightbox.test.tsx @@ -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(start); + return ( + { + setIndex(null); + onClose(); + }} + /> + ); +} + +async function openAt(start = 0, items?: GalleryItem[], onClose?: () => void) { + const result = await renderWithProviders( + , + ); + 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(); + 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(); + }); +}); diff --git a/web/src/components/Lightbox/Lightbox.tsx b/web/src/components/Lightbox/Lightbox.tsx new file mode 100644 index 0000000..13ddae6 --- /dev/null +++ b/web/src/components/Lightbox/Lightbox.tsx @@ -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(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) => { + if (!browsable) return; + const target: Record = { + 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) => { + if (event.target === event.currentTarget) onClose(); + }; + + return ( + { + if (!details.open) onClose(); + }} + initialFocusEl={() => closeButton.current} + finalFocusEl={finalFocusEl} + lazyMount + unmountOnExit + > + + + + {item && ( + + {label} + + {/* Keyed per photo: a new photo starts loading + from scratch */} + + + + + + + + + {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. + + show(current - 1)} + position={{ md: 'absolute' }} + left={{ md: 4 }} + top={{ md: '50%' }} + transform={{ md: 'translateY(-50%)' }} + > + + + + {current + 1} / {count} + + show(current + 1)} + position={{ md: 'absolute' }} + right={{ md: 4 }} + top={{ md: '50%' }} + transform={{ md: 'translateY(-50%)' }} + > + + + + )} + + + {announcement} + + + )} + + + + ); +} + +type PhotoProps = { + item: GalleryItem; + swipe: ReturnType; + onBackground: (event: MouseEvent) => 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('loading'); + const onLoad = () => setLoad('loaded'); + const onError = () => setLoad('failed'); + const caption = + load === 'failed' + ? 'Deze foto kon niet groot geladen worden' + : item.caption; + + return ( + + + + {load !== 'failed' && ( + + )} + + {caption && ( + + {caption} + + )} + + ); +} + +type ControlButtonProps = React.ComponentProps; + +// 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 ( + + ); +} diff --git a/web/src/components/PortfolioGrid/PortfolioGrid.test.tsx b/web/src/components/PortfolioGrid/PortfolioGrid.test.tsx new file mode 100644 index 0000000..25dcc9d --- /dev/null +++ b/web/src/components/PortfolioGrid/PortfolioGrid.test.tsx @@ -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( + {}} />, + ); + 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( + {}} + />, + ); + 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( + , + ); + 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( + , + ); + 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( + {}} + 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( + {}} />, + ); + expect(screen.getByTestId('portfolio-grid')).toBeEmptyDOMElement(); + }); +}); diff --git a/web/src/components/PortfolioGrid/PortfolioGrid.tsx b/web/src/components/PortfolioGrid/PortfolioGrid.tsx new file mode 100644 index 0000000..d2ccb28 --- /dev/null +++ b/web/src/components/PortfolioGrid/PortfolioGrid.tsx @@ -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, + 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 ( + + + + {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 ( + + + handleClick(event, index) + } + onPointerEnter={reportIntent} + onFocus={reportIntent} + > + {index < eagerCount ? ( + {item.thumb.alt} + ) : ( + + )} + {/* The alt names the photo; this says what + the link does */}{' '} + + (groot bekijken) + + + + ); + })} + + + + ); +} diff --git a/web/src/content/types.ts b/web/src/content/types.ts index 648b246..6a1f43c 100644 --- a/web/src/content/types.ts +++ b/web/src/content/types.ts @@ -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 { diff --git a/web/src/hooks/useSwipe.test.tsx b/web/src/hooks/useSwipe.test.tsx new file mode 100644 index 0000000..fcd4373 --- /dev/null +++ b/web/src/hooks/useSwipe.test.tsx @@ -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
; +} + +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(); + 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(); + }); +}); diff --git a/web/src/hooks/useSwipe.ts b/web/src/hooks/useSwipe.ts new file mode 100644 index 0000000..da4f86a --- /dev/null +++ b/web/src/hooks/useSwipe.ts @@ -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(null); + + return { + onTouchStart: (event: TouchEvent) => { + const touch = event.touches[0]; + start.current = { x: touch.clientX, y: touch.clientY }; + }, + onTouchEnd: (event: TouchEvent) => { + 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(); + }, + }; +} diff --git a/web/src/lib/lightboxReducer.test.ts b/web/src/lib/lightboxReducer.test.ts new file mode 100644 index 0000000..7a0913c --- /dev/null +++ b/web/src/lib/lightboxReducer.test.ts @@ -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); + } + } + }, + ), + ); + }); +}); diff --git a/web/src/lib/lightboxReducer.ts b/web/src/lib/lightboxReducer.ts new file mode 100644 index 0000000..484d5e3 --- /dev/null +++ b/web/src/lib/lightboxReducer.ts @@ -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; + } +} diff --git a/web/src/lib/masonryRowSpan.test.ts b/web/src/lib/masonryRowSpan.test.ts new file mode 100644 index 0000000..11d9294 --- /dev/null +++ b/web/src/lib/masonryRowSpan.test.ts @@ -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); + } + }), + ); + }); +}); diff --git a/web/src/lib/masonryRowSpan.ts b/web/src/lib/masonryRowSpan.ts new file mode 100644 index 0000000..db36410 --- /dev/null +++ b/web/src/lib/masonryRowSpan.ts @@ -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; +} diff --git a/web/src/lib/neighbourIndexes.test.ts b/web/src/lib/neighbourIndexes.test.ts new file mode 100644 index 0000000..ba0cb89 --- /dev/null +++ b/web/src/lib/neighbourIndexes.test.ts @@ -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(); + 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, + ); + }), + ); + }); +}); diff --git a/web/src/lib/neighbourIndexes.ts b/web/src/lib/neighbourIndexes.ts new file mode 100644 index 0000000..e01907b --- /dev/null +++ b/web/src/lib/neighbourIndexes.ts @@ -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; +} diff --git a/web/src/lib/swipeDirection.test.ts b/web/src/lib/swipeDirection.test.ts new file mode 100644 index 0000000..20e4545 --- /dev/null +++ b/web/src/lib/swipeDirection.test.ts @@ -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); + }), + ); + }); +}); diff --git a/web/src/lib/swipeDirection.ts b/web/src/lib/swipeDirection.ts new file mode 100644 index 0000000..e0d5b69 --- /dev/null +++ b/web/src/lib/swipeDirection.ts @@ -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'; +} diff --git a/web/src/lib/wrapIndex.test.ts b/web/src/lib/wrapIndex.test.ts new file mode 100644 index 0000000..430ae18 --- /dev/null +++ b/web/src/lib/wrapIndex.test.ts @@ -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); + }), + ); + }); +}); diff --git a/web/src/lib/wrapIndex.ts b/web/src/lib/wrapIndex.ts new file mode 100644 index 0000000..9ee9bc2 --- /dev/null +++ b/web/src/lib/wrapIndex.ts @@ -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; +} diff --git a/web/src/recipes/filterControl.ts b/web/src/recipes/filterControl.ts new file mode 100644 index 0000000..93440a5 --- /dev/null +++ b/web/src/recipes/filterControl.ts @@ -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; diff --git a/web/src/test/arbitraries.ts b/web/src/test/arbitraries.ts index f770a86..f1770ad 100644 --- a/web/src/test/arbitraries.ts +++ b/web/src/test/arbitraries.ts @@ -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 = 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 = 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 = 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 = 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 }), + }), +); diff --git a/web/src/test/galleryFixtures.ts b/web/src/test/galleryFixtures.ts new file mode 100644 index 0000000..10dafa5 --- /dev/null +++ b/web/src/test/galleryFixtures.ts @@ -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, +})); diff --git a/web/src/theme.ts b/web/src/theme.ts index 6fd81f0..6b02b10 100644 --- a/web/src/theme.ts +++ b/web/src/theme.ts @@ -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, }, }, });