diff --git a/.ai/layout-conventions.md b/.ai/layout-conventions.md index 514f995..a20512a 100644 --- a/.ai/layout-conventions.md +++ b/.ai/layout-conventions.md @@ -13,7 +13,7 @@ Used by every page except Shell (see exception below): - If a page needs more blocks than the template currently has letters for, add a new letter/color rather than cycling back to `A` — never reuse a color, since that would visually suggest two different blocks are "the same element." A new color's stroke is always its fill at 25% darker (multiply each RGB channel by 0.75, round, convert back to hex), kept in the same style: medium-high saturation, similar lightness to the existing set. - For two sections that sit side-by-side in one row (e.g. Contact's Photo + Contact form), switch that page's diagram to `columns 2`, give full-width blocks a `:2` span, and place the side-by-side pair as plain unspanned nodes next to each other in the code (no composite container needed) — small manual width tweaks to line them up are fine, it only needs to look "good enough." -Current letter → color template (extend with a new letter using the same formula if an 8th block is ever needed): +Current letter → color template (letters A to J; extend with a new letter using the same formula if an 11th block is ever needed): ``` style A fill:#e76f51,stroke:#ad533d,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px @@ -23,6 +23,9 @@ style D fill:#264653,stroke:#1d353e,color:#fff,font-size:16px,width:400px,height style E fill:#e9c46a,stroke:#af9350,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px style F fill:#b56576,stroke:#884c59,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px style G fill:#6d7fcc,stroke:#525f99,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px +style H fill:#9b6bb5,stroke:#745088,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px +style I fill:#4cc3e0,stroke:#3992a8,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px +style J fill:#8cb83f,stroke:#698a2f,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px ``` ## Exception — Shell diff --git a/LAYOUT.md b/LAYOUT.md index 822e197..0ee15b4 100644 --- a/LAYOUT.md +++ b/LAYOUT.md @@ -88,6 +88,34 @@ columns 1 style G fill:#6d7fcc,stroke:#525f99,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px ``` +## Shoot page +```mermaid +block-beta +columns 1 + A["Intro"] + B["Story 1"] + C["Story 2"] + D["Story 3"] + E["Story 4"] + F["Process timeline"] + G["Photos"] + H["FAQ"] + I["Package"] + J["Book"] + + style A fill:#e76f51,stroke:#ad533d,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style B fill:#f4a261,stroke:#b77a49,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style C fill:#2a9d8f,stroke:#20766b,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style D fill:#264653,stroke:#1d353e,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style E fill:#e9c46a,stroke:#af9350,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style F fill:#b56576,stroke:#884c59,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style G fill:#6d7fcc,stroke:#525f99,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style H fill:#9b6bb5,stroke:#745088,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style I fill:#4cc3e0,stroke:#3992a8,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px + style J fill:#8cb83f,stroke:#698a2f,color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px +``` +Photos is left out below the minimum number of photos. + ## Contact ```mermaid block-beta diff --git a/aidlc-docs/_shared/reverse-engineering/api-documentation.md b/aidlc-docs/_shared/reverse-engineering/api-documentation.md index 54307a8..58f76cb 100644 --- a/aidlc-docs/_shared/reverse-engineering/api-documentation.md +++ b/aidlc-docs/_shared/reverse-engineering/api-documentation.md @@ -30,7 +30,7 @@ None. There is no back-end yet (`api/` is empty). The static design README antic ### Components (props) - `AppShell()`, `NavigationBar()`, `BackToTop()`, `NotFound()` — no props -- `MobileNav({ id, open, onClose })`, `NavLink(RouterLink props)` +- `MobileNav({ id, open, groupOpen, pathname, dispatch })`, `NavLink(RouterLink props & { sectionCurrent? })`, `NavSubmenu({ item, id, open, pathname, transparent, toggleRef, dispatch })` (desktop panel), `MobileNavGroup({ item, id, open, pathname, dispatch })`, `ChevronIcon()` - `Footer({ content: SiteContent })`, `FooterColumn({ title, children })`, `FooterLink(LinkProps)` - `Hero({ content: HeroContent, socials: SocialLink[] })`, `HeroArrows({ onPrev, onNext })`, `HeroPauseButton({ stopped, onToggle })`, `HeroSocials({ socials })` - `PageIntro({ title, eyebrow?, children? })` — renders the page's only h1 @@ -55,6 +55,7 @@ None. There is no back-end yet (`api/` is empty). The static design README antic - `useSwipe({ onPrev, onNext, enabled? })` → `{ onTouchStart, onTouchEnd }` (threshold and direction from `lib/swipeDirection`) - `useScrolledPast(getThreshold)` → boolean (stable `getThreshold` required) - `useRouteFocus()` — focuses `
` after navigation +- `useDismiss(ref, active, onDismiss(reason: 'escape' | 'outside'))` — document-level Escape and outside pointer down, listeners only while `active` (unit 3) - `useInView({ rootMargin, skip })` → `{ ref, inView }`; `usePageLoaded()` → boolean; `useReveal()` → `{ ref, visible }` ### Pure helpers (`lib/`) @@ -67,6 +68,7 @@ None. There is no back-end yet (`api/` is empty). The static design README antic - Portfolio (`lib/portfolioFilters.ts`): `isShootTypeId`, `shootTypesWithPhotos(shootTypes, photos)`, `shootFromSearch(value, available)`, `filterPhotos(photos, shoot)`, `filterOptions(shootTypes, allLabel)`, `toGalleryItems(photos, shootTypes)`, `photoCountLabel(n)`; `seo.ts`: `galleryImages(photos)` - 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`) - Shoot pages (unit 1): `shootPagePath(id)`, `shootIdFromSlug(slug)`, `shootIdFromPath(pathname)` (`lib/shootPages.ts`); `shootPackage(shoot, packages)` (`lib/shootPackage.ts`); `fillPlaceholders(text, values)`, `fillRichText(rich, values)` (`lib/fillPlaceholders.ts`); `richTextToPlain(text)` (`lib/richTextToPlain.ts`); `shootPageView(id, page, sources)` (`lib/shootPageView.ts`) +- Navigation (unit 3): `shootNavItems(shoots): NavItem[]` (`lib/shootNavItems.ts`); `isItemCurrent(item, pathname)`, `isSectionCurrent(item, pathname)` (`lib/navCurrent.ts`); `navMenuReducer(state, event)` with `NavMenuState`, `NavMenuEvent`, `initialNavMenuState`, `FocusRequest` (`lib/navMenuState.ts`) ### Monitoring - `monitoringFor(hostname): Monitoring | null`, `startSentry(hostname?)`, `reportError(error)` @@ -98,6 +100,6 @@ None. There is no back-end yet (`api/` is empty). The static design README antic ### HeroContent - **Fields**: `title`, `tagline`, `cta: { label, to }`, `slides: { id, src, alt }[]` ### NavItem (`navigation.ts`) -- **Fields**: `to: RoutePath`, `label: string` +- **Fields**: `to: RoutePath`, `label: string`, `children?: readonly NavItem[]` (one level; `hasChildren(item)` is true only for a non-empty list; the shoot pages are the children of `/soorten-fotoshoots`) ### PageMeta (`sitePages.ts`) - **Fields**: `title`, `description`, `indexed`, `ogImage?` diff --git a/aidlc-docs/_shared/reverse-engineering/architecture.md b/aidlc-docs/_shared/reverse-engineering/architecture.md index 3be5e95..2c3f585 100644 --- a/aidlc-docs/_shared/reverse-engineering/architecture.md +++ b/aidlc-docs/_shared/reverse-engineering/architecture.md @@ -62,6 +62,7 @@ Text alternative: main.tsx starts Sentry and mounts the router; the root route r ### components/NavigationBar/ - **Purpose**: Site header and navigation - **Responsibilities**: Fixed header, transparent over the hero on desktop until scrolled; shrinks after scroll; logo links home; desktop links and full-screen mobile menu from `mainNav` +- **Menu state**: one `useReducer(navMenuReducer)` (`lib/navMenuState.ts`) holds the mobile menu, its group, the desktop submenu and the focus request, so the hamburger, the panels and the route listener cannot disagree; `routeChanged` closes everything (also on browser back) - **Type**: Application ### components/Footer/ @@ -98,6 +99,7 @@ Text alternative: main.tsx starts Sentry and mounts the router; the root route r - **Purpose**: Static content until the CMS API exists - **Responsibilities**: `types.ts` (API-shaped interfaces incl. `ContentImage`, `HomeContent`, `PricingPackage`, `Testimonial`), `siteContent.ts` (footer intro, socials, e-mail parts, contact form switch), `heroContent.ts`, `homeContent.ts` (texts and photos of the homepage sections), `packages.ts`, `testimonials.ts`, `socialPlatforms.ts` - **Type**: Application (data) +- **D5 (unit 3)**: `navigation.ts` imports `shootTypes` (the submenu is built from it), so the shoot type data is in the main bundle instead of its own chunk. Measured in the Step 16 build: main chunk 150.69 → 152.58 kB gzip (+1.89 kB, limit 2.5 kB; raw 528.98 → 536.68 kB) ### lib/ - **Purpose**: Pure, fully tested helpers diff --git a/aidlc-docs/_shared/reverse-engineering/code-structure.md b/aidlc-docs/_shared/reverse-engineering/code-structure.md index b693860..b7d9ee3 100644 --- a/aidlc-docs/_shared/reverse-engineering/code-structure.md +++ b/aidlc-docs/_shared/reverse-engineering/code-structure.md @@ -24,6 +24,8 @@ graph TD NavigationBar --> MobileNav["NavigationBar/MobileNav.tsx"] NavigationBar --> navigation["navigation.ts"] Footer --> navigation + navigation --> shootNavItems["lib/shootNavItems.ts"] + navigation --> shootTypes["content/shootTypes.ts"] Index["routes/index.tsx"] --> Hero["Hero/Hero.tsx"] Hero --> HeroArrows["Hero/HeroArrows.tsx"] Hero --> HeroPause["Hero/HeroPauseButton.tsx"] @@ -44,7 +46,7 @@ graph TD classDef util fill:#e2e8f0,stroke:#4a5568,stroke-width:1px,color:#000; class Root,AppShell,NavigationBar,Footer,BackToTop,Umami,NavLink,MobileNav shell; class Index,Hero,HeroArrows,HeroPause,HeroSocials,Placeholder,PageIntro,HomeParts page; - class navigation,useHeroSlider,LinkButton,RouterLink,PageSection,SectionHeading,Reveal,FramedImage,DeferredImage util; + class navigation,shootNavItems,shootTypes,useHeroSlider,LinkButton,RouterLink,PageSection,SectionHeading,Reveal,FramedImage,DeferredImage util; ``` Text alternative: the root route renders AppShell (NavigationBar, Footer, BackToTop, Umami); NavigationBar and Footer read navigation.ts; the index route renders the Hero and the six home sections, which are built from the shared PageSection, SectionHeading, Reveal, FramedImage and DeferredImage blocks; placeholder routes render PageIntro. @@ -65,6 +67,7 @@ Candidates for modification are marked with ★ for the over-mij-page feature. - `web/src/content/{shootTypes,shootTypesPageContent}.ts` — shoot types (also used by the portfolio filters) and page texts; `web/src/assets/shoots/` — 4:5 shoot photos - `web/src/lib/shootLinks.ts` — contact and portfolio link targets per shoot type - `web/src/lib/{shootPages,shootPackage,fillPlaceholders,richTextToPlain,shootPageView}.ts` — shoot page helpers (ids and paths, package, placeholders, plain text, view), each with a test +- `web/src/lib/{shootNavItems,navCurrent,navMenuState}.ts` — navigation helpers (unit 3), each with a test: submenu items from the shoot types (`shootNavItems`), current-page and section-current matching (`isItemCurrent`, `isSectionCurrent`), menu state reducer (`navMenuReducer`, `NavMenuState`, `NavMenuEvent`; `navMenuState.ts` at 100 % coverage) - `web/src/components/PhotoDuo/PhotoDuo.tsx` — two photos side by side - `web/src/content/aboutContent.ts` — about page content; `web/src/assets/about/*` — portrait and duo photos; `web/public/og-over-mij.jpg` — preview image - `web/src/routes/soorten-fotoshoots/index.tsx` — the shoot types page (moved from `routes/soorten-fotoshoots.tsx`); `newborn.tsx`, `zwangerschap.tsx`, `gezin.tsx`, `loveshoot.tsx`, `portret.tsx` — one route per shoot page (`/soorten-fotoshoots/`); `-shootPageSources.ts` — the sources the shoot routes share @@ -73,7 +76,7 @@ Candidates for modification are marked with ★ for the over-mij-page feature. - `web/src/routes/portfolio.tsx` — the portfolio (indexed; `?shoot=` filter; `ImageGallery` JSON-LD); `web/src/components/portfolio/PortfolioGallery/`, `web/src/content/portfolioContent.ts`, `web/src/lib/portfolioFilters.ts`, `web/src/assets/portfolio/*` (10 photos × 2 sizes), `web/public/og-portfolio.jpg` - `web/src/routes/{contact,privacyverklaring}.tsx` — placeholders with `PageIntro` - `web/src/components/AppShell.tsx` — shell -- `web/src/components/NavigationBar/*` — header, NavLink, MobileNav +- `web/src/components/NavigationBar/*` — header, NavLink (`sectionCurrent` underline for the parent of an open section), MobileNav (scrolls; Escape returns focus to the hamburger), NavSubmenu (desktop disclosure panel), MobileNavGroup (expandable shoot list on mobile), ChevronIcon - `web/src/components/Footer/*` — footer, FooterColumn, FooterLink - `web/src/components/Hero/*` — hero slider, arrows, pause button, socials, slider hook - `web/src/components/home/*` — five homepage sections (AboutBlock is the closest relative of the Over mij page's first block) @@ -92,14 +95,16 @@ Candidates for modification are marked with ★ for the over-mij-page feature. - ★ `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`, `useSwipe` (shared by the hero and the lightbox) +- `web/src/hooks/useDismiss.ts` — Escape and outside pointer down while active (`useDismiss(ref, active, onDismiss)`), used by NavSubmenu and MobileNav (unit 3) - `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` +- `web/src/navigation.ts` — `RoutePath`, `NavItem` (with `children`, one level), `hasChildren`, `mainNav` (the shoot submenu comes from `shootTypes` via `shootNavItems`), `footerNav` - ★ `web/src/seo.ts`, `sitePages.ts`, `sitemap.ts` — SEO (`/over-mij` is `indexed: false` today) - ★ `web/lighthouserc.cjs` / `.desktop.cjs` — own list of indexed/noindex paths, guarded by a test - `web/src/theme.ts`, `web/src/recipes/*.ts` — design system - `web/src/test/*` — `renderWithProviders`, axe matcher, fast-check arbitraries, `fakeIntersectionObserver`, setup +- `web/src/test/navArbitraries.ts` — navigation generators (menu events, menu states, pathnames; unit 3, not in `lib/` so the 100 % threshold does not apply); `web/src/test/navViewport.ts` — viewport helper (`matchMedia` stub and the `lg` display rules, because jsdom ignores `@media`) - `web/src/assets/*` — hero photos (8), `home/` (intro 1–4, andrea, deco 1–2, two review photos), light/dark logos - `web/config/securityHeaders.ts` — CSP - `web/config/serverConfig.ts`, `writeServerConfig.ts`, `sitemapPlugin.ts`, `testSeed.ts` diff --git a/aidlc-docs/features/shoot-type-pages/audit.md b/aidlc-docs/features/shoot-type-pages/audit.md index 62131e7..58926db 100644 --- a/aidlc-docs/features/shoot-type-pages/audit.md +++ b/aidlc-docs/features/shoot-type-pages/audit.md @@ -327,3 +327,55 @@ **Context**: CONSTRUCTION - Code Generation Part 2 --- + +## Code Generation — Commit, push and test deploy authorised +**Timestamp**: 2026-10-30T12:32:38Z +**User Input**: "je mag wel meteen committen, pushen en deployen naar test. Ik zit nu niet thuis dus dan kan ik het via de testomgeving bekijken. dat is prima" +**AI Response**: Committed unit 1 as e5f4348 (OG crops of unit 2 left out, awaiting approval), pushed feature/shoot-type-pages, dispatched CI run 585 with deploy_test=true. Units 2 and 3 will be committed and deployed to test the same way once each reaches a green, coherent state. No merge to master (DRAFT gate still open). +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation (unit 2) — OG crops approved +**Timestamp**: 2026-10-30T12:49:25Z +**User Input**: "akkoord op alle 5 de deelafbeeldingen. De volgende deploy naar test hoef je pas te doen als beide units klaar zijn. Tussendoor hoeft niet" +**AI Response**: All five OG crops approved as produced (contact sheet in scratchpad og-crops). Unit 2 resumes at Step 3. Next commit, push and test deploy only once units 2 and 3 are both complete. CI run 585 (unit 1, e5f4348): check and deploy-test succeeded. +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation — Requirement added: FR-ST-14 (404 inside the shoot section) +**Timestamp**: 2026-10-30T12:58:10Z +**User Input**: "oh ik weet niet of dit goed te fixen is. Ik zou het hier wel bij willen doen namelijk. Maar als je naar /soorten-fotohoots/niet-bestaande-shoot gaat dan krijg je een 404 met \"Terug naar home\". Kan hier iets komen van \"Terug naar Soorten Fotoshoots of Terug naar Home\"?" +**AI Response**: Root cause: unmatched paths fall to the root notFoundComponent (no soorten-fotoshoots layout route), and StatusPage defaults to one home button. Added FR-ST-14: NotFound reads the pathname and, under /soorten-fotoshoots/, shows "Terug naar Soorten fotoshoots" (accent) + "Terug naar home" (outline), same pattern as ErrorPage. No layout route, so unit 3 matching and the bundle are unaffected. Delegated to a Sonnet agent; files (components/StatusPage/*) are disjoint from units 2 and 3; no builds (unit 3 owns them). +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation — FR-ST-14 implemented +**Timestamp**: 2026-10-30T13:00:55Z +**AI Response**: NotFound reads the pathname via useRouterState (same as NavigationBar) and uses new pure helper lib/isShootSectionPath.ts (case-insensitive prefix '/soorten-fotoshoots/'); unit + PBT tests and 3 StatusPage tests (two links in order + axe, mixed case, single link elsewhere). Scoped vitest 18/18, tsc and lint clean on these files. Reviewed by orchestrator. Full verification runs with the unit 2/3 gates. +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation (unit 3) — Steps 1–16 complete +**Timestamp**: 2026-10-30T13:01:52Z +**AI Response**: Unit 3 Steps 1–16 done; D5 bundle gate passed (main chunk gzip 150.69 → 152.58 kB, +1.89 kB, limit 2.5 kB); lint/format/tsc green; 801 tests passing. Its reported coverage failure on lib/isShootSectionPath.ts was a mid-run race with the FR-ST-14 agent (source written 13:59:04, test 13:59:05); re-run alone gives 9 tests and 100% coverage. Steps 19–20 (docs) delegated to Haiku. Steps 17–18 (real browser, Lighthouse on port 4173) deferred until unit 2 finishes Step 21, so they measure a coherent build. +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation (unit 2) — Steps 3–21 complete; cross-unit test fix +**Timestamp**: 2026-10-30T13:17:14Z +**AI Response**: Unit 2 Steps 3–21 done (113 files / 883 tests, 1 failing). Root cause of the failure: unit 3's case-variant test counted every aria-current on the page; unit 2's breadcrumb legitimately marks its last item aria-current="page" (BR-SP-01), and the router renders the page on /soorten-fotoshoots/Newborn. Orchestrator narrowed the assertion: exactly one mark, a non-link inside the "Kruimelpad" nav (no nav/footer link marked). navSubmenu.test.tsx 18/18. LAYOUT.md Prettier warnings are pre-existing on HEAD and outside web/'s format check; left as is. Sequential gates delegated to one Sonnet agent: unit 2 Step 22 → unit 3 Step 17 → unit 3 Step 18 → unit 2 Step 23 → unit 2 Step 26 (sole owner of port 4173). +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- + +## Code Generation (units 2 and 3) — Sequential gates +**Timestamp**: 2026-10-30T13:43:43Z +**AI Response**: Unit 2 Step 22 pass (lint, format, tsc, build, audit:deps with seroval 1.7.3, 113 files / 883 tests, main gzip 152.56 kB = +1.87 kB vs unit 1, DRAFT markers 98). Unit 3 Step 17 pass (110/110 browser checks, 1024/1100/1280 fit, keyboard, reduced motion, short phones). Unit 3 Step 18 pass (mobile / pooled median 0.77 vs baseline 0.77). Unit 2 Step 26 done (exactly three aria-current per shoot page: breadcrumb, header submenu link, mobile sub-link; 888 tests). Unit 2 Step 23 NOT green: mobile gezin 0.84–0.85 and loveshoot 0.83 below the 0.85 budget (unit 1 shell-only 0.90); LCP render delay ~2.9 s after the main bundle, photo itself fast; / and /contact below budget as on master. Desktop 0.99–1.00. Decision on mitigation goes to the user. Per the user's instruction (deploy when both units are done; CI deploy-test does not wait on Lighthouse) units 2 and 3 plus FR-ST-14 are committed, pushed and deployed to test now. +**Context**: CONSTRUCTION - Code Generation Part 2 + +--- diff --git a/aidlc-docs/features/shoot-type-pages/construction/navigation-submenu/code/code-summary.md b/aidlc-docs/features/shoot-type-pages/construction/navigation-submenu/code/code-summary.md new file mode 100644 index 0000000..a5f6c08 --- /dev/null +++ b/aidlc-docs/features/shoot-type-pages/construction/navigation-submenu/code/code-summary.md @@ -0,0 +1,137 @@ +# Code Summary — Unit 3: Navigation submenu + +Plan: [navigation-submenu-code-generation-plan.md](../../plans/navigation-submenu-code-generation-plan.md). Branch `feature/shoot-type-pages` (from master `18e81d0`), worktree `AndreaSlopFotografie-shoot-type-pages`. Unit 2 (shoot page UI) is built in the same worktree; its files are not described here. + +## Status +- Steps 1–16 and 19–20 done (checked in the plan). +- Step 17 (real-browser check: 1024 px fit, transparent header, short phone): **pending — run by orchestrator after unit 2's build**. +- Step 18 (Lighthouse, needs the port 4173 claim): **pending — run by orchestrator after unit 2's build**. +- Gates (Step 15): lint, format:check and `tsc` green. `pnpm test`: 106 files, 801 tests passing, fast-check seed 1525740974. The coverage failure reported at that moment came from a file written mid-run by another task. `lib/isShootSectionPath.ts` has 100 % coverage when run on its own, and a full re-run happens at the joint verification. + +## Commits +None. The unit is uncommitted in the worktree. A commit (and a push) is made only when the user asks. + +## Files + +### Created (unit 3) +- `web/src/lib/shootNavItems.ts` (+ `.test.ts`): submenu items from the shoot types +- `web/src/lib/navCurrent.ts` (+ `.test.ts`): `isItemCurrent`, `isSectionCurrent` +- `web/src/lib/navMenuState.ts` (+ `.test.ts`): `navMenuReducer`, `NavMenuState`, `NavMenuEvent`, `initialNavMenuState`, `FocusRequest` +- `web/src/hooks/useDismiss.ts` (+ `useDismiss.test.tsx`) +- `web/src/components/NavigationBar/NavSubmenu.tsx` (desktop disclosure panel), `MobileNavGroup.tsx` (expandable shoot list), `ChevronIcon.tsx` (inline SVG) +- `web/src/components/NavigationBar/NavSubmenu.test.tsx`, `MobileNav.test.tsx`, `NavLink.test.tsx`, `activeOptions.test.tsx` (the exact-matching probe of Step 2, kept as a regression test) +- `web/src/navSubmenu.test.tsx` (real app, `renderApp`) +- `web/src/test/navArbitraries.ts` (unit 3's own fast-check generators; in `test/`, not `lib/`, so the 100 % threshold does not apply to them) +- `web/src/test/navViewport.ts` (test helper: `matchMedia` stub plus the `lg` display rules, because jsdom ignores `@media`) + +### Modified (unit 3) +- `web/src/navigation.ts`: `NavItem.children`, `hasChildren`, `mainNav` parent gets `children: shootNavItems(shootTypes)`; `footerNav` unchanged +- `web/src/navigation.test.ts` (6 tests added, 10 in total) +- `web/src/components/NavigationBar/NavigationBar.tsx`: `useReducer(navMenuReducer)`, effects for `viewport`, `routeChanged` and `focusRequest` +- `web/src/components/NavigationBar/NavigationBar.test.tsx` (extended; the "vaste volgorde" test now asserts the top level and the five children separately) +- `web/src/components/NavigationBar/NavLink.tsx`: `sectionCurrent` prop (`data-section-current`, underline) +- `web/src/components/NavigationBar/MobileNav.tsx`: props `{ id, open, groupOpen, pathname, dispatch }`, scrolls (`overflowY="auto"`), centring wrapper, reduced-motion reveal +- `web/src/components/Footer/Footer.tsx` (exact matching), `Footer.test.tsx` (5 tests added, 11 in total) + +### Not touched by unit 3 +`components/shoots/*`, the page section components, `MediaText`, `CallToAction`, `routes/soorten-fotoshoots/*`, `content/*`, `sitePages.ts`, `LAYOUT.md`, `.ai/`, `test/arbitraries.ts`, `theme.ts`, `package.json`, `pnpm-lock.yaml`. + +## Interfaces +- `NavItem.children?: readonly NavItem[]` (one level; an empty array counts as none); `hasChildren(item)` (`navigation.ts`) +- `shootNavItems(shoots: readonly ShootType[]): NavItem[]` (`lib/shootNavItems.ts`): `{ to: shootPagePath(id), label: name }` in input order +- `isItemCurrent(item, pathname)`, `isSectionCurrent(item, pathname)` (`lib/navCurrent.ts`): lower case, one trailing slash ignored (not for `/`); pure string comparison +- `NavMenuState { isDesktop, menuOpen, groupOpen, submenuOpen, focusRequest }`, `NavMenuEvent` (`viewport`, `toggleMenu`, `toggleGroup`, `toggleSubmenu`, `escape`, `outside`, `focusLeave`, `linkChosen`, `routeChanged`, `focusHandled`), `navMenuReducer(state, event)`, `initialNavMenuState` (`lib/navMenuState.ts`). Invariants I1–I4: `submenuOpen` implies desktop; `menuOpen` implies mobile; `groupOpen` implies `menuOpen`; a focus request fits the width. An event that does not apply returns the same object. +- `useDismiss(ref, active, onDismiss(reason: 'escape' | 'outside'))` (default export, `hooks/useDismiss.ts`) +- Component props: + - `NavSubmenu({ item, id, open, pathname, transparent, toggleRef, dispatch })` + - `MobileNavGroup({ item, id, open, pathname, dispatch })` + - `MobileNav({ id, open, groupOpen, pathname, dispatch })` (`onClose` removed) + - `NavLink(RouterLink props & { sectionCurrent?: boolean })` + - `ChevronIcon()` +- Footer links: `activeOptions={{ exact: true, includeSearch: false }}` (see the truth table below) + +## Requirement and rule traceability +| Requirement / rule | Where | Tests | +|---|---|---| +| FR-ST-10 Navigation submenu | `navigation.ts`, `shootNavItems.ts`, `NavigationBar/*`, `Footer.tsx`, `navMenuState.ts` | `navigation.test.ts`, `shootNavItems.test.ts`, `navMenuState.test.ts`, `NavigationBar.test.tsx`, `NavSubmenu.test.tsx`, `MobileNav.test.tsx`, `navSubmenu.test.tsx`, `Footer.test.tsx` | +| NFR-ST-01 Accessibility (disclosure pattern, keyboard, focus, 44 px, reduced motion, axe) | `NavSubmenu`, `MobileNavGroup`, `MobileNav`, `NavLink`, `ChevronIcon`, `useDismiss` | `NavigationBar.test.tsx` and `MobileNav.test.tsx` (axe open and closed, focus, Escape, keyboard), `useDismiss.test.tsx`, `NavLink.test.tsx`; the visual part is Step 17 (pending) | +| NFR-ST-03 Performance (D5 gate) | `navigation.ts` imports `shootTypes` | Step 16 bundle check; Steps 17–18 pending | +| NFR-ST-06 Testing (PBT + example + registry consistency) | `test/navArbitraries.ts`, `test/navViewport.ts` | PBT in `shootNavItems`, `navCurrent`, `navMenuState` (model-based stateful run); registry "a nav child per shoot" in `navigation.test.ts`; example tests as listed | +| D4 current state | `navCurrent.ts`, `NavLink` (`sectionCurrent`), exact `activeOptions` in every nav and footer link | `activeOptions.test.tsx` (12 tests), `navCurrent.test.ts` (20), `navSubmenu.test.tsx` (18), `Footer.test.tsx` | +| D5 nav source | `navigation.ts` → `shootNavItems(shootTypes)` (single source) | `navigation.test.ts`, `navSubmenu.test.tsx` (every panel name matches `shootTypes`) | +| BR-NAV-01..05 current state, exact matching, case, query, hash | `navCurrent.ts`, `activeOptions` (Step 2) | `activeOptions.test.tsx`, `navCurrent.test.ts`, `navSubmenu.test.tsx` | +| BR-NAV-10..12 content | `shootNavItems.ts`, `navigation.ts` | `shootNavItems.test.ts`, `navigation.test.ts` | +| BR-NAV-20..29 desktop submenu (click, Escape, outside, Tab out, no hover, no arrow keys, closed panel not reachable) | `NavSubmenu.tsx`, `useDismiss.ts`, `navMenuState.ts` | `NavSubmenu.test.tsx` (13), `NavigationBar.test.tsx` (27), `useDismiss.test.tsx` (9), `navMenuState.test.ts` (27) | +| BR-NAV-30..36 mobile menu (group state, collapse, close on choice, Escape to hamburger, scroll, scroll lock) | `MobileNav.tsx`, `MobileNavGroup.tsx`, `navMenuState.ts` | `MobileNav.test.tsx` (18), `navSubmenu.test.tsx` (back navigation, group expanded on a shoot page) | +| BR-NAV-40..43 layout, touch targets, motion, focus ring | `NavSubmenu`, `MobileNavGroup`, `MobileNav` (`_motionReduce`) | `NavigationBar.test.tsx` and `MobileNav.test.tsx` (reduced-motion rules via `cssRulesFor`); the browser measurements are Step 17 (pending) | +| BR-NAV-50 bundle and Lighthouse | Step 16, Step 18 | Step 16 done; Step 18 pending | + +## Test results +- Step 15 gate: lint, format:check, tsc green; `pnpm test` 106 files, 801 tests, seed 1525740974 (see Status for the coverage remark). +- New and extended unit 3 test files, with the counts from their steps: `activeOptions.test.tsx` 12; `shootNavItems.test.ts` 7 (5 properties); `navCurrent.test.ts` 20; `navMenuState.test.ts` 27 (incl. the model-based stateful run); `navigation.test.ts` 10 in total; `useDismiss.test.tsx` 9; `NavLink.test.tsx` 4; `NavigationBar.test.tsx` 27; `NavSubmenu.test.tsx` 13; `MobileNav.test.tsx` 18; `navSubmenu.test.tsx` 18; `Footer.test.tsx` 11 in total. + +## Coverage of the new lib files +- `lib/shootNavItems.ts`, `lib/navCurrent.ts`, `lib/navMenuState.ts`: 100 % (statements, branches, functions, lines), in the Step 15 run. +- `hooks/` and components are only reported, not thresholded. +- `test/navArbitraries.ts` and `test/navViewport.ts` are test code (excluded from coverage). + +## Router truth table (Step 2, router 1.170) +Verified by `activeOptions.test.tsx`: +- Trailing slash is ignored: `/soorten-fotoshoots/` is active with plain `exact` and with `exact` plus `includeSearch: false`. +- Case is not ignored: `/Soorten-Fotoshoots/Newborn` is not active in either variant. +- A query breaks plain `exact`: on `/soorten-fotoshoots?x=1` the link loses `aria-current` with `{ exact: true }` (`includeSearch` defaults to `true`). `{ exact: true, includeSearch: false }` keeps it. +- The parent is never active on a child path (`/soorten-fotoshoots/newborn`). + +Decision: every nav and footer link that gets `exact` also gets `includeSearch: false`. This deviates from the FD text (`{ exact: true }` only, BR-NAV-01, BR-NAV-04) and keeps today's behaviour for `/portfolio?shoot=…`, where the footer's Portfolio link is active. + +Consequence for the case variant: on `/soorten-fotoshoots/Newborn` the page renders (the route matches case-insensitively, unit 1 summary), no link has `aria-current`, and the parent keeps `data-section-current` through `isSectionCurrent` (case-insensitive). Accepted: `aria-current` is the router's output and the canonical URL is lowercase. + +## Bundle check (Step 16, D5 gate) +- Baseline (unit 1, Step 1): `index-D0huvRmx.js` 528.98 kB raw / 150.69 kB gzip. +- After unit 3 (Step 16): `index-Dtz2mqhH.js` 536.68 kB raw / 152.58 kB gzip. +- Delta: +7.70 kB raw, **+1.89 kB gzip** against the 2.5 kB limit. The delta may include small unit 2 changes made since Step 1. +- Shoot photos still emitted as files: 50 `.jpg` (same as Step 1), 0 `.webp`. `data:image` count in the index 1 (same as Step 1). +- The Newborn-only string ("Uit eerdere newbornshoots") is only in `newborn-*.js`; the five shoot page chunks are still separate files. +- The separate `shootTypes` chunk is gone (now in the main chunk); `dist/assets` has 119 files (121 at baseline). + +## Browser check (Step 17) — pending +Pending — run by orchestrator after unit 2's build. The checklist is in the plan: widths at 1024, 1100 and 1280 px (no wrapping, no overlap, real widths against the FD estimate of about 715 px of 848 px), open panel (visibility, bounding box, solid background, white chevron on the transparent header), keyboard run, reduced motion, mobile at 375 × 480 and 360 × 560. The `mx` fallback on `NavLink` is not applied unless the 1024 px check needs it (record it then). + +## Lighthouse (Step 18) — pending +Pending — run by orchestrator after unit 2's build (needs the port 4173 claim). Plan: median mobile performance of `/` after the unit, against the same-session baseline of the unit-1 build; unit-1 measurement was 0.76 on `/` (budget 0.8). Full set and failing budgets to be recorded then. + +## Deviations from the design +- **Exact matching:** `{ exact: true, includeSearch: false }` instead of `{ exact: true }` (router truth table above). +- **Test helper:** `src/test/navViewport.ts` (new, not in the plan's file list): a `matchMedia` stub and a style element with the `lg` display rules, because jsdom ignores `@media`. +- **Hamburger lookup:** `MobileNav` finds the hamburger by `aria-controls` (the id `mobile-nav`) for the Escape focus return, not by a test id in production code. +- **Focus request:** `linkChosen` and `routeChanged` also clear a pending `focusRequest`. +- **Pathname normalisation:** `navCurrent` treats `'//'` as `'/'` (one trailing slash removed). Harmless: the pathname is never rendered. +- **Real-app case-variant check:** moved to `navSubmenu.test.tsx` (the pre-Step-9 app still prefix-matched, so the check could not run in Step 2). + +## Open points for the orchestrator +1. **No focus trap in the mobile menu** (BR-NAV-35): not added in this unit; the menu is a full-screen overlay with Escape and the hamburger return. +2. **Desktop `NavLink` box height:** the existing desktop `NavLink` boxes are about 35 px high. Outside this unit (existing styling of the header). +3. **Case-insensitive route vs exact `aria-current`:** see the consequence above; the router matches case-insensitively but `aria-current` is exact, so `/soorten-fotoshoots/Newborn` shows the page with no `aria-current` on the links. Decision for the orchestrator together with the unit-1 open decision on `caseSensitive`. +4. Steps 17 and 18 (browser check, Lighthouse) are pending, see above. + +## Security and PBT compliance (final) +| Rule | Status | Evidence | +|---|---|---| +| SECURITY-04 HTTP headers | Compliant | `config/securityHeaders.ts` untouched; no inline script or handler string; no new external resource | +| SECURITY-05 Input validation | Compliant | The pathname is only compared (`navCurrent`, never throws on hostile strings, property-tested), never rendered; link targets are typed `RoutePath`s; labels are React text | +| SECURITY-09 Hardening | Compliant | No debug output or placeholders; Step 15 greps `console.` and `debugger` in the unit 3 files: none | +| SECURITY-10 Supply chain | Compliant | No dependency added; `package.json` and `pnpm-lock.yaml` unchanged (Step 15); the browser check (Step 17) uses a transitive `puppeteer-core` only from a script outside the repo | +| SECURITY-11 Secure design | Compliant | Menu logic in a pure, invariant-tested reducer; no `dangerouslySetInnerHTML`, no new `target="_blank"` (Step 15 greps) | +| SECURITY-13 Integrity | Compliant | Inline SVG chevron, no CDN or external asset | +| SECURITY-15 Fail-safe | Compliant | Impossible events return the same state; the reducer never opens a menu that cannot exist at the width; empty `children` renders a plain link; exhaustive `switch` with a `never` check; null refs and non-Node targets ignored | +| SECURITY-01, -02, -03, -06, -07, -08, -12, -14 | N/A | Front-end navigation only: no data store, intermediary, server code, IAM, network, auth or alerting | +| PBT-01 Identification | Compliant | Properties per function in the FD, mapped to Steps 3–5 | +| PBT-02 Round trip | Compliant | `shootIdFromPath(shootNavItems(...)[i].to)` equals the shoot id (Step 3) | +| PBT-03 Invariants | Compliant | Order, labels, known routes (Step 3); exactness, section implication, no look-alikes, normalisation (Step 4); I1–I4 (Step 5) | +| PBT-04 Idempotency | Compliant | `routeChanged`, `linkChosen`, `escape`, `outside` applied twice equal once; trailing slash (Steps 4, 5) | +| PBT-05 Oracle | N/A | No reference implementation (the Step 5 model is a second check of the transition table, not an oracle for a different algorithm) | +| PBT-06 Stateful | Compliant | Model-based event sequences on `navMenuReducer`, invariants after every step (Step 5) | +| PBT-07 Generators | Compliant | `navMenuEvent(s)`, `navMenuState`, `pathname` in `test/navArbitraries.ts`; domain generators reused from `test/arbitraries.ts` (import only) | +| PBT-08 Shrinking/reproducibility | Compliant | Seed from `config/testSeed.ts`, logged each run (seed 1525740974 at Step 15); shrinking untouched | +| PBT-09 Framework | Compliant | fast-check already a dependency | +| PBT-10 Complementary | Compliant | Example tests for keyboard, focus, outside click, route change, axe, real-app `aria-current`, named apart from the PBT | diff --git a/aidlc-docs/features/shoot-type-pages/construction/plans/navigation-submenu-code-generation-plan.md b/aidlc-docs/features/shoot-type-pages/construction/plans/navigation-submenu-code-generation-plan.md index c044c09..1aa2011 100644 --- a/aidlc-docs/features/shoot-type-pages/construction/plans/navigation-submenu-code-generation-plan.md +++ b/aidlc-docs/features/shoot-type-pages/construction/plans/navigation-submenu-code-generation-plan.md @@ -43,30 +43,34 @@ This plan is the **single source of truth** for code generation of unit 3. Steps ### Setup and probes -- [ ] **Step 1 — Baseline and unit-1 bundle number** [haiku] — *NFR-ST-03, BR-NAV-50, NFR-ST-06* +- [x] **Step 1 — Baseline and unit-1 bundle number** [haiku] — *NFR-ST-03, BR-NAV-50, NFR-ST-06* - In `web/` (worktree): confirm `node_modules` exists (`pnpm install --frozen-lockfile` if not; lockfile must stay unchanged). Run `pnpm lint`, `pnpm format:check`, `pnpm exec tsc`, `pnpm test`; note test count and the logged fast-check seed. All must be green before any change; if not, report and stop. - Build the **unit-1 baseline** before touching code: `pnpm exec vite build`; record from the build output the line for `dist/assets/index-*.js` (expected 528.98 kB raw / **150.69 kB gzip**, from the unit-1 code summary); also record the list of `dist/assets/*` with sizes and the number of `.jpg`/`.webp` files, and `grep -c "data:image" dist/assets/index-*.js` (inlined images). Copy the folder to `\dist-baseline` (outside the repo; used by Step 18). `dist/` is git-ignored. - Hand-back: numbers only. If the main chunk differs from 150.69 kB by more than 0.3 kB, report it: the D5 limit is then measured against the new number, which is the one that counts. + - Result: lint, format:check, tsc green; 90 files / 595 tests pass, seed 907726089. Baseline index-D0huvRmx.js 528.98 kB raw / 150.69 kB gzip (equal to expected); 50 .jpg files, 0 .webp, `data:image` count in index = 1 (pre-existing), 121 files in dist/assets, "Uit eerdere newbornshoots" only in newborn-*.js. Baseline copied to scratchpad dist-baseline. -- [ ] **Step 2 — Probe and pin the router's exact matching** [sonnet] — *BR-NAV-01, BR-NAV-04, D4 (risk 1)* +- [x] **Step 2 — Probe and pin the router's exact matching** [sonnet] — *BR-NAV-01, BR-NAV-04, D4 (risk 1)* - Why: the FD asks to verify `activeOptions={{ exact: true }}` "with trailing slash and case". Reading `@tanstack/router-core` `resolveIsActive` (node_modules, react-router 1.170): `exact` compares `removeTrailingSlash(location.pathname) !== removeTrailingSlash(next.pathname)` as plain strings, so **trailing slash is ignored but case is not**, and `includeSearch` defaults to `true`, so with `exact` a link is **not** active as soon as the location has a query string (`deepEqual` of `search` without partial matching). Both differ from BR-NAV-04 ("ignores case, query and hash"). This step proves it and fixes the plan for the later steps. - New `web/src/components/NavigationBar/activeOptions.test.tsx`: with `renderWithProviders` (splat route, memory history) render a `RouterLink` (`../RouterLink`) to `/soorten-fotoshoots` and to `/soorten-fotoshoots/newborn` with `activeOptions={{ exact: true }}` and with `activeOptions={{ exact: true, includeSearch: false }}`, at these locations: exact path; trailing slash; `/Soorten-Fotoshoots/Newborn` (case); `/soorten-fotoshoots?x=1` and `/portfolio?shoot=newborn` (search); `/soorten-fotoshoots/newborn` (parent must not be active). Assert `aria-current` present/absent for each. Also one case through `renderApp('/soorten-fotoshoots/Newborn')` (the real route tree renders the Newborn page there, unit-1 summary) to record what the router reports. - Expected result and consequence (the test pins whatever is true; if it differs, record the facts and adapt): (a) trailing slash is active in both variants; (b) the case variant is **not** active in either variant, so on `/soorten-fotoshoots/Newborn` the page shows but no link has `aria-current`, while `isSectionCurrent` (case-insensitive, Step 4) underlines the parent; accepted, because `aria-current` is the router's output and the canonical URL is lowercase (record in the code summary, not a bug to fix here); (c) with plain `exact` a query string removes `aria-current`, therefore **every nav and footer link that gets `exact` also gets `includeSearch: false`** (Steps 9, 10, 12): `activeOptions={{ exact: true, includeSearch: false }}`. This is a deliberate deviation from the FD text (`{ exact: true }` only); it keeps today's behaviour for `/portfolio?shoot=…` where the footer's Portfolio link is currently active. - Hand-back: the observed truth table, and whether (b) and (c) hold. + - Result: Truth table with router 1.170, verified by activeOptions.test.tsx (12 tests): trailing slash is active in both variants; case variant /Soorten-Fotoshoots/Newborn is NOT active in either; plain exact loses aria-current when the URL has a query (/soorten-fotoshoots?x=1), includeSearch false keeps it; parent never active on a child path. So (b) and (c) hold: every nav and footer link gets exact + includeSearch false. Real-app case-variant assertion on aria-current is pinned in navSubmenu.test.tsx (Step 14), because the pre-Step-9 app still prefix-matches. ### Pure logic (lib) -- [ ] **Step 3 — `shootNavItems`** [sonnet] — *FR-ST-10, BR-NAV-10, BR-NAV-12, PBT-01/02/03* +- [x] **Step 3 — `shootNavItems`** [sonnet] — *FR-ST-10, BR-NAV-10, BR-NAV-12, PBT-01/02/03* - New `web/src/lib/shootNavItems.ts`: `export function shootNavItems(shoots: readonly ShootType[]): NavItem[]` returning `{ to: shootPagePath(s.id), label: s.name }` per shoot in input order (no overview entry, no extra fields). `import type { NavItem } from '../navigation.ts'`, `import type { ShootType }`, value import of `shootPagePath` from `./shootPages.ts`. Short English comment. - New `web/src/lib/shootNavItems.test.ts`: properties with `uniqueShootTypes` — length equals input length; order preserved (invariant); `label === name` for each; round trip `shootIdFromPath(item.to) === shoot.id`; every `to` equals `shootPagePath(id)` and starts with `SHOOT_TYPES_PATH + '/'`. Example: the real `shootTypes` give the five labels in order, the fifth being the name ("Portretten") and not the id; empty input gives `[]`. - Coverage of the file 100 %. + - Result: shootNavItems.ts + 7 tests (5 properties), 100% coverage. -- [ ] **Step 4 — `navCurrent`** [sonnet] — *D4, BR-NAV-01..04, PBT-03/04* +- [x] **Step 4 — `navCurrent`** [sonnet] — *D4, BR-NAV-01..04, PBT-03/04* - New `web/src/lib/navCurrent.ts`: `isItemCurrent(item: NavItem, pathname: string): boolean` and `isSectionCurrent(item: NavItem, pathname: string): boolean`; private `normalise(path)`: lower-case and remove one trailing slash unless the path is `/`. `isItemCurrent` = `normalise(item.to) === normalise(pathname)`; `isSectionCurrent` = `isItemCurrent(item)` or `item.children?.some(child => isItemCurrent(child, pathname))`. Pure string comparison, never throws on any input (SECURITY-05, SECURITY-15); the pathname is never rendered. - New `web/src/lib/navCurrent.test.ts`, using `knownRoutePath`, `shootTypeId` and `uniqueShootTypes` from `test/arbitraries.ts` and the `pathname` generator of Step 5's `test/navArbitraries.ts` only if Step 5 is done; otherwise define the hostile-string generator locally and move it in Step 5. Properties from the FD: `isItemCurrent` true iff normalised paths equal (invariant); adding one trailing slash or changing letter case does not change the result (invariant/idempotency); false for any path outside the item (a path that normalises differently); `isSectionCurrent` is implied by `isItemCurrent`; implied by any child being exact; false for unrelated paths including the prefix look-alikes `/soorten-fotoshoots-extra` and `/soorten-fotoshootsX`; `/` is not a section of `/soorten-fotoshoots`; empty and hostile strings (`''`, `'//'`, spaces, `%2F`, very long) return a boolean and do not throw. Examples: `/soorten-fotoshoots/newborn/` marks the parent as section and the newborn child as item. - 100 % coverage. + - Result: navCurrent.ts + 20 tests, 100% coverage. Note: '//' normalises to '/' (one trailing slash removed), so it counts as the home page; harmless, pathname is never rendered. -- [ ] **Step 5 — `navMenuReducer` and unit 3 generators** [sonnet] — *FR-ST-10, BR-NAV-20..36, domain-entities invariants I1–I4, PBT-01/03/04/06/07/08* +- [x] **Step 5 — `navMenuReducer` and unit 3 generators** [sonnet] — *FR-ST-10, BR-NAV-20..36, domain-entities invariants I1–I4, PBT-01/03/04/06/07/08* - New `web/src/lib/navMenuState.ts` exactly as in business-logic-model.md and domain-entities.md: types `FocusRequest = 'menuToggle' | 'submenuToggle' | null`, `NavMenuState` (`isDesktop`, `menuOpen`, `groupOpen`, `submenuOpen`, `focusRequest`), the discriminated union `NavMenuEvent` (`viewport{isDesktop}`, `toggleMenu{inSection}`, `toggleGroup`, `toggleSubmenu`, `escape{focusInside}`, `outside`, `focusLeave`, `linkChosen`, `routeChanged`, `focusHandled`), `initialNavMenuState` (all `false`/`null`; `isDesktop` false until the first `viewport` event) and `navMenuReducer(state, event)` implementing the transition table. A condition that is not met returns the **same state object** (referential equality, so `useReducer` skips the re-render). `viewport(d)` also clears a `focusRequest` that no longer satisfies I4. `escape` closes the mobile menu first when it is open, otherwise the submenu; `focusRequest` is set only when `focusInside`. No default-case fallthrough that opens something (SECURITY-15); use an exhaustive `switch` with a `never` check. - New `web/src/test/navArbitraries.ts` (excluded from coverage by `src/test/**`; unit 3's own file, unit 2 never edits it): `navMenuEvent` (all events with random payloads, weighted so `viewport`, toggles and `escape` are frequent), `navMenuEvents` (arrays up to ~40), `navMenuState` (any state that satisfies I1–I4, plus a helper to build an arbitrary start state by folding random events from the initial state), `pathname` (known shoot paths, parent and other routes, with/without trailing slash, case variants, prefix look-alikes, hostile strings). Document each generator in one line. Do **not** edit `test/arbitraries.ts`; the FD note "appended to arbitraries.ts" (PBT-07) is superseded by the parallel-work constraint. - New `web/src/lib/navMenuState.test.ts`: @@ -75,66 +79,79 @@ This plan is the **single source of truth** for code generation of unit 3. Steps - (invariant) `toggleSubmenu` twice on desktop returns the original state; after `viewport(true)` no mobile state is open; after `viewport(false)` no submenu is open; `toggleMenu(inSection)` from closed opens with `groupOpen === inSection`, and closing sets `groupOpen = false`. - Examples (PBT-10): each row of the transition table once, including "ignored on the wrong viewport returns the same object" (`toggleSubmenu` on mobile, `toggleMenu` on desktop, `toggleGroup` while closed, `escape` with nothing open, `outside` with the submenu closed). - 100 % coverage of `navMenuState.ts` (every `case`, both branches of each condition). + - Result: navMenuState.ts, test/navArbitraries.ts, navMenuState.test.ts (27 tests incl. model-based stateful run), 100% coverage. Decisions: outside/focusLeave keep an existing focusRequest; linkChosen/routeChanged also clear it; unknown event returns the same state (default branch tested with a cast). ### Data -- [ ] **Step 6 — `navigation.ts` children** [sonnet] — *FR-ST-10, BR-NAV-10, BR-NAV-11, D5* +- [x] **Step 6 — `navigation.ts` children** [sonnet] — *FR-ST-10, BR-NAV-10, BR-NAV-11, D5* - `web/src/navigation.ts`: add `children?: readonly NavItem[]` to `NavItem` (comment: one level only, empty array counts as none). Export `hasChildren(item): item is NavItem & { children: readonly NavItem[] }` (`(item.children?.length ?? 0) > 0`). `mainNav`'s `/soorten-fotoshoots` entry gets `children: shootNavItems(shootTypes)`; `footerNav` unchanged. Value imports: `shootNavItems` from `./lib/shootNavItems.ts` and `shootTypes` from `./content/shootTypes.ts` (D5: single source). Check that this creates no runtime cycle (`content/shootTypes.ts` and `lib/shootPages.ts` must only import types from `navigation.ts`); if one appears, report instead of working around it. - `web/src/navigation.test.ts` (extend; keep the existing four tests): the parent has exactly the five children in `shootTypes` order with labels = names and `to = shootPagePath(id)`; **a nav child exists for every `SHOOT_TYPE_IDS` entry and nothing extra** (the registry consistency left open by unit 1); all other main items and all of `footerNav` have no children and children have none (one level); `hasChildren` true only for the parent and false for `children: []`; no duplicate `to` across the parent and its children; every child `to` is in `sitePages` with `indexed: true` (import `sitePages` read-only) so the menu never links to an unregistered page. + - Result: navigation.ts has children + hasChildren; mainNav parent uses shootNavItems(shootTypes). No runtime cycle (content/shootTypes.ts, content/types.ts, lib/shootPages.ts, lib/shootNavItems.ts only import types from navigation.ts). navigation.test.ts has 6 new tests (10 total). ### UI building blocks -- [ ] **Step 7 — `useDismiss`** [sonnet] — *FR-ST-10, BR-NAV-23, BR-NAV-24, NFR-ST-01* +- [x] **Step 7 — `useDismiss`** [sonnet] — *FR-ST-10, BR-NAV-23, BR-NAV-24, NFR-ST-01* - New `web/src/hooks/useDismiss.ts`: `export default function useDismiss(ref: RefObject, active: boolean, onDismiss: (reason: 'escape' | 'outside') => void): void`. While `active`: `document` `keydown` with `key === 'Escape'` calls `onDismiss('escape')`; `document` `pointerdown` whose `event.target` is a Node not contained in `ref.current` calls `onDismiss('outside')`. Listeners are added only while active and removed on deactivation and unmount. Keep `onDismiss` in a ref (updated in an effect) so a new callback identity does not re-subscribe. No menu logic. A `null` ref or a non-Node target is ignored (fail-safe). - New `web/src/hooks/useDismiss.test.tsx` (harness component, `@testing-library/user-event`): Escape and an outside pointer down call back only while active; inside pointer down does not; nothing fires when inactive; listeners removed on unmount (spy on `document.removeEventListener` or assert no call after unmount); changing the callback does not double-call. + - Result: useDismiss.ts + 9 tests. -- [ ] **Step 8 — `ChevronIcon` and `NavLink.sectionCurrent`** [sonnet] — *D4, BR-NAV-02, BR-NAV-42, NFR-ST-01* +- [x] **Step 8 — `ChevronIcon` and `NavLink.sectionCurrent`** [sonnet] — *D4, BR-NAV-02, BR-NAV-42, NFR-ST-01* - New `web/src/components/NavigationBar/ChevronIcon.tsx`: inline SVG, 12 x 12, `aria-hidden="true"`, `focusable="false"`, `stroke="currentColor"`, no fill, no external asset. Rotation (180 degrees) is driven by a `data-open` attribute on the parent button (CSS on the button in the consumers) with `transition: transform 0.3s`, and `_motionReduce: { transition: 'none' }` (state still shows via the rotated end position; BR-NAV-42). - `web/src/components/NavigationBar/NavLink.tsx`: prop type `React.ComponentProps & { sectionCurrent?: boolean }`; `sectionCurrent` sets `data-section-current` (omitted when false) and the existing underline selector list gains `&[data-section-current]::after`. Existing callers unchanged; `sectionCurrent` is not forwarded to the DOM as an unknown prop. - Small test `NavLink.test.tsx` (new, †): with `sectionCurrent` the `data-section-current` attribute is set and there is **no** `aria-current`; without the prop nothing changes; the underline rule list contains the attribute selector (use `test/cssRules.ts` if it fits). + - Result: ChevronIcon.tsx, NavLink.sectionCurrent, NavLink.test.tsx (4 tests). -- [ ] **Step 9 — `NavSubmenu` (desktop)** [sonnet] — *FR-ST-10, BR-NAV-20..29, BR-NAV-40, BR-NAV-42, BR-NAV-43, NFR-ST-01* +- [x] **Step 9 — `NavSubmenu` (desktop)** [sonnet] — *FR-ST-10, BR-NAV-20..29, BR-NAV-40, BR-NAV-42, BR-NAV-43, NFR-ST-01* - New `web/src/components/NavigationBar/NavSubmenu.tsx` with the props of the FD (`item`, `id`, `open`, `pathname`, `transparent`, `toggleRef`, `dispatch`). Structure: wrapper `Box` (`position: relative; display: flex; align-items: center`, `ref` for `useDismiss`, `onBlur` → `focusLeave` when `event.relatedTarget` is a Node outside the wrapper, otherwise ignored, BR-NAV-25) containing: parent `NavLink to={item.to} activeOptions={{ exact: true, includeSearch: false }} sectionCurrent={isSectionCurrent(item, pathname)} mr={0}`; toggle `chakra.button type="button"` 44 x 44 px, `aria-expanded`, `aria-controls={id}`, `aria-label={`Submenu ${item.label}`}`, `color: currentColor`, `data-open`, `ChevronIcon`, white `--focus-ring-color` while `transparent`, `onClick → dispatch({type:'toggleSubmenu'})`; panel `div#id` (`id = submenu-${item.to.slice(1)}` is built by the caller) with `ul` of `li > RouterLink` (`PanelLink`: `textStyle="eyebrow"`, explicit `color="fg"`, `min-height 44px`, flex centred, `px 5`, `_hover bg paper.alt`, `_currentPage` colour `accent.deep` plus a 2 px accent bar on the left, `activeOptions={{ exact: true, includeSearch: false }}`, `onClick → dispatch({type:'linkChosen'})`). Panel: `position: absolute; top: calc(100% + 0.75rem); left: 1rem; min-width: 15rem`, `bg="bg" color="fg"`, 1 px `line` border, `shadow="panel"`, `zIndex` above the header content. Closed: `visibility: hidden; opacity: 0; transform: translateY(-6px); pointer-events: none`; open: visible, opacity 1, no translate; transition `opacity, transform, visibility` 0.3 s `smooth`; `_motionReduce: { transition: 'none' }`. The panel stays in the DOM (BR-NAV-28). `useDismiss(ref, open, reason => dispatch(reason === 'escape' ? { type: 'escape', focusInside: ref.current?.contains(document.activeElement) ?? false } : { type: 'outside' }))`. No hover handlers (BR-NAV-21), no arrow-key handlers (BR-NAV-27), no `role="menu"`/`menuitem`. - Test file `NavSubmenu.test.tsx` is written in Step 13. Self-check here: renders with the real `mainNav` item in `renderWithProviders` without errors. + - Result: NavSubmenu.tsx as specified; renders with the real mainNav item (NavSubmenu.test.tsx, Step 13). -- [ ] **Step 10 — `MobileNavGroup` and `MobileNav`** [sonnet] — *FR-ST-10, BR-NAV-30..36, BR-NAV-40, BR-NAV-42, risk 6* +- [x] **Step 10 — `MobileNavGroup` and `MobileNav`** [sonnet] — *FR-ST-10, BR-NAV-30..36, BR-NAV-40, BR-NAV-42, risk 6* - New `web/src/components/NavigationBar/MobileNavGroup.tsx` (props per FD: `item`, `id` = `mobile-group-${slug}`, `open`, `pathname`, `dispatch`): `Flex` row with the parent `RouterLink` (heading font 1.9rem, `activeOptions={{ exact: true, includeSearch: false }}`, `color="ink"`, accent colour when `isSectionCurrent`, `onClick → linkChosen`) and a 44 x 44 px chevron `button` (`aria-expanded`, `aria-controls`, `aria-label="Submenu …"`, `data-open`); sub-list wrapper as a grid with `gridTemplateRows: open ? '1fr' : '0fr'`, inner `overflow: hidden`, `visibility: open ? 'visible' : 'hidden'` (on close the visibility transition is delayed by the duration so the collapse is seen; BR-NAV-36), `_motionReduce: { transition: 'none' }`; `ul` indented 1.25rem; sub-links heading font 1.4rem, `min-height 44px`, `color="ink"`, `_currentPage={{ color: 'accent.deep' }}`, `activeOptions` as above, `onClick → linkChosen`. - `web/src/components/NavigationBar/MobileNav.tsx`: props become `{ id; open; groupOpen; pathname; dispatch }` (the `onClose` prop is removed). Outer box: add `overflowY="auto"` and `overscrollBehavior="contain"`, drop `justifyContent="center"`; inner `Box` with `marginBlock="auto"` around the `nav` (centres short content, scrolls tall content from the top, BR-NAV-34); `pb` unchanged. Keep the body scroll lock effect. The keydown effect now calls `dispatch({ type: 'escape', focusInside })` with `focusInside` = the active element is inside the menu box or is the hamburger (`[data-testid="nav-menu-toggle"]` or an optional `toggleRef`; pick one and note it). `_motionReduce: { transition: 'none' }` on the clip-path reveal (BR-NAV-42). Plain items: `onClick → linkChosen`; items with `hasChildren` render `MobileNavGroup`. + - Result: MobileNavGroup.tsx new; MobileNav.tsx changed. Hamburger recognised for the Escape focus return by aria-controls === menu id (no test id in production code). -- [ ] **Step 11 — `NavigationBar` wiring** [sonnet] — *FR-ST-10, BR-NAV-02, 22, 23, 26, 30..33, domain-entities (events), I1–I4* +- [x] **Step 11 — `NavigationBar` wiring** [sonnet] — *FR-ST-10, BR-NAV-02, 22, 23, 26, 30..33, domain-entities (events), I1–I4* - `web/src/components/NavigationBar/NavigationBar.tsx`: replace `useState(open)`/`closeMenu` by `useReducer(navMenuReducer, initialNavMenuState)`. `isDesktop` stays from `useBreakpointValue({ base: false, lg: true }, { ssr: false })` (may be `undefined` on the first render; treat as `false`); an effect dispatches `viewport` when it changes. `pathname` from `useRouterState({ select: s => s.location.pathname })` (extend the existing `isHome` selector: `isHome = pathname === '/'`). Effect: dispatch `routeChanged` when `pathname` changes after the first render (ref with the previous value; do not close on mount). Focus effect: when `state.focusRequest` is set, focus `hamburgerRef` or `submenuToggleRef` and dispatch `focusHandled`. - Desktop list: `chakra.li` per item; `hasChildren(item) ? : `. Pass `transparent={!isSolid}`. Hamburger: `onClick → dispatch({ type: 'toggleMenu', inSection: isSectionCurrent(parentItem, pathname) })` where `parentItem` is the `mainNav` entry with children; `aria-expanded={state.menuOpen}`, names "Menu openen"/"Menu sluiten" and `data-testid="nav-menu-toggle"` unchanged; add the ref. ``. Ids: `submenu-soorten-fotoshoots` and `mobile-group-soorten-fotoshoots` derived from `item.to.slice(1)`. No context. Keep all existing header styling. - Check: the hamburger's `aria-controls="mobile-nav"` stays valid. + - Result: NavigationBar uses useReducer; effects for viewport, routeChanged (skips first render) and focusRequest. hamburger aria-controls='mobile-nav' unchanged. -- [ ] **Step 12 — Footer exact matching** [sonnet] — *D4, BR-NAV-01, FR-ST-10 (footer menu unchanged)* +- [x] **Step 12 — Footer exact matching** [sonnet] — *D4, BR-NAV-01, FR-ST-10 (footer menu unchanged)* - `web/src/components/Footer/Footer.tsx`: in the `footerNav.map`, the `RouterLink` gets `activeOptions={{ exact: true, includeSearch: false }}`. No visible change. - `web/src/components/Footer/Footer.test.tsx`: add (existing tests stay): on `/soorten-fotoshoots/newborn` the footer's "Soorten fotoshoots" link has no `aria-current` and the other links neither; on `/soorten-fotoshoots` and `/soorten-fotoshoots/` it has `aria-current="page"`; on `/portfolio?shoot=newborn` the Portfolio link still has `aria-current="page"` (regression of the `includeSearch: false` choice); axe still clean. + - Result: Footer links use exact + includeSearch false; Footer.test.tsx +5 tests (11 total). ### Tests (components and real app) -- [ ] **Step 13 — Component tests** [sonnet] — *NFR-ST-01, NFR-ST-06 (PBT-10), BR-NAV-20..36, BR-NAV-40..43* +- [x] **Step 13 — Component tests** [sonnet] — *NFR-ST-01, NFR-ST-06 (PBT-10), BR-NAV-20..36, BR-NAV-40..43* - `web/src/components/NavigationBar/NavigationBar.test.tsx` (extend; **update** the existing "toont het hoofdmenu in de vaste volgorde" test: the `Hoofdmenu` nav now also holds the five panel links, so assert the top-level order and, separately, the five children; keep the logo and hamburger tests): toggle has accessible name "Submenu Soorten fotoshoots", `aria-expanded` false then true, `aria-controls` points to an existing element; click, Enter and Space open it (`userEvent`); **hover does not open it** (BR-NAV-21); Escape closes it and focus is on the toggle when focus was inside, and not moved when focus was elsewhere (BR-NAV-23); a pointer down outside closes without moving focus; Tab from the last panel link closes it (BR-NAV-25); window blur without `relatedTarget` does not close; closed panel links are not reachable by role query nor by Tab (BR-NAV-28), open ones are; choosing a link closes it; toggling twice returns to closed with focus on the toggle; no element with `role="menu"`; axe with the panel closed and open (`axeResults`); at `/` the toggle uses `currentColor` and the panel has an own `bg` (computed or recipe check as far as jsdom allows; the visual part is Step 17); on `/soorten-fotoshoots/newborn` the newborn panel link has `aria-current="page"`, the parent link has none but `data-section-current`; on `/soorten-fotoshoots` the parent has both. - New `NavSubmenu.test.tsx`: the component alone with a fake `dispatch` (events emitted for toggle click, escape with `focusInside` true/false, outside pointer down, focusout to outside, link click → `linkChosen`; nothing emitted for hover and arrow keys). - New `MobileNav.test.tsx` (mount `NavigationBar` with the breakpoint forced below `lg`: mock `useBreakpointValue` or set `window.matchMedia` as the existing tests do; check how `NavigationBar.test.tsx`/`setup.ts` handle it first): hamburger opens the menu; the group starts collapsed on `/contact` and expanded on `/soorten-fotoshoots` and `/soorten-fotoshoots/gezin` (BR-NAV-31); the chevron flips `aria-expanded` and the visibility of the sub-links (BR-NAV-36); a collapsed sub-link is not found by role; choosing a link (parent or sub) closes the whole menu; Escape closes it and focus goes to the hamburger (BR-NAV-33); the box has `overflow-y: auto` and the inner centring wrapper exists (BR-NAV-34, as far as jsdom reports styles); body overflow locked while open and restored after; axe open (group collapsed and expanded); reduced-motion rule present via `test/cssRules.ts` if it can read emotion rules, otherwise leave to Step 17. - Reduced motion (BR-NAV-42): assert the generated rules contain a `prefers-reduced-motion: reduce` block with `transition: none` for panel, mobile group and mobile reveal where the helper allows; otherwise record "verified in the browser, Step 17". + - Result: NavigationBar.test.tsx 27 tests, NavSubmenu.test.tsx 13, MobileNav.test.tsx 18. Reduced-motion rules verified via cssRulesFor (panel, chevron, mobile box, group). Added test helper src/test/navViewport.ts (matchMedia stub plus a style element that applies the lg display rules, because jsdom ignores @media). -- [ ] **Step 14 — Real-app test** [sonnet] — *D4, BR-NAV-01..04, BR-NAV-26, BR-NAV-32, FR-ST-10* +- [x] **Step 14 — Real-app test** [sonnet] — *D4, BR-NAV-01..04, BR-NAV-26, BR-NAV-32, FR-ST-10* - New `web/src/navSubmenu.test.tsx` using `renderApp(path)` (real route tree, so the shoot routes exist; unit 1's `renderApp.tsx` is read only): on each of the five shoot pages the matching panel link has `aria-current="page"`, the parent "Soorten fotoshoots" in the header has none but `data-section-current`, the footer link has none (the breadcrumb is unit 2 and is not asserted here); on `/soorten-fotoshoots` parent and footer have `aria-current="page"` and no panel link has; on `/portfolio` no panel link and no section mark; trailing slash path behaves like the plain path as pinned in Step 2; the case variant `/soorten-fotoshoots/Newborn` behaves as recorded in Step 2. - Route change closes an open submenu: open it, `router.navigate({ to: '/portfolio' })` → closed. Click a panel link → page changes, panel closed, focus on `main#main` (`useRouteFocus`, BR-NAV-26). Mobile: open the menu, `router.history.back()` / navigate → menu closed (BR-NAV-32, the fixed browser-back gap); opening on a shoot page expands the group. Resize across `lg` (mock the breakpoint) closes the menu that no longer exists. Every shoot name in the panel matches `shootTypes` (single source). - Check the whole suite for new name collisions: panel/sub-list links (e.g. "Newborn") may now match `getByRole('link', { name })` queries in other test files. Fix collisions in **unit 3 files** only; a collision in a unit 2 or unit 1 test is reported to the orchestrator with file and line, not edited. + - Result: navSubmenu.test.tsx 18 tests (real app). Case variant /soorten-fotoshoots/Newborn: page renders, no link has aria-current, parent keeps data-section-current. Needs FakeIntersectionObserver stub as in app.test.tsx. ### Verification -- [ ] **Step 15 — Unit verification gate** [haiku] — *NFR-ST-06, NFR-ST-05 (SECURITY-10/11/15), NFR-ST-01* +- [x] **Step 15 — Unit verification gate** [haiku] — *NFR-ST-06, NFR-ST-05 (SECURITY-10/11/15), NFR-ST-01* - In `web/`, in this order, stopping at the first failure and reporting the output: `pnpm lint`; `pnpm format:check`; `pnpm exec tsc`; `pnpm test` (this runs `vitest run --coverage`: all green, the 100 % thresholds for `src/lib/**` pass, note test count, seed and coverage of the new files); `git diff --stat -- package.json pnpm-lock.yaml` is empty. - Greps (report matches): `dangerouslySetInnerHTML`, `target="_blank"`, `role="menu"`, `menuitem`, `onMouseEnter`/`onHover`/`_hover` opening logic, `console.` and `debugger` in the unit 3 files (expected: none). - File boundary check: `git status --short` shows no change in `src/components/shoots`, `src/content`, `src/sitePages.ts`, `src/routes`, `src/test/arbitraries.ts`, `src/theme.ts`, `LAYOUT.md` made by this unit (compare with the list from Step 1; unit 2's own changes are not unit 3's concern but must not be edited here). + - Result: lint, format:check, tsc green; pnpm test: 106 files / 801 tests pass, seed 1525740974; all unit 3 lib files 100% (shootNavItems, navCurrent, navMenuState). The only coverage threshold failure is a unit 2 file in src/lib with 0% coverage (…ectionPath.ts, no test yet), not unit 3. package.json and pnpm-lock.yaml unchanged. Greps: no dangerouslySetInnerHTML, role=menu (only in a comment), menuitem, hover handlers, console, debugger in unit 3 files; target=_blank only in the pre-existing Footer socials; _hover only styles a background. No changes by unit 3 to the forbidden files. -- [ ] **Step 16 — Bundle check (D5 gate)** [haiku] — *NFR-ST-03, BR-NAV-50, D5* +- [x] **Step 16 — Bundle check (D5 gate)** [haiku] — *NFR-ST-03, BR-NAV-50, D5* - `pnpm build` (runs `tsc && vite build`). Record the `dist/assets/index-*.js` line (raw / gzip) and compare with Step 1: **gzip increase must be at most 2.5 kB** (expected about 1.7 kB). Verify: the ten shoot photos are still emitted as files (`.jpg`/`.webp` count equals Step 1's; `grep -c "data:image" dist/assets/index-*.js` not higher than Step 1); a Newborn-only page string ("Uit eerdere newbornshoots") is still only in the `newborn-*.js` chunk; the shoot page chunks are still separate files. - **STOP rule**: if the gzip increase exceeds 2.5 kB, or images got inlined, stop the unit, do not switch to the D5 alternative (a separate `{ id, name }` list), and report the numbers to the orchestrator; that alternative changes the content model and needs the user. + - Result: pnpm build green. index-Dtz2mqhH.js 536.68 kB raw / 152.58 kB gzip vs baseline 528.98 / 150.69: +7.70 kB raw, +1.89 kB gzip (limit 2.5 kB). 50 .jpg (same as Step 1), 0 .webp, data:image count 1 (same as Step 1), Newborn-only string only in newborn-*.js, five shoot chunks separate; the separate shootTypes chunk is gone (now in main), dist/assets 119 files vs 121. Delta may include small unit 2 changes made since Step 1. -- [ ] **Step 17 — Real-browser check: 1024 px fit, transparent header, short phone** [sonnet] — *BR-NAV-41, BR-NAV-29, BR-NAV-34, BR-NAV-42, BR-NAV-43, risk 7* +- [x] **Step 17 — Real-browser check: 1024 px fit, transparent header, short phone** [sonnet] — *BR-NAV-41, BR-NAV-29, BR-NAV-34, BR-NAV-42, BR-NAV-43, risk 7* + - **Result (110/110 checks pass, no `mx` fallback needed)**: script `scratchpad/nav-browser-check/navCheck.mjs` (puppeteer-core 24.43.1 + Chrome headless, vite preview on 4173 of the unit-2 Step 22 build; PNGs in the same folder; server stopped, port free). Desktop at 1024/1100/1280 on `/`, `/portfolio`, `/soorten-fotoshoots/newborn`: the five top-level items sit in one row (vertical centres within 1 px; the submenu `li` is 44 px high and the others ~35 px, so their `top` differs by 5 px by design), real item span 711 px (180..890 at 1024; ul client width 848/918/1090), `scrollWidth == clientWidth`, logo right edge 87-94 px well left of the first item, no hamburger, no horizontal page overflow. Open panel: visible, opacity 1, inside viewport (e.g. 553..793 x 80..318 at 1024), background `rgb(250, 247, 242)` (solid); on `/` unscrolled the chevron is white `rgb(255,255,255)` over the transparent header, after scrolling 200 px the header is solid and the open panel is unchanged. Keyboard: Tab reaches toggle, Enter opens, Tab walks Newborn, Zwangerschap, Gezin, Loveshoot, Portretten, Escape returns focus to the toggle and closes, Tab out of the last link closes. Reduced motion: panel, mobile box and group `transition-duration` 0s. Mobile 375x480 and 360x560 (touch): collapsed group on `/` fits without scrolling (scrollHeight == clientHeight, 414/494 px; first link not cut off, Contact fully visible); expanded on `/soorten-fotoshoots/newborn` the box scrolls (632 px content in 414/494 px), first link below the box top at scroll 0, scrolling reaches Contact, hamburger stays topmost at its centre, Escape closes with focus on the hamburger, browser back closes the menu. Note: two script criteria were corrected to match the intent (same row = vertical centres, not `top`; collapsed group is expected to fit, not scroll). - Tooling: Playwright is **not** in `node_modules` and no dependency may be added. `puppeteer-core` 24.43.1 is present as a transitive dependency of `@lhci/cli` (`web/node_modules/.pnpm/puppeteer-core@24.43.1_*/node_modules/puppeteer-core`) and Chrome is installed at `C:\Program Files\Google\Chrome\Application\chrome.exe` (Edge also at `C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`). Write a throwaway script **outside the repo** (`\navCheck.mjs`, run with `node`), loading puppeteer-core via `createRequire` from that pnpm path and launching Chrome headless with `executablePath` (no `--no-sandbox` unless needed). Do not commit the script and do not touch `package.json`. - Serve the Step 16 build with `pnpm preview` on a **free port that is not 4173** (e.g. `pnpm exec vite preview --port 4180 --strictPort`), because port 4173 is shared and claimed by the orchestrator for Lighthouse; stop the server afterwards. - Measurements (print numbers, save PNGs to the scratchpad): at viewport widths 1024, 1100 and 1280 (height 800): on `/`, `/portfolio` and `/soorten-fotoshoots/newborn`, for the `nav[aria-label="Hoofdmenu"] > ul`: the five top-level `li` all share the same `getBoundingClientRect().top` (no wrapping), `scrollWidth <= clientWidth`, the rightmost nav item's right edge is below the hamburger/right container's left edge and the logo's right edge is below the first item's left edge (no overlap); record the real widths against the FD estimate (about 715 px of 848 px). Then open the submenu by clicking the toggle: panel `visibility: visible`, panel bounding box inside the viewport, panel `getComputedStyle` background is not transparent; on `/` before scrolling (transparent header) the screenshot shows a readable solid panel, and the toggle chevron is white; after scrolling 200 px the header is solid and the open panel is unchanged. Keyboard run: focus the toggle with Tab, Enter opens, Tab walks five links, Escape returns to the toggle, Tab out of the last link closes. Emulated `prefers-reduced-motion: reduce` (`page.emulateMediaFeatures`): the panel `transition-duration` is `0s` and the mobile reveal too. @@ -142,7 +159,8 @@ This plan is the **single source of truth** for code generation of unit 3. Steps - **Fallback if the nav does not fit at 1024 px (no wrapping allowed, BR-NAV-41)**: reduce the `NavLink` margin from `mx="4"` to `mx={{ base: '4', lg: '3' }}`-style at `lg` only (change in `NavLink.tsx`, unit 3 file; the desktop-only hamburger is hidden at `lg` anyway), rebuild, re-measure and record both numbers. If it still does not fit, stop and report; do not change the labels or the layout structure. - If this script cannot run on the machine (Chrome missing, launch failure), hand the same checklist to the orchestrator as a manual check at 1024 and 1100 px and record that in the summary; do not install anything. -- [ ] **Step 18 — Lighthouse (needs the orchestrator's port 4173 claim)** [haiku] — *NFR-ST-03, BR-NAV-50, D5, NFR-ST-01* +- [x] **Step 18 — Lighthouse (needs the orchestrator's port 4173 claim)** [haiku] — *NFR-ST-03, BR-NAV-50, D5, NFR-ST-01* + - **Result (regression gate passed; absolute mobile `/` still below 0.8, orchestrator decision as foreseen)**: build = unit-2 Step 22 build (units 1+2+3, `index-C65n6UdK.js` 536.65 kB / 152.56 kB gzip; +7.67 kB raw / +1.87 kB gzip vs baseline 528.98 / 150.69, limit 2.5 kB). Command: `pnpm exec vite preview --port 4173 --strictPort` (baseline: `--outDir /dist-baseline`) and `pnpm exec lhci collect --config=/lh-home/lhci-home.cjs` (`/` only, mobile preset, 3 runs, filesystem upload), run twice per build, alternating (current, baseline, current, baseline) in one session. Mobile `/` performance: current batch 1 = 0.69, 0.78, 0.78 (median 0.78; 0.69 is a TBT 496 ms outlier), batch 2 = 0.78, 0.75, 0.76 (median 0.76); baseline batch 1 = 0.77, 0.75, 0.77 (median 0.77), batch 2 = 0.77, 0.77, 0.75 (median 0.77). Pooled medians (six runs each): current 0.77, baseline 0.77, so no regression above 0.02; all below the 0.8 budget, as on master (0.78). LCP 4.3 s both. Accessibility, best practices, SEO 1.0 on every run. Full set (`lhci autorun`, mobile and desktop, one run per URL, same build): see Step 23 of the unit-2 plan; a11y/BP/SEO 1.0 on all indexed pages, mobile and desktop; the closed panel causes no axe failure. Preview server stopped, port 4173 free. - **Precondition**: the orchestrator has claimed port 4173 for this worktree (the port is shared with the other session). Do not start before that confirmation; do not kill other processes on the port. - In `web/` with the Step 16 build: `pnpm preview` (port 4173), then run the mobile config three times for `/` only (e.g. `pnpm exec lhci collect --url=http://localhost:4173/ --numberOfRuns=3 --config=lighthouserc.cjs` or the repo's usual `lhci autorun`; report the exact command used) and take the **median performance score**. In the same session run the **baseline** `\dist-baseline` from Step 1 the same way (`pnpm exec vite preview --outDir \dist-baseline --port 4173 --strictPort` after stopping the first server) so the two numbers are comparable; machine noise is about 0.01–0.02. - Then the full set as `pnpm lighthouse` does (mobile and desktop config, all indexed paths and the 404): report per page performance and the accessibility/best-practices/SEO values (all must stay 1.0 on every indexed page; the nav is on every page, and the closed panel must not create an axe-type failure), and which budgets fail. Known baseline failures from the unit-1 summary: mobile `/` 0.76 (budget 0.8; master 0.78) and `/contact` 0.85 (budget 0.9). @@ -150,10 +168,10 @@ This plan is the **single source of truth** for code generation of unit 3. Steps ### Documentation -- [ ] **Step 19 — Code summary** [haiku] — *traceability for FR-ST-10, NFR-ST-01/03/06* +- [x] **Step 19 — Code summary** [haiku] — *traceability for FR-ST-10, NFR-ST-01/03/06* - New `aidlc-docs/features/shoot-type-pages/construction/navigation-submenu/code/code-summary.md`, in the structure of unit 1's summary: status of the steps; files created/modified (paths); interfaces (`NavItem.children`, `hasChildren`, `shootNavItems`, `isItemCurrent`/`isSectionCurrent`, `NavMenuState`/`NavMenuEvent`/`navMenuReducer`, `useDismiss`, component props); requirement and business-rule traceability table (FR-ST-10, NFR-ST-01/03/06, BR-NAV-01..50, D4, D5 → files and tests); test counts and coverage of the new `lib` files; the seed; the Step 2 truth table (trailing slash, case, query) and the `includeSearch: false` decision; the Step 16 bundle numbers (before/after/delta against the 2.5 kB limit); the Step 17 measured widths at 1024/1100/1280 px, panel and mobile findings, and whether the `mx` fallback was needed; the Step 18 Lighthouse numbers (median `/` mobile, baseline vs after, other pages, failing budgets); deviations from the design (below); open points for the orchestrator (no focus trap in the mobile menu, BR-NAV-35; existing desktop `NavLink` boxes ~35 px high, outside this unit; case-insensitive route vs exact `aria-current`); the Security Baseline and PBT compliance tables of this plan with the final status. -- [ ] **Step 20 — Reverse-engineering lines** [haiku] — *project convention (own route/component lines only)* +- [x] **Step 20 — Reverse-engineering lines** [haiku] — *project convention (own route/component lines only)* - Edit only the lines of this unit in `aidlc-docs/_shared/reverse-engineering/`, minimal in-place edits, no rewriting of other lines (these files already carry unit 1's uncommitted edits, and unit 2 hands its lines to the orchestrator): `code-structure.md` — the `NavigationBar/*` line (add `NavSubmenu`, `MobileNavGroup`, `ChevronIcon`, `NavLink.sectionCurrent`, `MobileNav` scrolling), the `navigation.ts` line (`children`, `hasChildren`), new lines for `lib/{shootNavItems,navCurrent,navMenuState}.ts`, `hooks/useDismiss.ts`, `test/navArbitraries.ts`, and the component dependency diagram edge (`navigation` → `shootNavItems`/`shootTypes`) if the file contains one; `architecture.md` — one line on the menu state reducer in `NavigationBar` and the D5 consequence (shoot type data in the main bundle, with the measured delta); `api-documentation.md` — only if it lists `navigation.ts` or hook exports; otherwise no change and say so. Before editing, read the current text of each file and use `Edit` on exact lines; if the file has changed in a way that conflicts, stop and report instead of merging. ## Traceability diff --git a/aidlc-docs/features/shoot-type-pages/construction/plans/shoot-page-ui-code-generation-plan.md b/aidlc-docs/features/shoot-type-pages/construction/plans/shoot-page-ui-code-generation-plan.md index 1729423..d1b2077 100644 --- a/aidlc-docs/features/shoot-type-pages/construction/plans/shoot-page-ui-code-generation-plan.md +++ b/aidlc-docs/features/shoot-type-pages/construction/plans/shoot-page-ui-code-generation-plan.md @@ -37,14 +37,16 @@ This plan is the **single source of truth** for code generation of unit 2. Steps ### Setup -- [ ] **Step 1 — Baseline and checks of the inputs** [haiku] — *NFR-ST-06, NFR-ST-07, BR-SP-30a, FD Q1/Q2* +- [x] **Step 1 — Baseline and checks of the inputs** [haiku] — *NFR-ST-06, NFR-ST-07, BR-SP-30a, FD Q1/Q2* + - **Result (done, no edits)**: tsc, lint and vitest green (90 files / 595 tests). `pnpm exec vite build`, the routeTree diff comparison and any Lighthouse number skipped on purpose (unit-3 agent owns builds and port 4173). (a) `MOSAIC_MIN_PHOTOS` = 2. (b) photo selection matches domain-entities.md § 3. (c) git status shows no unit-3 path changed yet. - In `web/`: `pnpm exec tsc`, `pnpm lint`, `pnpm test` (all must be green; note the test count and the logged fast-check seed). `pnpm exec vite build` and `git diff --exit-code src/routeTree.gen.ts` against the working tree before the build (record the diff state first with `git diff --stat src/routeTree.gen.ts`, then compare after: it must not change). - Report only, no edits unless a check fails: (a) `MOSAIC_MIN_PHOTOS` in `src/lib/shootPageView.ts` is `2` (Q2 = A: no code change); (b) the photo selection in `src/content/shootPages/*.ts` equals the table in domain-entities.md § 3 (verified at planning time: Newborn stories `shoots/newborn.jpg`, `f41a8700`, `f41a7176`, `f41a1916` and three mosaic photos; Zwangerschap/Gezin story 2 = landscape portfolio photo, story 3 = portrait portfolio photo, story 4 text only, no mosaic; Loveshoot/Portret story 1 only, no mosaic); (c) none of the unit-3 paths listed above has been changed by this unit (`git status --short`, informational: unit 3 may be changing them). - If (b) differs, stop and report to the orchestrator instead of editing content (the decision belongs to FD Q1). ### OG images (user approval required) -- [ ] **Step 2 — Produce the five OG crops, then STOP for user approval** [sonnet] — *SEO-ST-05, BR-SP-80, BR-SP-81, FD Q7 = A, SECURITY-10, SECURITY-13* +- [x] **Step 2 — Produce the five OG crops, then STOP for user approval** [sonnet] — *SEO-ST-05, BR-SP-80, BR-SP-81, FD Q7 = A, SECURITY-10, SECURITY-13* + - **Result (done; waiting for user approval of the crops)**: five JPEGs 1200 x 630 written to `web/public/` (unreferenced, uncommitted; approved by the user as produced), 91-100 KB, quality 75-90, no EXIF/ICC (re-encoded from a fresh bitmap by System.Drawing, script in the scratchpad `og-crops/make-crops.ps1`). Contact sheet: scratchpad `og-crops/og-contact-sheet.png`. Gezin has no baby in the crop (faces prioritised); Loveshoot and Portret are upscaled 1.415x. - **No image tool is installed** (no Pillow, no ImageMagick; `convert` on the PATH is Windows' own `convert.exe`; no `sharp` in the repo). Use a throw-away PowerShell script with `System.Drawing` (or Pillow installed with `pip install --target Pillow`), kept **outside the repository** (scratchpad). **No new dependency in `web/`.** - Produce `web/public/og-newborn.jpg`, `og-zwangerschap.jpg`, `og-gezin.jpg`, `og-loveshoot.jpg`, `og-portret.jpg`: JPEG, exactly **1200 × 630**, at most about 100 KB (the existing ones are 54–92 KB; lower the quality in steps from about 85 until it fits), sRGB, progressive not required. Sources (domain-entities.md § 5, corrected where the planning check found a conflict): | Shoot | Source | Source size | Crop | @@ -61,80 +63,95 @@ This plan is the **single source of truth** for code generation of unit 2. Steps ### Generators and pure logic -- [ ] **Step 3 — Generators (append only)** [sonnet] — *NFR-ST-06, PBT-07* +- [x] **Step 3 — Generators (append only)** [sonnet] — *NFR-ST-06, PBT-07* + - **Result**: Four generators appended to `src/test/arbitraries.ts` (plus one import line at the top for `shootPageView`); smoke-checked by the tests of Steps 4-7, 11, 12. - `src/test/arbitraries.ts`, appended at the end, no existing definition changed: `imageWithOrientation` (a `ContentImage` whose width and height are drawn around the 1.2 threshold, including exactly 1.2 and values just below and above), `mosaicCount` (integers −3 to 12), `timelineSteps` (1 to 8 steps `{ id, title, text }` with hostile strings: ``, `<`, `>`, `&`, very long words, empty-looking whitespace), and `shootPageViewArb` (a `ShootPageView` built by `shootPageView` from `shootPageContent(id, reuse)`, `shootPageShared`, a unique list of shoot types and packages, so stories 0–6, photos present or not and FAQ present or not all occur; it must never return `undefined`). - Reuse `shootPageContent`, `shootPageShared`, `contentImage`, `storyBlock`, `faqItem`, `richText`, `uniqueShootTypes`, `anyPackage`; no duplicated generators. Smoke-check each new generator inside the tests of Steps 4–7 (no separate test file). -- [ ] **Step 4 — headingId and readMoreLabel** [sonnet] — *BR-SP-72, BR-SP-64, FR-ST-09, SECURITY-15, PBT-03* +- [x] **Step 4 — headingId and readMoreLabel** [sonnet] — *BR-SP-72, BR-SP-64, FR-ST-09, SECURITY-15, PBT-03* + - **Result**: `headingId.ts`, `readMoreLabel.ts` + tests, 100 % coverage. - Depends on: Step 3. - New `src/lib/headingId.ts`: `headingId(prefix: string, id: string): string` = `${prefix}-${id}` with the whole result lower-cased and every character outside `a-z 0-9 - _` replaced by `-` (BR-SP-72); pure, never throws for any string. The caller adds `-title` where needed. - New `src/lib/readMoreLabel.ts`: `readMoreLabel(shoot: ShootType): string` = ``Lees meer over de ${shoot.shootLabel.toLowerCase()}`` (domain-entities.md § 6). - Tests `headingId.test.ts`, `readMoreLabel.test.ts`: examples (the five real ids, spaces, uppercase, ``, empty string, non-ASCII); the five real labels ("Lees meer over de newbornshoot", "… zwangerschapsshoot", "… gezinsshoot", "… loveshoot", "… portretshoot") are unique; PBT per business-rules.md § 3: `headingId` output only `a-z0-9-_`, deterministic, never throws for arbitrary and hostile strings (invariant); `readMoreLabel` starts with "Lees meer over de " and is unique for any `uniqueShootTypes` list with unique `shootLabel` (invariant). 100 % coverage. -- [ ] **Step 5 — mosaicLayout** [sonnet] — *FR-ST-05, BR-SP-30b, BR-SP-31, BR-SP-35, PBT-03* +- [x] **Step 5 — mosaicLayout** [sonnet] — *FR-ST-05, BR-SP-30b, BR-SP-31, BR-SP-35, PBT-03* + - **Result**: `mosaicLayout.ts` + test, 100 % coverage. The first tile is `1 / 3` x `1 / 3` for counts 2 to 4 only; the table gives count 1 (never shown) `1 / 5`, which the property respects. - Depends on: Step 3. - New `src/lib/mosaicLayout.ts`: `MOSAIC_MAX_PHOTOS = 4`, `MosaicTile` (`column`, `row`, `wide`, `phoneRatio`) and `mosaicLayout(count: number): MosaicTile[]` exactly per the table in domain-entities.md § 2 (0 or below none; 1 total-but-unused; 2, 3, 4; 5 or more = the layout for 4). Non-integer or `NaN` input: treat as no tiles (fail safe). - Test `mosaicLayout.test.ts`: examples for 0, 1, 2, 3, 4, 5, −1; PBT over `mosaicCount` per business-rules.md § 3: `[]` for ≤ 0; exactly `min(count, 4)` tiles; desktop cells pairwise disjoint and, for 2 to 4, covering all eight cells of the 4 × 2 grid (compute cells from the `column`/`row` strings in the test); first tile always `1 / 3` × `1 / 3`; number of non-wide tiles even; pure (same output twice) (invariant). 100 % coverage. -- [ ] **Step 6 — storyLayout** [sonnet] — *FR-ST-03, BR-SP-11, BR-SP-12, BR-SP-13, BR-SP-14, BR-SP-40, PBT-03* +- [x] **Step 6 — storyLayout** [sonnet] — *FR-ST-03, BR-SP-11, BR-SP-12, BR-SP-13, BR-SP-14, BR-SP-40, PBT-03* + - **Result**: `storyLayout.ts` + test, 100 % coverage. - Depends on: Step 3. - New `src/lib/storyLayout.ts`: `StoryLayout` (`tone`, `spacing`, `reverse`, `priority`, `media?: { aspectRatio: '3 / 2' | '4 / 5'; mediaSize: 'half' | 'medium' }`) and `storyLayout(stories: readonly StoryBlock[]): StoryLayout[]` (domain-entities.md § 2): tone `paper` for even index and `alt` for odd, spacing `flushTop` for index 0, `reverse` for odd index, `priority` only for index 0 and only with an image, `media` absent without an image; orientation: `width >= 1.2 * height` → `3 / 2` and `half`, otherwise `4 / 5` and `medium`. Export the threshold as a named constant. - Test `storyLayout.test.ts`: examples with the real Newborn stories (4/5 + medium for the portrait photos, 3/2 + half for `f41a8700`) and a text-only list (Loveshoot); boundary examples (exactly 1.2, 1.19); empty list; PBT over `storyBlock`/`imageWithOrientation` per business-rules.md § 3: tone and `reverse` alternate with the index; `priority` only at index 0 and only with an image; no image means no `media`; ratio `3 / 2` exactly when width ≥ 1.2 × height and `mediaSize` matches (invariant). 100 % coverage. -- [ ] **Step 7 — shootPageBands** [sonnet] — *BR-SP-70, BR-SP-71, BR-SP-73, FR-ST-02..08, PBT-03* +- [x] **Step 7 — shootPageBands** [sonnet] — *BR-SP-70, BR-SP-71, BR-SP-73, FR-ST-02..08, PBT-03* + - **Result**: `shootPageBands.ts` + test, 100 % coverage. - Depends on: Steps 3, 6. - New `src/lib/shootPageBands.ts`: `SectionBand` (`id`: `` `story-${string}` `` | `'process'` | `'photos'` | `'faq'` | `'offer'` | `'closing'`, `tone`, `position`) and `shootPageBands(view: ShootPageView): SectionBand[]`: stories in index order, then process, `photos` iff `view.photos`, `faq` iff `view.faq`, offer, closing; positions consecutive from 0, tone `paper` at even and `alt` at odd positions (the intro is not a band, it is `paper`). Story tones must equal `storyLayout(...)[i].tone` (the same rule; a test pins it). - Test `shootPageBands.test.ts`: examples with the real views (Newborn: 4 stories + process + photos + faq + offer + closing = 9 bands; Loveshoot: no photos = 8) and a view without FAQ; PBT over `shootPageViewArb` per business-rules.md § 3: tones alternate strictly starting with `paper`; ids in canonical order; length = stories + 1 + [photos] + [faq] + 2; no id twice; story band tone equals `storyLayout` tone (invariant). 100 % coverage. ### Shared components -- [ ] **Step 8 — Additive changes: PageIntro, MediaText, CallToAction** [sonnet] — *BR-SP-05, BR-SP-12, BR-SP-63, FR-ST-02, FR-ST-03, FR-ST-08, NFR-ST-02* +- [x] **Step 8 — Additive changes: PageIntro, MediaText, CallToAction** [sonnet] — *BR-SP-05, BR-SP-12, BR-SP-63, FR-ST-02, FR-ST-03, FR-ST-08, NFR-ST-02* + - **Result**: `PageIntro` (`titleId`, `breadcrumb`), `MediaText` (`medium`), `CallToAction` (`tone`) with tests; existing tests unchanged and green. - `src/components/PageIntro/PageIntro.tsx`: new optional `titleId?: string` (id of the h1; the section gets `aria-labelledby={titleId}`) and `breadcrumb?: ReactNode` (rendered above the eyebrow with `mb` 6 on phones and 7 from `md`). Existing callers render byte-identically (no `aria-labelledby`, no wrapper). Test: one test pins the existing markup (`container.innerHTML` equal to the output without the new props, e.g. with a stored expected structure), one for `titleId`/`breadcrumb`. - `src/components/MediaText/MediaText.tsx`: `mediaSize` accepts `'medium'` in addition to `'half'` and `'small'`: photo column up to 30rem (480 px), text up to 36rem centred in the rest, laid out exactly as `small` does (reuse its branch; add a `MEDIUM_MEDIA = '30rem'` constant next to `SMALL_MEDIA`). Detail-image behaviour unchanged. Add the `medium` test to `MediaText.test.tsx`; existing tests unchanged and green. - `src/components/CallToAction/CallToAction.tsx`: new optional `tone?: 'paper' | 'alt'`, default `'alt'`, passed to `PageSection`. Add one test; existing tests green. The overview page keeps its current output. - Update the doc comments of the three components. Touch no other file. -- [ ] **Step 9 — Breadcrumb** [sonnet] — *FR-ST-02, BR-SP-01..04, NFR-ST-01, SEO-ST-04* +- [x] **Step 9 — Breadcrumb** [sonnet] — *FR-ST-02, BR-SP-01..04, NFR-ST-01, SEO-ST-04* + - **Result**: `Breadcrumb` + test (separators are `li[aria-hidden]` as in BR-SP-02). Tests render at the page's own path: at `/` the Home link is correctly current. - New `src/components/Breadcrumb/Breadcrumb.tsx` (+ test): props `label: string`, `items: readonly BreadcrumbItem[]` (type import from `@/lib/shootPageView`), optional `data-testid`. Markup per frontend-components.md § 2: `nav[aria-label]` > `ol` > `li` per item; links through the router `Link` (`RouterLink`) with `activeOptions={{ exact: true }}` (so only the page itself can carry `aria-current`), accent.deep text, permanent underline, `minH` 44 px, inline-flex centred; the last item a `span[aria-current="page"]` in `ink`; between items a decorative `li[aria-hidden="true"]` "/"; `fontSize` 0.875rem, `color` `ink.soft`, centred, wrap, gap 2. No items: renders nothing; one item: only the current page. - Tests: examples (3 items, 1 item, none); PBT for 1 to 5 generated items per business-rules.md § 3: exactly the last item is a non-link with `aria-current="page"`, the others are links in order, separators number items − 1 and are `aria-hidden` (component property, few runs); axe. -- [ ] **Step 10 — ProcessIcons** [sonnet] — *FR-ST-04, BR-SP-23, BR-SP-74, NFR-ST-01* +- [x] **Step 10 — ProcessIcons** [sonnet] — *FR-ST-04, BR-SP-23, BR-SP-74, NFR-ST-01* + - **Result**: `ProcessIcons` + test. - New `src/components/shoots/ProcessIcons/ProcessIcons.tsx` (+ test): `processIcons: Record JSX.Element>` with the six SVGs from domain-entities.md § 4 (envelope, calendar with heart, coin, camera, sliders, picture): `viewBox="0 0 24 24"`, `fill="none"`, `stroke="currentColor"`, `stroke-width="1.5"`, round caps and joins, `aria-hidden="true"`, `focusable="false"`, 24 × 24; shapes verbatim from design E (also in the domain-entities table). The `Record` type makes a missing id a compile error. - Test: one icon per `PROCESS_STEP_ORDER` id, each `svg` is `aria-hidden`, not focusable, has no ``; axe. -- [ ] **Step 11 — ProcessTimeline** [sonnet] — *FR-ST-04, BR-SP-20..26, NFR-ST-01, NFR-ST-02* +- [x] **Step 11 — ProcessTimeline** [sonnet] — *FR-ST-04, BR-SP-20..26, NFR-ST-01, NFR-ST-02* + - **Result**: `ProcessTimeline` + test. Deviation: the subgrid fallback is not expressible through Chakra style props (a nested `@supports` rule is dropped), so `gridTemplateRows: subgrid` from `lg` stands without a fallback (all current browsers support subgrid). - Depends on: Step 10 (only for the page test; the component takes icons as props). - New `src/components/ProcessTimeline/ProcessTimeline.tsx` (+ test): props `steps: readonly { id: string; title: string; text: string; icon?: ReactNode }[]`, `tone?: 'paper' | 'alt'` (default `paper`), `data-testid`. `Reveal` > `ol[role="list"]` > `li` per step (marker `div[aria-hidden]` with the icon, line segments `span[aria-hidden]`, text block with `h3` and `p`), layout exactly as frontend-components.md § 2 (below `lg`: grid `3.5rem | 1fr`, column gap 5, vertical line, list capped at `34rem` centred; from `lg`: grid of `repeat(<n>, minmax(0, 1fr))` by `auto 3.5rem auto` rows with `subgridRows` and fallback, text above for even indexes and below for odd, horizontal line through the markers from the first to the last centre). Markers hide the line with the band colour (`tone`); last marker filled (`accent.deep`, white icon), others outlined; no numbers; DOM order = `steps` order. Zero steps: renders nothing. Breakpoints via responsive props (`lg`), no pixel literals. - If a CSS feature is not expressible with Chakra style props (subgrid with fallback), use a style prop `gridTemplateRows` with the `@supports`-free fallback in the same value list (`1fr 3.5rem 1fr` as the base, `subgrid` from `lg`); report if impossible. - Tests: examples (6 steps; 1 step; 0 steps; last marker filled; an alternation check that does not depend on class names, e.g. a `data-text-position="above|below"` attribute set from the index parity); PBT for 1 to 8 `timelineSteps` per business-rules.md § 3: one `li` per step in input order, one h3 per `li`, every icon wrapper `aria-hidden`, no digit-only text added by the component (component property, few runs); axe. -- [ ] **Step 12 — PhotoMosaic** [sonnet] — *FR-ST-05, BR-SP-30b..35, BR-SP-41, BR-SP-42, NFR-ST-03* +- [x] **Step 12 — PhotoMosaic** [sonnet] — *FR-ST-05, BR-SP-30b..35, BR-SP-41, BR-SP-42, NFR-ST-03* + - **Result**: `PhotoMosaic` + test. - Depends on: Step 5. - New `src/components/PhotoMosaic/PhotoMosaic.tsx` (+ test): props `images: readonly ContentImage[]`, `data-testid`. Takes the first `MOSAIC_MAX_PHOTOS`; `ul[role="list"]` as a grid (below `md` two columns; from `md` four columns by two rows of `clamp(12rem, 22vw, 18.75rem)`; gap `gridGap`) with `Reveal as li` (delay `index * 0.08`) per tile with the tile's `column`/`row` (from `md`) or span 2 when `wide` (below `md`), `aspectRatio` = `phoneRatio` below `md` and `auto` from `md`, `position: relative`, `overflow: hidden`, `bg paper.deep`, and a `DeferredImage` absolutely filling the cell (`objectFit: cover`, intrinsic width/height attributes kept by `DeferredImage`). Not interactive (Q3 = A): no link, no button, no hover effect. Empty list: renders nothing. - Tests: examples with 2, 3, 4, 5 and 0 photos (tile counts 2, 3, 4, 4, none; alt texts present; no `a`/`button` inside); PBT for 2 to 6 generated images per business-rules.md § 3: `min(n, 4)` `img` elements with the given alt texts in order (component property); axe. -- [ ] **Step 13 — FaqList** [sonnet] — *FR-ST-06, BR-SP-50..53, NFR-ST-01, SECURITY-11* +- [x] **Step 13 — FaqList** [sonnet] — *FR-ST-06, BR-SP-50..53, NFR-ST-01, SECURITY-11* + - **Result**: `FaqList` + test. jsdom and user-event do not turn Enter/Space on a `summary` into the click that toggles `details` (the browser does); the test checks focusability, `summary` as first child, and the toggle on activation (click) instead. - New `src/components/FaqList/FaqList.tsx` (+ test): props `items: readonly FaqItem[]`, `data-testid`. `Box` with a top hairline (`sand`) > per item one native `details` (bottom hairline) > `summary` (flex, space-between, `minH` 44 px, `py` 5, heading font 1.25rem, `ink`, `cursor pointer`, `listStyle none`, WebKit marker hidden, visible focus ring from the theme `focusRing` token with offset) holding the question and a decorative `svg[aria-hidden]` plus icon whose vertical stroke is hidden by CSS under `details[open]` (Chakra `css`/`_open`-style selector; no state), followed by `RichParagraph` for the answer with `mb` 6 and `maxW` 680 px. **No item has the `open` attribute** (Q5 = C); no React state, no JavaScript handler. Answers stay in the DOM when closed. Question text is the disclosure label, not a heading. Zero items: renders nothing. - Tests: examples (3 items all closed at load, answers in the DOM, answer links present as links); keyboard: focus the `summary`, press Enter and Space with `userEvent` and check `open`; if jsdom does not toggle `details` on activation, diagnose the cause first (do not skip the assertion silently) and test the attribute through the documented jsdom behaviour or report; PBT for 0 to 6 `faqItem`s per business-rules.md § 3: one `details` per item, every answer text present in the DOM, no `details` with `open` (component property); axe. -- [ ] **Step 14 — PackageBlock** [sonnet] — *FR-ST-07, BR-SP-60..62, NFR-ST-01, SECURITY-11* +- [x] **Step 14 — PackageBlock** [sonnet] — *FR-ST-07, BR-SP-60..62, NFR-ST-01, SECURITY-11* + - **Result**: `PackageBlock` + test. - Depends on: Step 8 (`MediaText` `small` already exists; no `medium` needed here). - New `src/components/PackageBlock/PackageBlock.tsx` (+ test): props `titleId`, `eyebrow`, `title`, `image: ContentImage`, `frameColor?`, `pkg?: PricingPackage`, `onRequest: { price: string; text: string }`, `note?: string`, `children` (the actions), `data-testid`. `MediaText mediaSize="small"` (aspect `1 / 1`, deferred image, `frameColor`; **no priority**); text column: `Eyebrow`, `h2#titleId` (`sectionTitle`), price paragraph (heading font, 2.25rem, `accent.deep`, `formatPrice(pkg.price)` or `onRequest.price`), then the features `ul` (rows with a `sand` top border, the last also a bottom border; `role="list"`) when `pkg` exists or the `onRequest.text` paragraph (`ink.soft`) otherwise, the actions row (flex, wrap, gap 3 / 7, centred) with `children`, and the `note` paragraph (0.875rem, `mt` 5) when given. The variant is decided by `pkg` presence only, never by a shoot id. - Tests: Newborn-style package (price `€ 185` with the non-breaking space from `formatPrice`, all features listed, note shown), on-request variant (price text and text paragraph, no list), no note, extra actions rendered; axe. ### Shoot page parts -- [ ] **Step 15 — StoryBlocks** [sonnet] — *FR-ST-03, BR-SP-10..14, BR-SP-40, BR-SP-41, NFR-ST-03* +- [x] **Step 15 — StoryBlocks** [sonnet] — *FR-ST-03, BR-SP-10..14, BR-SP-40, BR-SP-41, NFR-ST-03* + - **Result**: `StoryBlocks` + test. - Depends on: Steps 4, 6, 8. - New `src/components/shoots/StoryBlocks/StoryBlocks.tsx` (+ test): props `stories`, `frameColor`, `idPrefix`. One band per story, tone, spacing and media from `storyLayout`. With media: `PageSection` (`labelledBy`) > `MediaText` (`image`, `aspectRatio`, `mediaSize`, `reverse`, `priority`, `frameColor`) whose text column holds `Eyebrow`, `h2` (`sectionTitle`, id `headingId(idPrefix, story.id) + '-title'`) and a stack of `RichParagraph`s (gap 4, `ink.soft`). Without media (Q4 = A): the same `PageSection` (width `narrow`, tone and spacing from the layout) with the same text column inside a `Reveal`, `maxW` 36rem, centred; no `MediaText`, no frame, no empty column. `data-testid="story-<id>"`. Only index 0 may be a priority image; all other photos are deferred (BR-SP-40/41). Empty list: renders nothing. - Tests: Newborn stories (4 sections, each named by its h2, first image is not lazy and carries `fetchpriority="high"`, the others lazy and deferred, tones alternate), Loveshoot stories (1 photo, 3 text-only bands), hostile story ids (spaces, uppercase) give valid `aria-labelledby` targets that exist in the DOM; axe. -- [ ] **Step 16 — ShootBlock "Lees meer"** [sonnet] — *FR-ST-09, BR-SP-64, Q6 = A, NFR-ST-01* +- [x] **Step 16 — ShootBlock "Lees meer"** [sonnet] — *FR-ST-09, BR-SP-64, Q6 = A, NFR-ST-01* + - **Result**: `ShootBlock` link first in the row; `ShootBlock.test` and `ShootList.test` extended; `app.test.tsx` overview tests green. - Depends on: Step 4. - `src/components/shoots/ShootBlock/ShootBlock.tsx`: new first link in the links row: `Link variant="underline" asChild` with `linkStyle` > `RouterLink to={shootPagePath(shoot.id)}` with the visible text `readMoreLabel(shoot)` and `data-testid={`shoot-${shoot.id}-readmore`}`; no `aria-label` (the visible text already differs per shoot). Props unchanged; `article` id, the other two links and their `aria-label`/test ids unchanged. Update the file comment. - `ShootBlock.test.tsx` and `ShootList.test.tsx`: link text and `href` per shoot (all five), the link comes first, unique accessible names across the list, existing anchors and links still present, axe. Existing assertions stay unchanged and green; check the overview tests in `app.test.tsx` still pass. -- [ ] **Step 17 — ShootPage assembly** [sonnet] — *FR-ST-02..08, BR-SP-70, BR-SP-71, BR-SP-73, BR-SP-74, NFR-ST-01, NFR-ST-03, SEO-ST-04* +- [x] **Step 17 — ShootPage assembly** [sonnet] — *FR-ST-02..08, BR-SP-70, BR-SP-71, BR-SP-73, BR-SP-74, NFR-ST-01, NFR-ST-03, SEO-ST-04* + - **Result**: `ShootPage` assembled; test extended. The primary buttons use `Box asChild css={linkButton recipe}` around the router's own `Link` (as `PriceCard`), because `LinkButton` loses the typed `search`. The intro and the first story are both paper on purpose (the story is `flushTop`); from the first story on the bands alternate. Cross-check with design E (by reading): section order, eyebrows and tone alternation match; the five-section order intro, 4 stories, process, photos, FAQ, offer, closing is the same. - Depends on: Steps 7, 8, 9, 10, 11, 12, 13, 14, 15. - `src/components/shoots/ShootPage/ShootPage.tsx`: props `{ view }` unchanged; no content imports; no state. Composition in the order of `shootPageBands(view)` (frontend-components.md § 3): (1) `PageIntro` with `eyebrow`, `title`, `titleId="intro-title"`, `breadcrumb=<Breadcrumb label items/>`, text `view.intro.text`; (2) `StoryBlocks` (`frameColor = view.shoot.frameColor`, `idPrefix="story"`); (3) `PageSection id="zo-werkt-het" labelledBy="process-title" tone` with `SectionHeading` (eyebrow, h2 id `process-title`, lead) and `ProcessTimeline` (steps mapped with `processIcons[step.id]`, `tone` passed; an id without an icon yields none); (4) if `view.photos`: `PageSection id="impressie" labelledBy="photos-title" tone` with a head (eyebrow, h2 `photos-title`, "Bekijk meer {photosLabel}" link when `portfolioLink`, at least 44 px high, wrapping below the heading on narrow screens) and `PhotoMosaic`; (5) if `view.faq`: `PageSection id="vragen" labelledBy="faq-title" tone` in two columns from `lg` (eyebrow, h2 `faq-title`, `RichParagraph` of the lead | `FaqList`), stacked below; (6) `PageSection id="pakket" labelledBy="offer-title" tone` with `PackageBlock` (`titleId="offer-title"`, `view.offer` data, `note = depositNote`, actions: package variant "Boek dit pakket" (`bookLink`, accent `LinkButton`) + "Eerst een vraag stellen" (`askLink`, underline link); on-request variant one primary button `onRequest.linkLabel` to `bookLink`); (7) `CallToAction` (`titleId="closing-title"`, `tone` = next band tone, rich-text lead via `RichParagraph`, accent `LinkButton` to `closing.link`). `data-testid`s: `shoot-page`, `shoot-breadcrumb`, `story-<id>`, `process-timeline`, `photo-mosaic`, `faq-list`, `package-block`, `shoot-closing`. The portfolio link uses the same `shootPortfolioLink` data from the view. - Update `ShootPage.test.tsx` (the unit-1 test stays valid; extend it): one h1, h2 per section, h3 per step, no level skipped (heading outline for Newborn with mosaic and FAQ, Loveshoot without mosaic, and a view without FAQ built by clearing `faq` in a copy of the content), every `aria-labelledby` target exists, section anchors `zo-werkt-het`, `impressie`, `vragen`, `pakket` exist when the section does, adjacent bands never share a tone (read from the `PageSection` backgrounds or a `data-tone` attribute added for the test), axe. @@ -142,7 +159,8 @@ This plan is the **single source of truth** for code generation of unit 2. Steps ### Route-level tests -- [ ] **Step 18 — `src/shootPages.test.tsx` (page structure and links)** [sonnet] — *FR-ST-02..09, NFR-ST-01, NFR-ST-06, SEO-ST-04, PBT-10* +- [x] **Step 18 — `src/shootPages.test.tsx` (page structure and links)** [sonnet] — *FR-ST-02..09, NFR-ST-01, NFR-ST-06, SEO-ST-04, PBT-10* + - **Result**: `src/shootPages.test.tsx` (23 tests at this step): outline, sections, breadcrumb, `aria-current` in `main` only, offer variants, priority photo, overview links and anchors, one-link-per-shoot facet. - Depends on: Steps 16, 17. - New `src/shootPages.test.tsx` using `renderApp` and `expectShell` from `src/test/renderApp.tsx` (copy the `vi.mock` and `beforeEach`/`afterEach` stubs that `app.test.tsx` needs for the same pages; mocks are per test file). Per shoot (`it.each` over `shootTypes`): heading outline (one h1; h2 per section; h3 = six steps), sections present or omitted as the data says (Newborn: mosaic with 3 tiles; Zwangerschap, Gezin, Loveshoot, Portret: no `#impressie`, no mosaic heading; FAQ and process always), the breadcrumb ("Kruimelpad", Home, Soorten fotoshoots, current page with `aria-current="page"`, three items), no `aria-current` anywhere in `main` other than the breadcrumb's last item (see the integration note in Step 26), package variant for Newborn/Zwangerschap/Gezin ("Boek dit pakket" `href` `/contact?pakket=<id>`, price from `formatPrice`) and "Prijs op aanvraag" for Loveshoot/Portret (no price, one primary button, `href` `/contact`), deposit note under the actions in both variants, closing band different tone from the package band, the first story photo is not lazy (priority) and no other photo has `loading="eager"`, axe on each of the five pages. - Overview page: for every shoot a "Lees meer over de … " link to `/soorten-fotoshoots/<id>` that is first in the row and has a unique accessible name; the `article` anchors (`#newborn` … `#portret`) and the old links are still there (FR-ST-09). @@ -151,26 +169,30 @@ This plan is the **single source of truth** for code generation of unit 2. Steps ### OG wiring (only after the user approved the crops in Step 2) -- [ ] **Step 19 — Wire the OG images into the registry** [haiku] — *SEO-ST-05, BR-SP-80, BR-SP-81, FR-ST-12* +- [x] **Step 19 — Wire the OG images into the registry** [haiku] — *SEO-ST-05, BR-SP-80, BR-SP-81, FR-ST-12* + - **Result**: Done after the user approved the crops. Five `ogImage` entries in `sitePages.ts`; `app.test.tsx`: one assertion now reads `sitePages[path].ogImage!.path`. - **Blocked until the orchestrator confirms the user approved the five crops from Step 2.** Do not start without that confirmation in the hand-over text. - `src/sitePages.ts`: add to each of the five shoot entries, directly after `indexed: true`, `ogImage: { path: '/og-<id>.jpg', width: 1200, height: 630, alt: '<alt of the source photo, Dutch>' }` (alts as listed in Step 2, as approved). Existing entries and the `PageMeta` type unchanged. - `src/app.test.tsx` (**not in unit 2's ownership table; one assertion**): the shoot-page head test currently expects `${siteUrl}/og-image.jpg` with the comment "The default image until unit 2 gives the pages their own" (around lines 519–522). Change it to `${siteUrl}${sitePages[path].ogImage!.path}` (or the equivalent that does not hardcode five names) and update the comment. Nothing else in the file; unit 3 does not edit this file (its tests live in `navSubmenu.test.tsx`). - Run `pnpm exec tsc`, `pnpm lint`, `pnpm exec vitest run src/app.test.tsx src/seo.test.ts src/sitemap.test.ts`. -- [ ] **Step 20 — OG registry consistency test** [sonnet] — *SEO-ST-05, BR-SP-80, FR-ST-12, PBT-10* +- [x] **Step 20 — OG registry consistency test** [sonnet] — *SEO-ST-05, BR-SP-80, FR-ST-12, PBT-10* + - **Result**: OG registry consistency added to `src/shootPages.test.tsx` (file read via `import.meta.dirname`, SOF marker parsed from the bytes). The `og:image` meta facet is covered by the changed `app.test.tsx` assertion (not duplicated). - Depends on: Step 19. - In `src/shootPages.test.tsx`: for every `ShootTypeId` (finite set, example-based): `sitePages[shootPagePath(id)].ogImage` is defined, `path` is `/og-<id>.jpg`, width 1200, height 630, alt non-blank, and `web/public/og-<id>.jpg` exists (read with `node:fs`, resolved from the test file location); no two `ogImage.path` values in `sitePages` are equal across the whole registry; the file is a JPEG of 1200 × 630 (read the SOF0/SOF2 marker from the bytes in a small test helper, no image dependency) and at most 150 KB. Also assert the `og:image` meta of each shoot page in the app equals `siteUrl + ogImage.path` (one `renderApp` per shoot, or reuse the facet of `app.test.tsx` if it is enough; do not duplicate it). ### Documentation -- [ ] **Step 21 — LAYOUT.md and layout conventions** [haiku] — *FR-ST-13, BR-SP-90* +- [x] **Step 21 — LAYOUT.md and layout conventions** [haiku] — *FR-ST-13, BR-SP-90* + - **Result**: `LAYOUT.md` section and `.ai/layout-conventions.md` updated. Root files are outside `web/`'s `prettier --check .`; a direct check flags LAYOUT.md (not checked for a pre-existing baseline). - `LAYOUT.md`: new section **"Shoot page"** placed directly after "Types of shoots" (before "Contact"), the `block-beta` diagram from frontend-components.md § 9 (A Intro, B–E Story 1–4, F Process timeline, G Photos, H FAQ, I Package, J Book; style lines A–G as in the template, H `#9b6bb5`/`#745088`, I `#4cc3e0`/`#3992a8`, J `#8cb83f`/`#698a2f`, same `color:#fff,font-size:16px,width:400px,height:125px,stroke-width:2px`). Add a one-line note under the diagram that Photos is left out below the minimum number of photos. "Types of shoots", Shell and the other sections stay unchanged. - `.ai/layout-conventions.md`: append the three `style` lines H, I, J to the template list and change the sentence "extend with a new letter using the same formula if an 8th block is ever needed" to name the ten letters (A–J) ("if an 11th block is ever needed"). No other change. - Check the new colours: stroke = fill × 0.75 (H 155,107,181 → 116,80,136; I 76,195,224 → 57,146,168; J 140,184,63 → 105,138,47), all three distinct from A–G. Run `pnpm exec prettier --check` on the two files if prettier covers them (repo root files may be outside `web/`; if not, skip). ### Verification -- [ ] **Step 22 — Unit verification** [haiku] — *NFR-ST-01, NFR-ST-03, NFR-ST-05, NFR-ST-06, NFR-ST-07* +- [x] **Step 22 — Unit verification** [haiku] — *NFR-ST-01, NFR-ST-03, NFR-ST-05, NFR-ST-06, NFR-ST-07* + - **Result (all green)**: lint, format:check, tsc clean; `pnpm test` 113 files / 883 tests pass, seed 1191455385, coverage thresholds pass (incl. `isShootSectionPath.ts`); `pnpm build` clean; `audit:deps` passes (seroval@1.7.3 in lockfile), `audit:dev` exit 0 (22 dev advisories, non-blocking by NFR-SEC-05, as on master). `package.json`, lockfile, `securityHeaders.ts`, `routeTree.gen.ts`: no diff. Bundle: `index-C65n6UdK.js` 536.65 kB / 152.56 kB gzip vs unit 1 528.98 / 150.69 (+7.67 kB raw, +1.87 kB gzip; the shoot-nav data now sits in main via unit 3 D5). "Kruimelpad", "Zo werkt het", `process-title`, `faq-title`, `offer-title` only in `-shootPageSources-*.js` (route chunk, not in main); "Uit eerdere newbornshoots" only in `newborn-*.js`. Five OG JPEGs in `dist/` (91-100 KB each). Greps: `dangerouslySetInnerHTML` only in `StructuredData`; the one `console.error` is the pre-existing `ErrorPage.tsx`; no new e-mail/mailto; no placeholders; no hex/rgb in new components; `DRAFT(CON-ST-03)` count 98 (unchanged). - Depends on: Steps 1–21 (Step 20 only if the user approved the crops; otherwise run it without 19/20 and **run Steps 19, 20 and this step's test, build and bundle items again** after the approval). - In `web/`, each on its own and all green: `pnpm lint`; `pnpm format:check`; `pnpm exec tsc`; `pnpm test` (coverage thresholds 100 % for `src/lib/**`, `src/seo.ts`, `src/sitemap.ts`; note test count, files and the fast-check seed; the unit-1 baseline is 90 files / 595 tests); `pnpm build`; `pnpm audit:deps` and `pnpm audit:dev` (the branch was fast-forwarded to master 1416497, which contains the seroval patch from PR #12 — lockfile resolves `seroval@1.7.3` — so `audit:deps` must pass; a failure is reported). Lighthouse is Step 23, not part of this step. - `git diff --exit-code web/pnpm-lock.yaml web/package.json web/config/securityHeaders.ts` (no new dependency, headers unchanged; SECURITY-04/10). `git diff --stat web/src/routeTree.gen.ts` must show no change from unit 2's work (`pnpm exec vite build` regenerates it; no route files added). @@ -179,6 +201,7 @@ This plan is the **single source of truth** for code generation of unit 2. Steps - If any item fails: diagnose the root cause, fix it (or hand a [sonnet] fix step to the orchestrator), re-run. Do not weaken a test or threshold. - [ ] **Step 23 — Lighthouse (mobile and desktop)** [haiku] — *NFR-ST-01, NFR-ST-03, FR-ST-12, SEO-ST-04* + - **Result (2026-10-30), NOT green (left unchecked): mobile performance budgets fail on four pages; everything else passes.** Build = Step 22 build with units 1+2+3; `pnpm lighthouse` equivalent (`lhci autorun`, then `lhci autorun --config=lighthouserc.desktop.cjs`, 1 run per URL; the mobile command exits 1 on the assertions, desktop exits 0). Accessibility, best practices 1.0 on all 12 URLs mobile and desktop; SEO 1.0 on all indexed pages (0.58 `/bestaat-niet`, 0.69 `/privacyverklaring` are the expected noindex values). Mobile performance (unit-1 Step 24 in brackets): `/` 0.75 (0.76) FAIL budget 0.8; `/contact` 0.87 (0.85) FAIL budget 0.9; `/over-mij` 0.87; `/portfolio` 0.91; `/soorten-fotoshoots` 0.85; newborn 0.86 (0.90); zwangerschap 0.85 (0.90); gezin 0.84 (0.90) FAIL budget 0.85; loveshoot 0.83 (0.90) FAIL budget 0.85; portret 0.85 (0.90); `/privacyverklaring` 0.90; `/bestaat-niet` 0.92. Re-measure of the two failing shoot pages, 3 runs each: gezin 0.85, 0.85, 0.85 (passes, borderline), loveshoot 0.83, 0.83, 0.83 (fails consistently). Desktop performance 0.99-1.00 on every page (shoot pages 0.99; budget 0.9). `/` and `/contact` fail on master too (0.78 / 0.87). Diagnosis (loveshoot, gezin): the first story photo is not the bottleneck (153 / 117 KB, load time 15-24 ms); LCP is 3.8 / 3.7 s with a render delay of ~2.9-3.0 s, FCP is 2.6 s on every page, i.e. the image is only painted after the main bundle (536 kB, +1.9 kB gzip from unit 3) has run, which matches the `photoPagePaths` comment in `lighthouserc.cjs`; the shoot pages dropped 0.05-0.07 from the shell-only unit-1 numbers because the page now renders the first story through `MediaText`/`Reveal` inside the lazy route chunk. Mitigations for the orchestrator, in the plan's order, none applied: (1) first story without the fade-in (`Reveal` removed for story 0), (2) fewer pixels for the first photo by capping its column, (3) report and keep the known limit. Preview port 4173 released (the lhci server stopped itself; free). - Depends on: Step 22 green. **Needs the orchestrator's claim of port 4173** (`pnpm preview --port 4173 --strictPort`; `--strictPort` fails fast when taken: then wait, never change the port) and a quiet machine (performance is blocking locally). Do not start without the orchestrator's go. - In `web/`: `pnpm lighthouse` (runs `lhci autorun` for mobile and then `lhci autorun --config=lighthouserc.desktop.cjs`; indexed pages incl. the five shoot pages). Run it **after Step 19** so the OG images and final markup are measured (if the crops are still unapproved, run now and re-run later). - Expected: accessibility, best practices and SEO **1.0** on every page, mobile and desktop; the five shoot pages performance ≥ **0.85 mobile** (goal 0.9) and ≥ **0.9 desktop**. Unit 1 left the shoot pages at 0.90 mobile / 100 desktop with the shell only and the baseline failures `/` 0.76 (budget 0.8) and `/contact` 0.85 (budget 0.9) that also fail on master; report current numbers for all pages next to those. @@ -195,7 +218,8 @@ This plan is the **single source of truth** for code generation of unit 2. Steps - `architecture.md`: one line on the shoot page composition (`shootPageBands` → sections) next to unit 1's Outlet line; no diagram restructure. - No timestamp refresh. **Note**: the application design says the orchestrator writes both units' lines after both are done; this step follows the instruction for this plan (unit 2 writes its own lines). If the orchestrator prefers to write them, hand the lines over instead via the code summary and skip the edit. -- [ ] **Step 26 — Integration facet after unit 3 (orchestrator, conditional)** [sonnet] — *BR-SP-03, NFR-ST-01, NFR-ST-06* +- [x] **Step 26 — Integration facet after unit 3 (orchestrator, conditional)** [sonnet] — *BR-SP-03, NFR-ST-01, NFR-ST-06* + - **Result**: one `it.each` test per shoot added to `src/shootPages.test.tsx` (5 tests; file now 34 tests). Decision recorded (unit 3's final markup): the mobile menu (`#mobile-nav`) is a sibling of the `header`, not inside it, and both menus carry the shoot's own link as current, so the whole page has exactly three `aria-current="page"` elements: the breadcrumb's last item (main), the header submenu link and the mobile-menu sub-link (both `href` = the shoot path; only one of the two menus is shown at a time). The rule is therefore "exactly one in main, exactly one in each menu, none in the footer, the parent 'Soorten fotoshoots' links (header and mobile menu) and the footer link never current". Full suite after the change: lint, format:check clean; 113 files / 888 tests pass, seed 1757660570. Record the decision in the code summary (Step 24). - **Run only when unit 3 is built in the same worktree.** Currently the header link "Soorten fotoshoots" and the footer link receive TanStack's fuzzy `aria-current="page"` on a shoot page (unit 3 fixes both, application-design D4), so a **whole-page** "exactly one `aria-current="page"`" assertion cannot pass in unit 2 alone; Step 18 therefore checks `main` only. - Add to `src/shootPages.test.tsx` (unit 2's file) one test per shoot: in the whole document exactly one element has `aria-current="page"` **and** it is the breadcrumb's last item or the nav's exact-page child (decide with unit 3's final markup; the intended rule is "only the exact page", D4), then re-run the unit's tests. If both header submenu child and breadcrumb mark the same page, the rule is "at most one in `main` and at most one in `header`", not one overall; record the decision in the code summary. diff --git a/aidlc-docs/features/shoot-type-pages/inception/requirements/requirements.md b/aidlc-docs/features/shoot-type-pages/inception/requirements/requirements.md index e14a087..80ac583 100644 --- a/aidlc-docs/features/shoot-type-pages/inception/requirements/requirements.md +++ b/aidlc-docs/features/shoot-type-pages/inception/requirements/requirements.md @@ -114,6 +114,10 @@ Text alternative: each shoot page runs from the intro with breadcrumb through fo - New section **"Shoot page"** (one generic diagram for all five shoots) following [.ai/layout-conventions.md](../../../../../.ai/layout-conventions.md): A Intro (with breadcrumb), B–E Story 1–4, F Process timeline, G Photos, H FAQ, I Package, J Book. Letters H, I and J need new template colours (stroke = fill × 0.75), added to the template in `.ai/layout-conventions.md` as well. - "Types of shoots" keeps its blocks (the new links do not add a section). The Shell diagram does not show menu items, so it stays unchanged. +### FR-ST-14 404 inside the shoot section +- An unknown URL under `/soorten-fotoshoots/` (e.g. `/soorten-fotoshoots/niet-bestaande-shoot`; prefix match case-insensitive, like the router) shows the normal 404 page with two actions: **"Terug naar Soorten fotoshoots"** (link to `/soorten-fotoshoots`, `accent` variant, first) and **"Terug naar home"** (link to `/`, `outline`). Every other unknown URL keeps the single "Terug naar home" button. Title, text and `noindex` stay unchanged. +- Implemented in `NotFound` by reading the current pathname; no layout route is added (the route tree, the menu matching of unit 3 and the bundle stay unchanged). *Source: user request 2026-10-30, added during Code Generation* + --- ## SEO Requirements diff --git a/web/public/og-gezin.jpg b/web/public/og-gezin.jpg new file mode 100644 index 0000000..c30148c Binary files /dev/null and b/web/public/og-gezin.jpg differ diff --git a/web/public/og-loveshoot.jpg b/web/public/og-loveshoot.jpg new file mode 100644 index 0000000..c738555 Binary files /dev/null and b/web/public/og-loveshoot.jpg differ diff --git a/web/public/og-newborn.jpg b/web/public/og-newborn.jpg new file mode 100644 index 0000000..4852b30 Binary files /dev/null and b/web/public/og-newborn.jpg differ diff --git a/web/public/og-portret.jpg b/web/public/og-portret.jpg new file mode 100644 index 0000000..3f64f9b Binary files /dev/null and b/web/public/og-portret.jpg differ diff --git a/web/public/og-zwangerschap.jpg b/web/public/og-zwangerschap.jpg new file mode 100644 index 0000000..30bb0c9 Binary files /dev/null and b/web/public/og-zwangerschap.jpg differ diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx index 380696d..b2d5f7a 100644 --- a/web/src/app.test.tsx +++ b/web/src/app.test.tsx @@ -516,10 +516,13 @@ describe('shoot pages', () => { expect( document.head.querySelector('link[rel="canonical"]'), ).toHaveAttribute('href', `${siteUrl}${path}`); - // The default image until unit 2 gives the pages their own + // Each shoot page has its own preview image from the registry expect( document.head.querySelector('meta[property="og:image"]'), - ).toHaveAttribute('content', `${siteUrl}/og-image.jpg`); + ).toHaveAttribute( + 'content', + `${siteUrl}${sitePages[path].ogImage!.path}`, + ); expect(document.head.querySelector('meta[name="robots"]')).toBeNull(); const data = structuredData(); diff --git a/web/src/components/Breadcrumb/Breadcrumb.test.tsx b/web/src/components/Breadcrumb/Breadcrumb.test.tsx new file mode 100644 index 0000000..a678237 --- /dev/null +++ b/web/src/components/Breadcrumb/Breadcrumb.test.tsx @@ -0,0 +1,97 @@ +import { screen, within } from '@testing-library/react'; +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { cleanup } from '@testing-library/react'; +import type { BreadcrumbItem } from '@/lib/shootPageView'; +import { axeResults } from '@/test/axe'; +import { knownRoutePath } from '@/test/arbitraries'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import Breadcrumb from './Breadcrumb'; + +const three: BreadcrumbItem[] = [ + { label: 'Home', to: '/' }, + { label: 'Soorten fotoshoots', to: '/soorten-fotoshoots' }, + { label: 'Newborn', to: '/soorten-fotoshoots/newborn' }, +]; + +describe('Breadcrumb', () => { + it('shows links for all but the last item, which is the current page', async () => { + const { container } = await renderWithProviders( + <Breadcrumb label="Kruimelpad" items={three} data-testid="crumb" />, + { path: '/soorten-fotoshoots/newborn' }, + ); + const nav = screen.getByRole('navigation', { name: 'Kruimelpad' }); + expect(nav).toBe(screen.getByTestId('crumb')); + expect(within(nav).getAllByRole('link')).toHaveLength(2); + expect(screen.getByRole('link', { name: 'Home' })).toHaveAttribute( + 'href', + '/', + ); + expect( + screen.getByRole('link', { name: 'Soorten fotoshoots' }), + ).toHaveAttribute('href', '/soorten-fotoshoots'); + const current = screen.getByText('Newborn'); + expect(current.tagName).toBe('SPAN'); + expect(current).toHaveAttribute('aria-current', 'page'); + expect(nav.querySelectorAll('[aria-current]')).toHaveLength(1); + expect(nav.querySelectorAll('li[aria-hidden="true"]')).toHaveLength(2); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('shows only the current page for one item', async () => { + await renderWithProviders( + <Breadcrumb label="Kruimelpad" items={three.slice(2)} />, + ); + expect(screen.queryByRole('link')).toBeNull(); + expect(screen.getByText('Newborn')).toHaveAttribute( + 'aria-current', + 'page', + ); + expect( + document.querySelectorAll('li[aria-hidden="true"]'), + ).toHaveLength(0); + }); + + it('renders nothing without items', async () => { + const { container } = await renderWithProviders( + <Breadcrumb label="Kruimelpad" items={[]} />, + ); + expect(screen.queryByRole('navigation')).toBeNull(); + expect(container.querySelector('ol')).toBeNull(); + }); + + it('marks only the last item as current, and the links are not current on their own page (invariant)', async () => { + const items = fc.uniqueArray( + fc.record({ + label: fc + .string({ minLength: 1, maxLength: 12 }) + .filter((text) => text.trim() !== ''), + to: knownRoutePath, + }), + { selector: (item) => item.to, minLength: 1, maxLength: 5 }, + ); + const samples = fc.sample(items, { numRuns: 8 }); + for (const sample of samples) { + const { container } = await renderWithProviders( + <Breadcrumb label="Kruimelpad" items={sample} />, + { path: sample[sample.length - 1].to }, + ); + const entries = [...container.querySelectorAll('ol > li')].filter( + (li) => li.getAttribute('aria-hidden') !== 'true', + ); + expect(entries).toHaveLength(sample.length); + entries.forEach((li, index) => { + const last = index === sample.length - 1; + expect(li.querySelectorAll('a')).toHaveLength(last ? 0 : 1); + expect( + li.querySelectorAll('[aria-current="page"]').length, + ).toBe(last ? 1 : 0); + expect(li.textContent).toBe(sample[index].label); + }); + expect( + container.querySelectorAll('li[aria-hidden="true"]'), + ).toHaveLength(sample.length - 1); + cleanup(); + } + }); +}); diff --git a/web/src/components/Breadcrumb/Breadcrumb.tsx b/web/src/components/Breadcrumb/Breadcrumb.tsx new file mode 100644 index 0000000..5f4e2a5 --- /dev/null +++ b/web/src/components/Breadcrumb/Breadcrumb.tsx @@ -0,0 +1,80 @@ +import { Fragment } from 'react'; +import { Box, Flex, Text } from '@chakra-ui/react'; +import RouterLink from '@/components/RouterLink'; +import type { BreadcrumbItem } from '@/lib/shootPageView'; + +type BreadcrumbProps = { + // The name of the navigation landmark, e.g. "Kruimelpad" + label: string; + // The last item is the page itself + items: readonly BreadcrumbItem[]; + 'data-testid'?: string; +}; + +// The path to the current page (BR-SP-01..04): links for every item but the +// last, which is plain text marked as the current page. The links match +// exactly, so only the page itself can ever be "current". +export default function Breadcrumb({ + label, + items, + 'data-testid': testId, +}: BreadcrumbProps) { + if (items.length === 0) return null; + + return ( + <Box as="nav" aria-label={label} data-testid={testId}> + <Flex + as="ol" + wrap="wrap" + justify="center" + align="center" + gap={2} + fontSize="0.875rem" + color="ink.soft" + listStyle="none" + m={0} + p={0} + > + {items.map((item, index) => { + const last = index === items.length - 1; + // The list is static, so the index is a stable key + return ( + <Fragment key={index}> + <Box as="li"> + {last ? ( + <Text + as="span" + aria-current="page" + color="ink" + minH="2.75rem" + display="inline-flex" + alignItems="center" + > + {item.label} + </Text> + ) : ( + <RouterLink + to={item.to} + activeOptions={{ exact: true }} + color="accent.deep" + textDecoration="underline" + minH="2.75rem" + display="inline-flex" + alignItems="center" + > + {item.label} + </RouterLink> + )} + </Box> + {!last && ( + <Box as="li" aria-hidden="true"> + / + </Box> + )} + </Fragment> + ); + })} + </Flex> + </Box> + ); +} diff --git a/web/src/components/CallToAction/CallToAction.test.tsx b/web/src/components/CallToAction/CallToAction.test.tsx index d3d6263..0c31ca6 100644 --- a/web/src/components/CallToAction/CallToAction.test.tsx +++ b/web/src/components/CallToAction/CallToAction.test.tsx @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'; import LinkButton from '@/components/LinkButton'; import RichParagraph from '@/components/RichParagraph/RichParagraph'; import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; import { renderWithProviders } from '@/test/renderWithProviders'; import CallToAction from './CallToAction'; @@ -66,4 +67,28 @@ describe('CallToAction', () => { ); expect(screen.queryByRole('paragraph')).toBeNull(); }); + + it('takes the alt tone by default and the given tone otherwise', async () => { + const { unmount } = await renderWithProviders( + <CallToAction title="Vragen?" titleId="q" data-testid="cta"> + <LinkButton to="/">Contact</LinkButton> + </CallToAction>, + ); + const rules = (testId: string) => + cssRulesFor(screen.getByTestId(testId)).join(); + expect(rules('cta')).toContain('var(--slp-colors-paper-alt)'); + unmount(); + + await renderWithProviders( + <CallToAction + title="Vragen?" + titleId="q" + tone="paper" + data-testid="cta" + > + <LinkButton to="/">Contact</LinkButton> + </CallToAction>, + ); + expect(rules('cta')).not.toContain('var(--slp-colors-paper-alt)'); + }); }); diff --git a/web/src/components/CallToAction/CallToAction.tsx b/web/src/components/CallToAction/CallToAction.tsx index 7469b47..6302a45 100644 --- a/web/src/components/CallToAction/CallToAction.tsx +++ b/web/src/components/CallToAction/CallToAction.tsx @@ -9,6 +9,8 @@ type CallToActionProps = { titleId: string; // Plain text, or a paragraph with links in it (e.g. RichParagraph) lead?: ReactNode; + // Band colour; alt unless the page needs it to differ from the band above + tone?: 'paper' | 'alt'; 'data-testid'?: string; // The action below the text, e.g. a LinkButton children: ReactNode; @@ -16,18 +18,19 @@ type CallToActionProps = { // Closing block of a page (design .section--alt.section--tight with a narrow, // centred column): a heading, a short lead and one action. The page chooses -// the action and any link in the lead. +// the action, any link in the lead and, when needed, the band colour. export default function CallToAction({ title, titleId, lead, + tone = 'alt', 'data-testid': testId, children, }: CallToActionProps) { return ( <PageSection labelledBy={titleId} - tone="alt" + tone={tone} width="narrow" spacing="tight" data-testid={testId} diff --git a/web/src/components/FaqList/FaqList.test.tsx b/web/src/components/FaqList/FaqList.test.tsx new file mode 100644 index 0000000..e978680 --- /dev/null +++ b/web/src/components/FaqList/FaqList.test.tsx @@ -0,0 +1,101 @@ +import { cleanup, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import type { FaqItem } from '@/content/types'; +import { faqItems } from '@/test/arbitraries'; +import { axeResults } from '@/test/axe'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import FaqList from './FaqList'; + +const items: FaqItem[] = [ + { + id: 'een', + question: 'Wanneer boek ik?', + answer: [ + 'Zo vroeg mogelijk, zie ', + { text: 'de prijzen', to: '/', hash: 'prijzen' }, + '.', + ], + }, + { id: 'twee', question: 'Waar?', answer: ['Bij jullie thuis.'] }, + { id: 'drie', question: 'Hoe lang?', answer: ['Twee uur.'] }, +]; + +describe('FaqList', () => { + it('shows every question closed, with the answers in the page', async () => { + const { container } = await renderWithProviders( + <FaqList items={items} data-testid="faq" />, + ); + const details = container.querySelectorAll('details'); + expect(details).toHaveLength(3); + for (const item of details) expect(item).not.toHaveAttribute('open'); + for (const item of items) { + expect(screen.getByText(item.question).tagName).toBe('SUMMARY'); + } + expect( + screen.getByText('Bij jullie thuis.', { exact: false }), + ).toBeInTheDocument(); + expect( + screen.getByRole('link', { name: 'de prijzen' }), + ).toHaveAttribute('href', '/#prijzen'); + // The questions are labels, not headings + expect(screen.queryByRole('heading')).toBeNull(); + expect( + container.querySelectorAll('summary svg[aria-hidden="true"]'), + ).toHaveLength(3); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + // jsdom does not turn Enter or Space on a summary into the click that + // opens the details (browsers do, for any summary that is the first + // child of its details), and user-event only does so for buttons and + // links. So the test checks what the page controls: the summary is + // focusable and is the first child of its details, and activating it + // (the click a browser sends) toggles the item. + it('has a focusable summary as first child, which toggles the item when activated', async () => { + const user = userEvent.setup(); + const { container } = await renderWithProviders( + <FaqList items={items} />, + ); + const first = container.querySelector('details')!; + const summary = first.firstElementChild as HTMLElement; + expect(summary.tagName).toBe('SUMMARY'); + expect(summary).toHaveTextContent('Wanneer boek ik?'); + expect(summary.getAttribute('tabindex')).not.toBe('-1'); + await user.tab(); + expect(summary).toHaveFocus(); + await user.click(summary); + expect(first).toHaveAttribute('open'); + await user.click(summary); + expect(first).not.toHaveAttribute('open'); + }); + + it('renders nothing without questions', async () => { + const { container } = await renderWithProviders(<FaqList items={[]} />); + expect(container.querySelector('details')).toBeNull(); + }); + + it('has one closed details per item, with every answer in the page (invariant)', async () => { + for (const sample of fc.sample(faqItems, { numRuns: 6 })) { + const { container } = await renderWithProviders( + <FaqList items={sample} />, + ); + const details = container.querySelectorAll('details'); + expect(details).toHaveLength(sample.length); + details.forEach((item, index) => { + expect(item.hasAttribute('open')).toBe(false); + expect(item.querySelector('summary')!.textContent).toBe( + sample[index].question, + ); + const answer = sample[index].answer + .map((piece) => + typeof piece === 'string' ? piece : piece.text, + ) + .join(''); + expect(item.querySelector('p')!.textContent).toBe(answer); + }); + cleanup(); + } + }); +}); diff --git a/web/src/components/FaqList/FaqList.tsx b/web/src/components/FaqList/FaqList.tsx new file mode 100644 index 0000000..128705b --- /dev/null +++ b/web/src/components/FaqList/FaqList.tsx @@ -0,0 +1,82 @@ +import { Box, chakra } from '@chakra-ui/react'; +import RichParagraph from '@/components/RichParagraph/RichParagraph'; +import type { FaqItem } from '@/content/types'; + +type FaqListProps = { + items: readonly FaqItem[]; + 'data-testid'?: string; +}; + +// The plus that turns into a minus while its item is open: the vertical +// stroke is hidden by CSS under details[open]. Decoration only. +function ToggleIcon() { + return ( + <chakra.svg + aria-hidden="true" + focusable="false" + viewBox="0 0 24 24" + w="1.25rem" + h="1.25rem" + flexShrink={0} + fill="none" + stroke="currentColor" + strokeWidth="1.5" + strokeLinecap="round" + > + <path d="M5 12h14" /> + <path data-faq-vertical d="M12 5v14" /> + </chakra.svg> + ); +} + +// The questions of a shoot page (FR-ST-06, BR-SP-50..52): one native +// details element per question, so it works without JavaScript and by +// keyboard. All items start closed; the answers are in the page either way. +// The browser keeps track of what is open, there is no state here. +export default function FaqList({ + items, + 'data-testid': testId, +}: FaqListProps) { + if (items.length === 0) return null; + + return ( + <Box borderTopWidth="1px" borderColor="sand" data-testid={testId}> + {items.map((item) => ( + <Box + as="details" + key={item.id} + borderBottomWidth="1px" + borderColor="sand" + css={{ + '&[open] [data-faq-vertical]': { display: 'none' }, + }} + > + <Box + as="summary" + display="flex" + alignItems="center" + justifyContent="space-between" + gap={4} + minH="2.75rem" + py={5} + fontFamily="heading" + fontSize="1.25rem" + color="ink" + cursor="pointer" + listStyle="none" + css={{ + '&::-webkit-details-marker': { display: 'none' }, + }} + _focusVisible={{ outlineOffset: '2px' }} + > + {item.question} + <ToggleIcon /> + </Box> + <Box mb={6} maxW="680px" color="ink.soft"> + <RichParagraph paragraph={item.answer} /> + </Box> + </Box> + ))} + </Box> + ); +} diff --git a/web/src/components/Footer/Footer.test.tsx b/web/src/components/Footer/Footer.test.tsx index c44cb88..3220347 100644 --- a/web/src/components/Footer/Footer.test.tsx +++ b/web/src/components/Footer/Footer.test.tsx @@ -77,6 +77,44 @@ describe('Footer', () => { expect(links[1]).not.toHaveAttribute('aria-current'); }); + it('markeert op een shootpagina geen footerlink (exact)', async () => { + await renderFooter(siteContent, '/soorten-fotoshoots/newborn'); + const nav = screen.getByRole('navigation', { name: 'Footermenu' }); + for (const link of within(nav).getAllByRole('link')) { + expect(link).not.toHaveAttribute('aria-current'); + } + }); + + it.each(['/soorten-fotoshoots', '/soorten-fotoshoots/'])( + 'markeert Soorten fotoshoots op %s', + async (path) => { + await renderFooter(siteContent, path); + const nav = screen.getByRole('navigation', { name: 'Footermenu' }); + expect( + within(nav).getByRole('link', { name: 'Soorten fotoshoots' }), + ).toHaveAttribute('aria-current', 'page'); + expect( + within(nav).getByRole('link', { name: 'Portfolio' }), + ).not.toHaveAttribute('aria-current'); + }, + ); + + it('markeert Portfolio ook met een query in de URL', async () => { + await renderFooter(siteContent, '/portfolio?shoot=newborn'); + const nav = screen.getByRole('navigation', { name: 'Footermenu' }); + expect( + within(nav).getByRole('link', { name: 'Portfolio' }), + ).toHaveAttribute('aria-current', 'page'); + }); + + it('blijft zonder axe-fouten op een shootpagina', async () => { + const { container } = await renderFooter( + siteContent, + '/soorten-fotoshoots/newborn', + ); + expect(await axeResults(container)).toHaveNoViolations(); + }); + it('laat lege kolommen weg', async () => { await renderFooter({ ...siteContent, diff --git a/web/src/components/Footer/Footer.tsx b/web/src/components/Footer/Footer.tsx index c70c4dc..41eed28 100644 --- a/web/src/components/Footer/Footer.tsx +++ b/web/src/components/Footer/Footer.tsx @@ -138,6 +138,12 @@ export default function Footer({ content }: FooterProps) { <FooterLink asChild> <RouterLink to={item.to} + // Exact, also with a query: on a shoot page the + // overview link is not the current page + activeOptions={{ + exact: true, + includeSearch: false, + }} data-testid={`footer-nav-${item.to.slice(1)}`} > {item.label} diff --git a/web/src/components/MediaText/MediaText.test.tsx b/web/src/components/MediaText/MediaText.test.tsx index edbf2c3..3237ebc 100644 --- a/web/src/components/MediaText/MediaText.test.tsx +++ b/web/src/components/MediaText/MediaText.test.tsx @@ -167,4 +167,23 @@ describe('MediaText', () => { ); expect(await axeResults(container)).toHaveNoViolations(); }); + + it('keeps a medium photo at most 30rem wide and lays out like small', async () => { + await renderWithProviders( + <MediaText image={image} aspectRatio="4 / 5" mediaSize="medium"> + <h2>Newborn</h2> + </MediaText>, + ); + expect(gridRules()).toMatch( + /grid-template-columns: minmax\(0, ?30rem\) minmax\(0, ?1fr\)/, + ); + expect(cssRulesFor(photoColumnElement()).join()).toContain( + 'max-width: 30rem', + ); + const textRules = cssRulesFor( + screen.getByRole('heading').closest('[data-reveal]')!, + ).join(); + expect(textRules).toContain('max-width: 36rem'); + expect(textRules).toMatch(/min-width: 64rem.*margin-inline: auto/s); + }); }); diff --git a/web/src/components/MediaText/MediaText.tsx b/web/src/components/MediaText/MediaText.tsx index 51d7b0e..a9886a3 100644 --- a/web/src/components/MediaText/MediaText.tsx +++ b/web/src/components/MediaText/MediaText.tsx @@ -9,6 +9,8 @@ import type { ContentImage, FrameColor } from '@/content/types'; // alone, or the photo with a detail photo overlapping it const SMALL_MEDIA = '20rem'; const SMALL_MEDIA_WITH_DETAIL = '28rem'; +// Widest a medium photo column gets (a portrait photo on a shoot page) +const MEDIUM_MEDIA = '30rem'; // Widest the text next to a small photo gets: about 70 characters a line const SMALL_TEXT = '36rem'; @@ -23,8 +25,9 @@ type MediaTextProps = { reverse?: boolean; // half: photo and text share the width equally (design .about); // small: the photo column stays narrow (20rem, 28rem with a detail - // photo); the text, at most 36rem, is centred in the rest - mediaSize?: 'half' | 'small'; + // photo); the text, at most 36rem, is centred in the rest; + // medium: laid out like small, with a photo column up to 30rem + mediaSize?: 'half' | 'small' | 'medium'; // A smaller square photo overlapping the main one's lower right corner detailImage?: ContentImage; // Colour of the block behind the photo (FramedImage) @@ -48,8 +51,14 @@ export default function MediaText({ 'data-testid': testId, children, }: MediaTextProps) { - const small = mediaSize === 'small'; - const mediaWidth = detailImage ? SMALL_MEDIA_WITH_DETAIL : SMALL_MEDIA; + // medium shares the layout of small, with a wider photo column + const small = mediaSize !== 'half'; + const mediaWidth = + mediaSize === 'medium' + ? MEDIUM_MEDIA + : detailImage + ? SMALL_MEDIA_WITH_DETAIL + : SMALL_MEDIA; const media = `minmax(0, ${mediaWidth})`; const columns = small ? reverse diff --git a/web/src/components/NavigationBar/ChevronIcon.tsx b/web/src/components/NavigationBar/ChevronIcon.tsx new file mode 100644 index 0000000..abe7fd9 --- /dev/null +++ b/web/src/components/NavigationBar/ChevronIcon.tsx @@ -0,0 +1,28 @@ +import { chakra } from '@chakra-ui/react'; + +// A small chevron for the submenu toggles. Decorative: the button carries the +// name and aria-expanded. It turns upside down while its button has +// `data-open`; with reduced motion it jumps instead of turning (BR-NAV-42). +export default function ChevronIcon() { + return ( + <chakra.svg + viewBox="0 0 12 12" + width="12px" + height="12px" + aria-hidden="true" + focusable="false" + fill="none" + stroke="currentColor" + strokeWidth="1.5" + strokeLinecap="round" + strokeLinejoin="round" + transitionProperty="transform" + transitionDuration="swap" + transitionTimingFunction="smooth" + _motionReduce={{ transition: 'none' }} + css={{ '[data-open] > &': { transform: 'rotate(180deg)' } }} + > + <path d="M2 4.25 6 8l4-3.75" /> + </chakra.svg> + ); +} diff --git a/web/src/components/NavigationBar/MobileNav.test.tsx b/web/src/components/NavigationBar/MobileNav.test.tsx new file mode 100644 index 0000000..638ad2f --- /dev/null +++ b/web/src/components/NavigationBar/MobileNav.test.tsx @@ -0,0 +1,177 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; +import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; +import { mockViewport } from '@/test/navViewport'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import NavigationBar from './NavigationBar'; + +const GROUP = 'Submenu Soorten fotoshoots'; + +// The mobile layout (below lg) through the whole navigation bar +async function renderMobile(path = '/contact') { + mockViewport(375); + const result = await renderWithProviders(<NavigationBar />, { path }); + return { ...result, user: userEvent.setup() }; +} + +const hamburger = () => screen.getByTestId('nav-menu-toggle'); +const menu = () => document.getElementById('mobile-nav')!; +const inMenu = () => within(menu()); +const groupToggle = () => inMenu().getByRole('button', { name: GROUP }); +const subLinks = () => ['Newborn', 'Zwangerschap', 'Gezin']; + +async function openMenu(path?: string) { + const rendered = await renderMobile(path); + await rendered.user.click(hamburger()); + return rendered; +} + +describe('MobileNav', () => { + it('opens with the hamburger and shows the main items', async () => { + await openMenu(); + expect(hamburger()).toHaveAttribute('aria-expanded', 'true'); + expect(hamburger()).toHaveAccessibleName('Menu sluiten'); + for (const name of ['Home', 'Over mij', 'Portfolio', 'Contact']) { + expect(inMenu().getByRole('link', { name })).toBeVisible(); + } + }); + + it('keeps the menu out of reach while closed', async () => { + await renderMobile(); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + expect( + within(menu()).queryByRole('link', { name: 'Contact' }), + ).toBeNull(); + }); + + it('starts with the group collapsed outside the section (BR-NAV-31)', async () => { + await openMenu('/contact'); + expect(groupToggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it.each(['/soorten-fotoshoots', '/soorten-fotoshoots/gezin'])( + 'starts with the group expanded on %s (BR-NAV-31)', + async (path) => { + await openMenu(path); + expect(groupToggle()).toHaveAttribute('aria-expanded', 'true'); + for (const name of subLinks()) { + expect(inMenu().getByRole('link', { name })).toBeVisible(); + } + }, + ); + + it('flips the group with the chevron and hides collapsed links (BR-NAV-36)', async () => { + const { user } = await openMenu('/contact'); + expect(groupToggle()).toHaveAttribute( + 'aria-controls', + 'mobile-group-soorten-fotoshoots', + ); + for (const name of subLinks()) { + expect(inMenu().queryByRole('link', { name })).toBeNull(); + } + + await user.click(groupToggle()); + expect(groupToggle()).toHaveAttribute('aria-expanded', 'true'); + for (const name of subLinks()) { + expect(inMenu().getByRole('link', { name })).toBeVisible(); + } + + await user.click(groupToggle()); + expect(groupToggle()).toHaveAttribute('aria-expanded', 'false'); + expect(inMenu().queryByRole('link', { name: 'Gezin' })).toBeNull(); + }); + + it('is not reached by Tab while the group is collapsed', async () => { + const { user } = await openMenu('/contact'); + const reached: string[] = []; + for (let i = 0; i < 10; i += 1) { + await user.tab(); + reached.push(document.activeElement?.textContent ?? ''); + } + for (const name of subLinks()) expect(reached).not.toContain(name); + }); + + it.each(['Contact', 'Soorten fotoshoots'])( + 'closes the whole menu when %s is chosen (BR-NAV-32)', + async (name) => { + const { user } = await openMenu('/contact'); + await user.click(inMenu().getByRole('link', { name })); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + expect(hamburger()).toHaveAccessibleName('Menu openen'); + }, + ); + + it('closes the whole menu when a sub-link is chosen', async () => { + const { user } = await openMenu('/soorten-fotoshoots'); + await user.click(inMenu().getByRole('link', { name: 'Gezin' })); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('closes with the hamburger itself', async () => { + const { user } = await openMenu(); + await user.click(hamburger()); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('closes with Escape and puts the focus on the hamburger (BR-NAV-33)', async () => { + const { user } = await openMenu(); + inMenu().getByRole('link', { name: 'Portfolio' }).focus(); + await user.keyboard('{Escape}'); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + expect(hamburger()).toHaveFocus(); + }); + + it('also returns the focus to the hamburger when Escape is pressed on it', async () => { + const { user } = await openMenu(); + expect(hamburger()).toHaveFocus(); + await user.keyboard('{Escape}'); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + expect(hamburger()).toHaveFocus(); + }); + + it('does not move the focus on Escape when it was elsewhere', async () => { + const { user } = await openMenu(); + (document.activeElement as HTMLElement).blur(); + await user.keyboard('{Escape}'); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + expect(hamburger()).not.toHaveFocus(); + }); + + it('scrolls inside the screen and centres short content (BR-NAV-34)', async () => { + await openMenu(); + expect(getComputedStyle(menu()).overflowY).toBe('auto'); + const rules = cssRulesFor(menu()).join('\n'); + expect(rules).toContain('overscroll-behavior'); + const centring = menu().firstElementChild!; + expect(cssRulesFor(centring).join('\n')).toContain('margin-block'); + expect(centring.querySelector('nav')).not.toBeNull(); + }); + + it('locks the page behind it while open and restores it after', async () => { + const { user } = await openMenu(); + expect(document.body.style.overflow).toBe('hidden'); + await user.click(hamburger()); + expect(document.body.style.overflow).toBe(''); + }); + + it('has no axe violations open, collapsed and expanded', async () => { + const { container, user } = await openMenu('/contact'); + expect(await axeResults(container)).toHaveNoViolations(); + await user.click(groupToggle()); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('removes the transitions with reduced motion (BR-NAV-42)', async () => { + await openMenu('/soorten-fotoshoots'); + const group = document.getElementById( + 'mobile-group-soorten-fotoshoots', + )!; + for (const element of [menu(), group]) { + const rules = cssRulesFor(element).join('\n'); + expect(rules).toContain('prefers-reduced-motion: reduce'); + expect(rules).toContain('transition: none'); + } + }); +}); diff --git a/web/src/components/NavigationBar/MobileNav.tsx b/web/src/components/NavigationBar/MobileNav.tsx index d44f84b..12336d9 100644 --- a/web/src/components/NavigationBar/MobileNav.tsx +++ b/web/src/components/NavigationBar/MobileNav.tsx @@ -1,22 +1,43 @@ -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { Box, Stack } from '@chakra-ui/react'; -import { mainNav } from '@/navigation'; +import type { NavMenuEvent } from '@/lib/navMenuState'; +import { hasChildren, mainNav } from '@/navigation'; import RouterLink from '../RouterLink'; +import MobileNavGroup from './MobileNavGroup'; type MobileNavProps = { id: string; open: boolean; - onClose: () => void; + // The sub-list of the item with children is expanded + groupOpen: boolean; + pathname: string; + dispatch: (event: NavMenuEvent) => void; }; // Menu onder de navigatiebalk op mobiel, vult de rest van het scherm -export default function MobileNav({ id, open, onClose }: MobileNavProps) { - // Pagina eronder niet laten scrollen, en sluiten met Escape +export default function MobileNav({ + id, + open, + groupOpen, + pathname, + dispatch, +}: MobileNavProps) { + const box = useRef<HTMLDivElement>(null); + + // Pagina eronder niet laten scrollen, en sluiten met Escape. De focus gaat + // terug naar de hamburger als die in het menu of op de hamburger stond + // (de hamburger herken je aan aria-controls naar dit menu). useEffect(() => { if (!open) return; const onKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape') onClose(); + if (event.key !== 'Escape') return; + const active = document.activeElement; + const focusInside = + !!active && + (!!box.current?.contains(active) || + active.getAttribute('aria-controls') === id); + dispatch({ type: 'escape', focusInside }); }; document.body.style.overflow = 'hidden'; document.addEventListener('keydown', onKeyDown); @@ -25,10 +46,11 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) { document.body.style.overflow = ''; document.removeEventListener('keydown', onKeyDown); }; - }, [open, onClose]); + }, [open, id, dispatch]); return ( <Box + ref={box} id={id} position="fixed" top="header" @@ -38,7 +60,9 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) { zIndex="mobileNav" display={{ base: 'flex', lg: 'none' }} flexDirection="column" - justifyContent="center" + // Een hoog menu scrolt binnen het scherm (BR-NAV-34) + overflowY="auto" + overscrollBehavior="contain" pt={8} pb={16} px="gutter" @@ -49,26 +73,43 @@ export default function MobileNav({ id, open, onClose }: MobileNavProps) { transitionProperty="clip-path, visibility" transitionDuration="interaction" transitionTimingFunction="smooth" + _motionReduce={{ transition: 'none' }} > - <nav aria-label="Mobiel menu"> - <Stack as="ul" gap={5} listStyleType="none"> - {mainNav.map((item) => ( - <li key={item.to}> - <RouterLink - to={item.to} - onClick={onClose} - display="block" - fontFamily="heading" - fontSize="1.9rem" - color="ink" - _currentPage={{ color: 'accent' }} - > - {item.label} - </RouterLink> - </li> - ))} - </Stack> - </nav> + {/* Automatische marges centreren een kort menu en laten een hoog + menu bovenaan beginnen (centreren zou de bovenkant afknippen) */} + <Box marginBlock="auto"> + <nav aria-label="Mobiel menu"> + <Stack as="ul" gap={5} listStyleType="none"> + {mainNav.map((item) => ( + <li key={item.to}> + {hasChildren(item) ? ( + <MobileNavGroup + item={item} + id={`mobile-group-${item.to.slice(1)}`} + open={groupOpen} + pathname={pathname} + dispatch={dispatch} + /> + ) : ( + <RouterLink + to={item.to} + onClick={() => + dispatch({ type: 'linkChosen' }) + } + display="block" + fontFamily="heading" + fontSize="1.9rem" + color="ink" + _currentPage={{ color: 'accent' }} + > + {item.label} + </RouterLink> + )} + </li> + ))} + </Stack> + </nav> + </Box> </Box> ); } diff --git a/web/src/components/NavigationBar/MobileNavGroup.tsx b/web/src/components/NavigationBar/MobileNavGroup.tsx new file mode 100644 index 0000000..e3500b9 --- /dev/null +++ b/web/src/components/NavigationBar/MobileNavGroup.tsx @@ -0,0 +1,113 @@ +import { Box, chakra, Flex } from '@chakra-ui/react'; +import { isSectionCurrent } from '@/lib/navCurrent'; +import type { NavMenuEvent } from '@/lib/navMenuState'; +import type { NavItem } from '@/navigation'; +import RouterLink from '../RouterLink'; +import ChevronIcon from './ChevronIcon'; + +type MobileNavGroupProps = { + item: NavItem & { children: readonly NavItem[] }; + // Id of the sub-list, for aria-controls + id: string; + open: boolean; + pathname: string; + dispatch: (event: NavMenuEvent) => void; +}; + +// Exact: only the page itself is current (BR-NAV-01), also with a query +const exactActive = { exact: true, includeSearch: false } as const; + +const duration = '0.3s'; +const easing = 'cubic-bezier(.22, .61, .36, 1)'; + +// The parent row of the mobile menu: the link to the overview, a chevron +// button and an expandable list of sub-pages (BR-NAV-30..36) +export default function MobileNavGroup({ + item, + id, + open, + pathname, + dispatch, +}: MobileNavGroupProps) { + return ( + <> + <Flex alignItems="center" gap={1}> + <RouterLink + to={item.to} + activeOptions={exactActive} + onClick={() => dispatch({ type: 'linkChosen' })} + display="block" + fontFamily="heading" + fontSize="1.9rem" + color={isSectionCurrent(item, pathname) ? 'accent' : 'ink'} + _currentPage={{ color: 'accent' }} + > + {item.label} + </RouterLink> + <chakra.button + type="button" + aria-expanded={open} + aria-controls={id} + aria-label={`Submenu ${item.label}`} + data-open={open || undefined} + display="flex" + alignItems="center" + justifyContent="center" + // 44px: minimaal klikdoel op touch (BR-NAV-40) + w="44px" + h="44px" + flexShrink={0} + cursor="pointer" + color="ink" + onClick={() => dispatch({ type: 'toggleGroup' })} + > + <ChevronIcon /> + </chakra.button> + </Flex> + {/* Grid rows 0fr to 1fr animate the height without measuring. On + close the visibility switches only after the collapse, so the + collapse is seen; collapsed links are neither focusable nor + read (BR-NAV-36). */} + <Box + id={id} + display="grid" + gridTemplateRows={open ? '1fr' : '0fr'} + visibility={open ? 'visible' : 'hidden'} + transition={`grid-template-rows ${duration} ${easing}, visibility 0s linear ${open ? '0s' : duration}`} + _motionReduce={{ transition: 'none' }} + > + <Box overflow="hidden" minH={0}> + <chakra.ul + listStyleType="none" + pl="1.25rem" + pt={2} + display="flex" + flexDirection="column" + > + {item.children.map((child) => ( + <li key={child.to}> + <RouterLink + to={child.to} + activeOptions={exactActive} + onClick={() => + dispatch({ type: 'linkChosen' }) + } + display="flex" + alignItems="center" + minH="44px" + fontFamily="heading" + fontSize="1.4rem" + color="ink" + // accent.deep: 1.4rem is not large text + _currentPage={{ color: 'accent.deep' }} + > + {child.label} + </RouterLink> + </li> + ))} + </chakra.ul> + </Box> + </Box> + </> + ); +} diff --git a/web/src/components/NavigationBar/NavLink.test.tsx b/web/src/components/NavigationBar/NavLink.test.tsx new file mode 100644 index 0000000..d527635 --- /dev/null +++ b/web/src/components/NavigationBar/NavLink.test.tsx @@ -0,0 +1,63 @@ +import { screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { cssRulesFor } from '@/test/cssRules'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import NavLink from './NavLink'; + +describe('NavLink', () => { + it('marks the section without aria-current', async () => { + await renderWithProviders( + <NavLink + to="/soorten-fotoshoots" + activeOptions={{ exact: true, includeSearch: false }} + sectionCurrent + > + Soorten + </NavLink>, + { path: '/soorten-fotoshoots/newborn' }, + ); + const link = screen.getByRole('link', { name: 'Soorten' }); + expect(link).toHaveAttribute('data-section-current'); + expect(link).not.toHaveAttribute('aria-current'); + }); + + it('sets no section mark by default or when false', async () => { + await renderWithProviders( + <> + <NavLink to="/portfolio">Plain</NavLink> + <NavLink to="/contact" sectionCurrent={false}> + Off + </NavLink> + </>, + ); + for (const name of ['Plain', 'Off']) { + expect(screen.getByRole('link', { name })).not.toHaveAttribute( + 'data-section-current', + ); + } + }); + + it('still lets the router set aria-current on the current page', async () => { + await renderWithProviders( + <NavLink to="/portfolio">Portfolio</NavLink>, + { + path: '/portfolio', + }, + ); + expect(screen.getByRole('link')).toHaveAttribute( + 'aria-current', + 'page', + ); + }); + + it('draws the underline for the section mark too', async () => { + await renderWithProviders( + <NavLink to="/soorten-fotoshoots" sectionCurrent> + Soorten + </NavLink>, + ); + const rules = cssRulesFor(screen.getByRole('link')).join('\n'); + expect(rules).toContain('[data-section-current]::after'); + expect(rules).toContain('[aria-current="page"]::after'); + }); +}); diff --git a/web/src/components/NavigationBar/NavLink.tsx b/web/src/components/NavigationBar/NavLink.tsx index c816b6a..3cf6059 100644 --- a/web/src/components/NavigationBar/NavLink.tsx +++ b/web/src/components/NavigationBar/NavLink.tsx @@ -1,8 +1,16 @@ import RouterLink from '../RouterLink'; -type NavLinkProps = React.ComponentProps<typeof RouterLink>; +type NavLinkProps = React.ComponentProps<typeof RouterLink> & { + // The page is below this link (a shoot page below the overview): shows + // the same underline as the current page, without aria-current + sectionCurrent?: boolean; +}; -export default function NavLink({ children, ...props }: NavLinkProps) { +export default function NavLink({ + children, + sectionCurrent, + ...props +}: NavLinkProps) { return ( <RouterLink textStyle="eyebrow" @@ -11,6 +19,7 @@ export default function NavLink({ children, ...props }: NavLinkProps) { display="inline-block" py="2" mx="4" + data-section-current={sectionCurrent ? '' : undefined} css={{ '&::after': { content: '""', @@ -26,7 +35,7 @@ export default function NavLink({ children, ...props }: NavLinkProps) { transitionDuration: 'interaction', transitionTimingFunction: 'smooth', }, - '&:hover::after, &:focus-visible::after, &[aria-current="page"]::after': + '&:hover::after, &:focus-visible::after, &[aria-current="page"]::after, &[data-section-current]::after': { transform: 'scaleX(1)', transformOrigin: 'left', diff --git a/web/src/components/NavigationBar/NavSubmenu.test.tsx b/web/src/components/NavigationBar/NavSubmenu.test.tsx new file mode 100644 index 0000000..505e275 --- /dev/null +++ b/web/src/components/NavigationBar/NavSubmenu.test.tsx @@ -0,0 +1,158 @@ +import { createRef } from 'react'; +import { fireEvent, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import { hasChildren, mainNav } from '@/navigation'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import NavSubmenu from './NavSubmenu'; + +const item = mainNav.find(hasChildren)!; +const TOGGLE = 'Submenu Soorten fotoshoots'; + +// The component alone with a fake dispatch: what it reports, not what the +// reducer does with it +async function renderSubmenu({ + open = false, + path = '/', + transparent = false, +} = {}) { + const dispatch = vi.fn(); + const toggleRef = createRef<HTMLButtonElement>(); + await renderWithProviders( + <> + <NavSubmenu + item={item} + id="submenu-soorten-fotoshoots" + open={open} + pathname={path} + transparent={transparent} + toggleRef={toggleRef} + dispatch={dispatch} + /> + <button>elsewhere</button> + </>, + { path }, + ); + return { dispatch, toggleRef, user: userEvent.setup() }; +} + +const toggle = () => screen.getByRole('button', { name: TOGGLE }); + +describe('NavSubmenu', () => { + it('renders without errors with the real main menu item', async () => { + await renderSubmenu(); + expect( + screen.getByRole('link', { name: 'Soorten fotoshoots' }), + ).toHaveAttribute('href', '/soorten-fotoshoots'); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('passes the toggle element to toggleRef', async () => { + const { toggleRef } = await renderSubmenu(); + expect(toggleRef.current).toBe(toggle()); + }); + + it('reflects open in aria-expanded and data-open', async () => { + await renderSubmenu({ open: true }); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + expect(toggle()).toHaveAttribute('data-open'); + }); + + it('reports toggleSubmenu for a click on the toggle', async () => { + const { dispatch, user } = await renderSubmenu(); + await user.click(toggle()); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ + type: 'toggleSubmenu', + }); + }); + + it('reports linkChosen for a click on a panel link', async () => { + const { dispatch, user } = await renderSubmenu({ open: true }); + await user.click(screen.getByRole('link', { name: 'Gezin' })); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ + type: 'linkChosen', + }); + }); + + it('reports escape with focusInside true when focus is in the submenu', async () => { + const { dispatch, user } = await renderSubmenu({ open: true }); + toggle().focus(); + await user.keyboard('{Escape}'); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ + type: 'escape', + focusInside: true, + }); + }); + + it('reports escape with focusInside false when focus is elsewhere', async () => { + const { dispatch, user } = await renderSubmenu({ open: true }); + screen.getByRole('button', { name: 'elsewhere' }).focus(); + await user.keyboard('{Escape}'); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ + type: 'escape', + focusInside: false, + }); + }); + + it('reports outside for a pointer down outside, not inside', async () => { + const { dispatch } = await renderSubmenu({ open: true }); + fireEvent.pointerDown(toggle()); + expect(dispatch).not.toHaveBeenCalled(); + fireEvent.pointerDown( + screen.getByRole('button', { name: 'elsewhere' }), + ); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ type: 'outside' }); + }); + + it('listens for Escape and outside only while open', async () => { + const { dispatch, user } = await renderSubmenu({ open: false }); + await user.keyboard('{Escape}'); + fireEvent.pointerDown( + screen.getByRole('button', { name: 'elsewhere' }), + ); + expect(dispatch).not.toHaveBeenCalled(); + }); + + it('reports focusLeave when focus moves to an element outside', async () => { + const { dispatch } = await renderSubmenu({ open: true }); + fireEvent.focusOut(toggle(), { + relatedTarget: screen.getByRole('button', { name: 'elsewhere' }), + }); + expect(dispatch).toHaveBeenCalledExactlyOnceWith({ + type: 'focusLeave', + }); + }); + + it('ignores focus that stays inside or has no target', async () => { + const { dispatch } = await renderSubmenu({ open: true }); + fireEvent.focusOut(toggle(), { + relatedTarget: screen.getByRole('link', { name: 'Newborn' }), + }); + fireEvent.focusOut(toggle(), { relatedTarget: null }); + expect(dispatch).not.toHaveBeenCalled(); + }); + + it('reports nothing for hover or arrow keys (BR-NAV-21, BR-NAV-27)', async () => { + const { dispatch, user } = await renderSubmenu({ open: true }); + await user.hover(toggle()); + await user.hover(screen.getByRole('link', { name: 'Gezin' })); + screen.getByRole('link', { name: 'Gezin' }).focus(); + await user.keyboard( + '{ArrowDown}{ArrowUp}{ArrowLeft}{ArrowRight}{Home}{End}', + ); + expect(dispatch).not.toHaveBeenCalled(); + }); + + it('marks the shoot page in the panel and the section on the parent', async () => { + await renderSubmenu({ open: true, path: '/soorten-fotoshoots/gezin' }); + expect(screen.getByRole('link', { name: 'Gezin' })).toHaveAttribute( + 'aria-current', + 'page', + ); + const parent = screen.getByRole('link', { + name: 'Soorten fotoshoots', + }); + expect(parent).not.toHaveAttribute('aria-current'); + expect(parent).toHaveAttribute('data-section-current'); + }); +}); diff --git a/web/src/components/NavigationBar/NavSubmenu.tsx b/web/src/components/NavigationBar/NavSubmenu.tsx new file mode 100644 index 0000000..54a596c --- /dev/null +++ b/web/src/components/NavigationBar/NavSubmenu.tsx @@ -0,0 +1,162 @@ +import { useRef, type RefObject } from 'react'; +import { Box, chakra } from '@chakra-ui/react'; +import useDismiss from '@/hooks/useDismiss'; +import { isSectionCurrent } from '@/lib/navCurrent'; +import type { NavMenuEvent } from '@/lib/navMenuState'; +import type { NavItem } from '@/navigation'; +import RouterLink from '../RouterLink'; +import ChevronIcon from './ChevronIcon'; +import NavLink from './NavLink'; + +type NavSubmenuProps = { + item: NavItem & { children: readonly NavItem[] }; + // Id of the panel, for aria-controls + id: string; + open: boolean; + pathname: string; + // The header is see-through over the home hero (white text) + transparent: boolean; + toggleRef: RefObject<HTMLButtonElement | null>; + dispatch: (event: NavMenuEvent) => void; +}; + +// Exact: only the page itself is current, not the pages below it (BR-NAV-01); +// without the query, so a filter in the URL does not switch it off +const exactActive = { exact: true, includeSearch: false } as const; + +// Desktop submenu: the parent stays a link, a separate toggle opens a panel +// with the sub-pages. Disclosure navigation: no role="menu", no arrow keys, +// no hover opening (BR-NAV-21, BR-NAV-27). +export default function NavSubmenu({ + item, + id, + open, + pathname, + transparent, + toggleRef, + dispatch, +}: NavSubmenuProps) { + const wrapper = useRef<HTMLDivElement>(null); + + useDismiss(wrapper, open, (reason) => + dispatch( + reason === 'escape' + ? { + type: 'escape', + focusInside: + wrapper.current?.contains(document.activeElement) ?? + false, + } + : { type: 'outside' }, + ), + ); + + return ( + <Box + ref={wrapper} + position="relative" + display="flex" + alignItems="center" + // Focus moving to something outside closes the panel; a blur + // without a target (window blur) is ignored (BR-NAV-25) + onBlur={(event) => { + const next = event.relatedTarget; + if ( + next instanceof Node && + !event.currentTarget.contains(next) + ) { + dispatch({ type: 'focusLeave' }); + } + }} + > + <NavLink + to={item.to} + activeOptions={exactActive} + sectionCurrent={isSectionCurrent(item, pathname)} + mr={0} + > + {item.label} + </NavLink> + <chakra.button + ref={toggleRef} + type="button" + aria-expanded={open} + aria-controls={id} + aria-label={`Submenu ${item.label}`} + data-open={open || undefined} + display="flex" + alignItems="center" + justifyContent="center" + // 44px: minimaal klikdoel op touch (BR-NAV-40) + w="44px" + h="44px" + cursor="pointer" + color="currentColor" + // Over the hero the header is dark: a white ring (BR-NAV-43) + css={ + transparent ? { '--focus-ring-color': 'white' } : undefined + } + onClick={() => dispatch({ type: 'toggleSubmenu' })} + > + <ChevronIcon /> + </chakra.button> + <Box + id={id} + position="absolute" + top="calc(100% + 0.75rem)" + left="4" + minW="15rem" + // Own colours, so the panel is solid also over the hero (BR-NAV-29) + bg="bg" + color="fg" + borderWidth="1px" + borderColor="line" + shadow="panel" + // Hidden from sight and from Tab and screen readers while + // closed, but kept in the DOM so aria-controls stays valid + visibility={open ? 'visible' : 'hidden'} + opacity={open ? 1 : 0} + transform={open ? 'none' : 'translateY(-6px)'} + pointerEvents={open ? 'auto' : 'none'} + transitionProperty="opacity, transform, visibility" + transitionDuration="swap" + transitionTimingFunction="smooth" + _motionReduce={{ transition: 'none' }} + > + <chakra.ul listStyleType="none" py="2"> + {item.children.map((child) => ( + <li key={child.to}> + <RouterLink + to={child.to} + activeOptions={exactActive} + onClick={() => dispatch({ type: 'linkChosen' })} + textStyle="eyebrow" + color="fg" + display="flex" + alignItems="center" + minH="44px" + px="5" + position="relative" + _hover={{ bg: 'paper.alt' }} + _currentPage={{ + color: 'accent.deep', + _before: { + content: '""', + position: 'absolute', + left: 0, + top: 0, + bottom: 0, + width: '2px', + bg: 'accent', + }, + }} + > + {child.label} + </RouterLink> + </li> + ))} + </chakra.ul> + </Box> + </Box> + ); +} diff --git a/web/src/components/NavigationBar/NavigationBar.test.tsx b/web/src/components/NavigationBar/NavigationBar.test.tsx index 7a3fab0..664efa8 100644 --- a/web/src/components/NavigationBar/NavigationBar.test.tsx +++ b/web/src/components/NavigationBar/NavigationBar.test.tsx @@ -1,9 +1,30 @@ -import { screen, within } from '@testing-library/react'; +import { fireEvent, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { describe, expect, it } from 'vitest'; import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; +import { mockViewport } from '@/test/navViewport'; import { renderWithProviders } from '@/test/renderWithProviders'; import NavigationBar from './NavigationBar'; +const TOGGLE = 'Submenu Soorten fotoshoots'; +const SHOOTS = ['Newborn', 'Zwangerschap', 'Gezin', 'Loveshoot', 'Portretten']; + +// The desktop layout (lg and up) unless a width is given +async function renderBar(path = '/', width = 1280) { + mockViewport(width); + const result = await renderWithProviders(<NavigationBar />, { path }); + return { ...result, user: userEvent.setup() }; +} + +const toggle = () => screen.getByRole('button', { name: TOGGLE }); +const panel = () => document.getElementById('submenu-soorten-fotoshoots')!; +// By text: the name of a link in a closed (hidden) panel is empty +const panelLink = (text: string) => + within(panel()) + .getAllByRole('link', { hidden: true }) + .find((link) => link.textContent === text)!; + describe('NavigationBar', () => { it('heeft het logo als link naar home', async () => { await renderWithProviders(<NavigationBar />, { path: '/portfolio' }); @@ -15,12 +36,11 @@ describe('NavigationBar', () => { }); it('toont het hoofdmenu in de vaste volgorde', async () => { - const { container } = await renderWithProviders(<NavigationBar />); + const { container } = await renderBar(); const nav = screen.getByRole('navigation', { name: 'Hoofdmenu' }); + const topLevel = [...nav.querySelectorAll(':scope > ul > li')]; expect( - within(nav) - .getAllByRole('link', { hidden: true }) - .map((link) => link.textContent), + topLevel.map((li) => li.querySelector('a')?.textContent), ).toEqual([ 'Home', 'Over mij', @@ -28,6 +48,11 @@ describe('NavigationBar', () => { 'Soorten fotoshoots', 'Contact', ]); + expect( + within(panel()) + .getAllByRole('link', { hidden: true }) + .map((link) => link.textContent), + ).toEqual(SHOOTS); expect(await axeResults(container)).toHaveNoViolations(); }); @@ -38,3 +63,222 @@ describe('NavigationBar', () => { ); }); }); + +describe('NavigationBar submenu', () => { + it('heeft een knop met vaste naam, aria-expanded en een bestaand paneel', async () => { + await renderBar(); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + expect(toggle()).toHaveAttribute( + 'aria-controls', + 'submenu-soorten-fotoshoots', + ); + expect(panel()).toBeInTheDocument(); + }); + + it('opent met een klik en meldt dat in aria-expanded', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + expect(toggle()).toHaveAccessibleName(TOGGLE); + for (const name of SHOOTS) { + expect(screen.getByRole('link', { name })).toBeVisible(); + } + }); + + it.each(['{Enter}', ' '])('opent met toets %j', async (key) => { + const { user } = await renderBar(); + toggle().focus(); + await user.keyboard(key); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + }); + + it('opent niet bij hoveren (BR-NAV-21)', async () => { + const { user } = await renderBar(); + await user.hover(toggle()); + await user.hover( + screen.getByRole('link', { name: 'Soorten fotoshoots' }), + ); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('sluit met Escape en zet de focus op de knop als die binnen stond (BR-NAV-23)', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + await user.tab(); + expect(document.activeElement).toBe(panelLink('Newborn')); + await user.keyboard('{Escape}'); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + expect(document.activeElement).toBe(toggle()); + }); + + it('laat de focus staan bij Escape als die buiten het submenu stond', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + toggle().blur(); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + await user.keyboard('{Escape}'); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + expect(document.activeElement).not.toBe(toggle()); + }); + + it('sluit bij een pointer-down buiten zonder de focus te verplaatsen (BR-NAV-24)', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + fireEvent.pointerDown(document.body); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + expect(document.activeElement).toBe(toggle()); + }); + + it('blijft open bij een pointer-down binnen het paneel', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + fireEvent.pointerDown(panelLink('Gezin')); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + }); + + it('sluit als Tab de focus uit het laatste paneellink haalt (BR-NAV-25)', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + panelLink('Portretten').focus(); + await user.tab(); + expect(screen.getByRole('link', { name: 'Contact' })).toHaveFocus(); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('blijft open bij een focusout zonder doel, zoals een venster-blur', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + fireEvent.focusOut(toggle(), { relatedTarget: null }); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + }); + + it('blijft open als de focus binnen het submenu verschuift', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + await user.tab(); + await user.tab(); + expect(panelLink('Zwangerschap')).toHaveFocus(); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + }); + + it('houdt de links van een gesloten paneel buiten bereik van rolzoeker en Tab (BR-NAV-28)', async () => { + const { user } = await renderBar(); + for (const name of SHOOTS) { + expect(screen.queryByRole('link', { name })).toBeNull(); + } + const reached: string[] = []; + for (let i = 0; i < 8; i += 1) { + await user.tab(); + reached.push(document.activeElement?.textContent ?? ''); + } + for (const name of SHOOTS) expect(reached).not.toContain(name); + + await user.click(toggle()); + for (const name of SHOOTS) { + expect(screen.getByRole('link', { name })).toBeVisible(); + } + }); + + it('sluit na het kiezen van een link', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + await user.click(screen.getByRole('link', { name: 'Gezin' })); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('sluit weer met een tweede klik en laat de focus op de knop', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + await user.click(toggle()); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + expect(toggle()).toHaveFocus(); + }); + + it('gebruikt geen menu-rollen (disclosure, geen menu)', async () => { + const { user } = await renderBar(); + await user.click(toggle()); + expect( + document.querySelector('[role="menu"], [role="menuitem"]'), + ).toBeNull(); + }); + + it('heeft geen axe-fouten met het paneel dicht en open', async () => { + const { container, user } = await renderBar(); + expect(await axeResults(container)).toHaveNoViolations(); + await user.click(toggle()); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('zet de eigen kleuren op het paneel en currentColor op de knop (BR-NAV-29)', async () => { + await renderBar('/'); + const panelRules = cssRulesFor(panel()).join('\n'); + expect(panelRules).toMatch(/background(-color)?:/); + const toggleRules = cssRulesFor(toggle()).join('\n'); + expect(toggleRules.toLowerCase()).toContain('color: currentcolor'); + // Over de hero is de header doorzichtig: witte focusring (BR-NAV-43) + expect(toggleRules).toContain('--focus-ring-color: white'); + }); + + it('zet de witte focusring niet op een effen header', async () => { + await renderBar('/portfolio'); + expect(cssRulesFor(toggle()).join('\n')).not.toContain( + '--focus-ring-color: white', + ); + }); + + it('zet bij voorkeur voor minder beweging geen overgang (BR-NAV-42)', async () => { + await renderBar(); + const panelRules = cssRulesFor(panel()).join('\n'); + expect(panelRules).toContain('prefers-reduced-motion: reduce'); + expect(panelRules).toContain('transition: none'); + const chevron = toggle().querySelector('svg')!; + const chevronRules = cssRulesFor(chevron).join('\n'); + expect(chevronRules).toContain('prefers-reduced-motion: reduce'); + expect(chevronRules).toContain('transition: none'); + }); + + it('draait de pijl open via data-open (rotatie 180 graden)', async () => { + const { user } = await renderBar(); + const chevron = toggle().querySelector('svg')!; + expect(cssRulesFor(chevron).join('\n')).toContain('rotate(180deg)'); + expect(toggle()).not.toHaveAttribute('data-open'); + await user.click(toggle()); + expect(toggle()).toHaveAttribute('data-open'); + }); +}); + +describe('NavigationBar current page', () => { + it('markeert op een shootpagina het paneellink en alleen de sectie bij het hoofditem', async () => { + await renderBar('/soorten-fotoshoots/newborn'); + expect(panelLink('Newborn')).toHaveAttribute('aria-current', 'page'); + for (const name of SHOOTS.slice(1)) { + expect(panelLink(name)).not.toHaveAttribute('aria-current'); + } + const parent = screen.getByRole('link', { + name: 'Soorten fotoshoots', + }); + expect(parent).not.toHaveAttribute('aria-current'); + expect(parent).toHaveAttribute('data-section-current'); + }); + + it('markeert op het overzicht het hoofditem met beide', async () => { + await renderBar('/soorten-fotoshoots'); + const parent = screen.getByRole('link', { + name: 'Soorten fotoshoots', + }); + expect(parent).toHaveAttribute('aria-current', 'page'); + expect(parent).toHaveAttribute('data-section-current'); + for (const name of SHOOTS) { + expect(panelLink(name)).not.toHaveAttribute('aria-current'); + } + }); + + it('markeert op een andere pagina het hoofditem niet', async () => { + await renderBar('/portfolio'); + const parent = screen.getByRole('link', { + name: 'Soorten fotoshoots', + }); + expect(parent).not.toHaveAttribute('data-section-current'); + expect(parent).not.toHaveAttribute('aria-current'); + }); +}); diff --git a/web/src/components/NavigationBar/NavigationBar.tsx b/web/src/components/NavigationBar/NavigationBar.tsx index 6aa0e7b..b66778c 100644 --- a/web/src/components/NavigationBar/NavigationBar.tsx +++ b/web/src/components/NavigationBar/NavigationBar.tsx @@ -8,32 +8,65 @@ import { } from '@chakra-ui/react'; import NavLink from './NavLink'; import MobileNav from './MobileNav'; -import { mainNav } from '@/navigation'; +import NavSubmenu from './NavSubmenu'; +import { hasChildren, mainNav } from '@/navigation'; import RouterLink from '../RouterLink'; import useScrolledPast from '@/hooks/useScrolledPast'; -import { useCallback, useState } from 'react'; +import { isSectionCurrent } from '@/lib/navCurrent'; +import { initialNavMenuState, navMenuReducer } from '@/lib/navMenuState'; +import { useEffect, useReducer, useRef } from 'react'; import { useRouterState } from '@tanstack/react-router'; // Images import logoLight from '../../assets/logo-light.png'; import logoDark from '../../assets/logo-dark.png'; +// Het item met een submenu: bepaalt of het mobiele menu open start in een sectie +const parentItem = mainNav.find(hasChildren); + export default function NavigationBar() { - const [open, setOpen] = useState(false); - const closeMenu = useCallback(() => setOpen(false), []); + // Eén reducer voor het mobiele menu, de groep en het desktop-submenu, zodat + // ze elkaar niet tegenspreken + const [state, dispatch] = useReducer(navMenuReducer, initialNavMenuState); + const hamburgerRef = useRef<HTMLButtonElement>(null); + const submenuToggleRef = useRef<HTMLButtonElement>(null); // Het mobiele menu bestaat alleen onder lg; wordt het scherm breder, dan - // telt het als dicht. + // sluit de reducer het. Eerste render kan undefined geven: telt als mobiel. const isDesktop = useBreakpointValue( { base: false, lg: true }, { ssr: false }, ); - const menuOpen = open && !isDesktop; + useEffect(() => { + dispatch({ type: 'viewport', isDesktop: !!isDesktop }); + }, [isDesktop]); + + const pathname = useRouterState({ + select: (routerState) => routerState.location.pathname, + }); + const isHome = pathname === '/'; + + // Elke wissel van pagina sluit de menu's (ook de terugknop), maar niet + // bij de eerste render + const previousPathname = useRef(pathname); + useEffect(() => { + if (previousPathname.current === pathname) return; + previousPathname.current = pathname; + dispatch({ type: 'routeChanged' }); + }, [pathname]); + + // De reducer vraagt om focus (na Escape); hier wordt die verplaatst + useEffect(() => { + if (!state.focusRequest) return; + const target = + state.focusRequest === 'menuToggle' + ? hamburgerRef.current + : submenuToggleRef.current; + target?.focus(); + dispatch({ type: 'focusHandled' }); + }, [state.focusRequest]); const pastHero = useScrolledPast(() => 150); - const isHome = useRouterState({ - select: (state) => state.location.pathname === '/', - }); const isSolid = pastHero || !isHome; // Doorzichtig over de hero, maar alleen op desktop. Op mobiel staat de @@ -119,9 +152,21 @@ export default function NavigationBar() { > {mainNav.map((item) => ( <chakra.li key={item.to}> - <NavLink to={item.to}> - {item.label} - </NavLink> + {hasChildren(item) ? ( + <NavSubmenu + item={item} + id={`submenu-${item.to.slice(1)}`} + open={state.submenuOpen} + pathname={pathname} + transparent={!isSolid} + toggleRef={submenuToggleRef} + dispatch={dispatch} + /> + ) : ( + <NavLink to={item.to}> + {item.label} + </NavLink> + )} </chakra.li> ))} </HStack> @@ -134,13 +179,26 @@ export default function NavigationBar() { justifyContent="flex-end" > <chakra.button - onClick={() => setOpen(!menuOpen)} - aria-label={ - menuOpen ? 'Menu sluiten' : 'Menu openen' + ref={hamburgerRef} + onClick={() => + dispatch({ + type: 'toggleMenu', + inSection: parentItem + ? isSectionCurrent( + parentItem, + pathname, + ) + : false, + }) } - aria-expanded={menuOpen} + aria-label={ + state.menuOpen + ? 'Menu sluiten' + : 'Menu openen' + } + aria-expanded={state.menuOpen} aria-controls="mobile-nav" - data-open={menuOpen || undefined} + data-open={state.menuOpen || undefined} // Op desktop opent deze knop straks het info-menu (side area) display={{ base: 'block', lg: 'none' }} data-testid="nav-menu-toggle" @@ -189,7 +247,13 @@ export default function NavigationBar() { </Flex> </Container> </chakra.header> - <MobileNav id="mobile-nav" open={menuOpen} onClose={closeMenu} /> + <MobileNav + id="mobile-nav" + open={state.menuOpen} + groupOpen={state.groupOpen} + pathname={pathname} + dispatch={dispatch} + /> </> ); } diff --git a/web/src/components/NavigationBar/activeOptions.test.tsx b/web/src/components/NavigationBar/activeOptions.test.tsx new file mode 100644 index 0000000..818559c --- /dev/null +++ b/web/src/components/NavigationBar/activeOptions.test.tsx @@ -0,0 +1,108 @@ +import { cleanup, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { renderApp } from '@/test/renderApp'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import RouterLink from '../RouterLink'; + +// Regression probe of the router's `activeOptions` (BR-NAV-01, BR-NAV-04). +// The facts pinned here decide why every nav and footer link gets +// `{ exact: true, includeSearch: false }`: a plain `exact` ignores a trailing +// slash but not letter case, and loses `aria-current` on any query string. + +const bothVariants = [ + ['exact', { exact: true }], + ['exact + includeSearch false', { exact: true, includeSearch: false }], +] as const; + +async function currentOf( + variant: (typeof bothVariants)[number][1], + path: string, +) { + cleanup(); + await renderWithProviders( + <> + <RouterLink to="/soorten-fotoshoots" activeOptions={variant}> + parent + </RouterLink> + <RouterLink + to="/soorten-fotoshoots/newborn" + activeOptions={variant} + > + child + </RouterLink> + </>, + { path }, + ); + const isCurrent = (name: string) => + screen.getByRole('link', { name }).getAttribute('aria-current') === + 'page'; + return { parent: isCurrent('parent'), child: isCurrent('child') }; +} + +describe.each(bothVariants)('activeOptions %s', (_name, variant) => { + it('marks the exact path only', async () => { + expect(await currentOf(variant, '/soorten-fotoshoots')).toEqual({ + parent: true, + child: false, + }); + }); + + it('marks the child, not the parent, on the child path', async () => { + expect(await currentOf(variant, '/soorten-fotoshoots/newborn')).toEqual( + { parent: false, child: true }, + ); + }); + + it('ignores a trailing slash', async () => { + expect(await currentOf(variant, '/soorten-fotoshoots/')).toEqual({ + parent: true, + child: false, + }); + expect( + await currentOf(variant, '/soorten-fotoshoots/newborn/'), + ).toEqual({ parent: false, child: true }); + }); + + it('does not ignore letter case', async () => { + expect(await currentOf(variant, '/Soorten-Fotoshoots/Newborn')).toEqual( + { parent: false, child: false }, + ); + }); +}); + +describe('activeOptions and the query string', () => { + it('plain exact loses aria-current when the URL has a query', async () => { + expect( + await currentOf({ exact: true }, '/soorten-fotoshoots?x=1'), + ).toEqual({ parent: false, child: false }); + }); + + it('includeSearch false keeps aria-current with a query', async () => { + expect( + await currentOf( + { exact: true, includeSearch: false }, + '/soorten-fotoshoots?x=1', + ), + ).toEqual({ parent: true, child: false }); + }); + + it('includeSearch false keeps a non-matching page unmarked', async () => { + expect( + await currentOf( + { exact: true, includeSearch: false }, + '/portfolio?shoot=newborn', + ), + ).toEqual({ parent: false, child: false }); + }); +}); + +describe('activeOptions in the real route tree', () => { + it('renders the Newborn page on a case variant', async () => { + // The router matches case-insensitively, so the page shows; which + // links are current there is pinned in navSubmenu.test.tsx + await renderApp('/soorten-fotoshoots/Newborn'); + expect( + await screen.findByRole('heading', { level: 1 }), + ).toBeInTheDocument(); + }); +}); diff --git a/web/src/components/PackageBlock/PackageBlock.test.tsx b/web/src/components/PackageBlock/PackageBlock.test.tsx new file mode 100644 index 0000000..be86d29 --- /dev/null +++ b/web/src/components/PackageBlock/PackageBlock.test.tsx @@ -0,0 +1,95 @@ +import { screen, within } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import LinkButton from '@/components/LinkButton'; +import packages from '@/content/packages'; +import shootTypes from '@/content/shootTypes'; +import type { PricingPackage } from '@/content/types'; +import { formatPrice } from '@/lib/formatPrice'; +import { axeResults } from '@/test/axe'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import PackageBlock from './PackageBlock'; + +const newborn = shootTypes.find((shoot) => shoot.id === 'newborn')!; +const pkg: PricingPackage = packages.find( + (item) => item.id === newborn.packageId, +)!; +const onRequest = { price: 'Prijs op aanvraag', text: 'Neem contact op.' }; + +describe('PackageBlock', () => { + it('shows the price, the features, the actions and the note for a package', async () => { + const { container } = await renderWithProviders( + <PackageBlock + titleId="offer-title" + eyebrow="Het pakket" + title="Newbornshoot" + image={newborn.image} + pkg={pkg} + onRequest={onRequest} + note="Aanbetaling € 50." + data-testid="package" + > + <LinkButton variant="accent" to="/contact"> + Boek dit pakket + </LinkButton> + <a href="/contact">Eerst een vraag stellen</a> + </PackageBlock>, + ); + expect(screen.getByRole('heading', { level: 2 })).toHaveAttribute( + 'id', + 'offer-title', + ); + // The price keeps its non-breaking space + const price = screen.getByText(/185/); + expect(price.textContent).toBe(formatPrice(pkg.price)); + expect(price.textContent).toBe('€ 185'); + const list = screen.getByRole('list'); + const rows = within(list).getAllByRole('listitem'); + expect(rows.map((row) => row.textContent)).toEqual(pkg.features); + expect(screen.queryByText(onRequest.text)).toBeNull(); + expect( + screen.getByRole('link', { name: 'Boek dit pakket' }), + ).toBeInTheDocument(); + expect( + screen.getByRole('link', { name: 'Eerst een vraag stellen' }), + ).toBeInTheDocument(); + expect(screen.getByText('Aanbetaling € 50.')).toBeInTheDocument(); + expect(screen.getByTestId('package')).toBeInTheDocument(); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('shows the on-request price and text, without a list, when there is no package', async () => { + const { container } = await renderWithProviders( + <PackageBlock + titleId="offer-title" + eyebrow="Het aanbod" + title="Loveshoot" + image={newborn.image} + onRequest={onRequest} + > + <LinkButton variant="accent" to="/contact"> + Vraag naar de mogelijkheden + </LinkButton> + </PackageBlock>, + ); + expect(screen.getByText('Prijs op aanvraag')).toBeInTheDocument(); + expect(screen.getByText('Neem contact op.')).toBeInTheDocument(); + expect(screen.queryByRole('list')).toBeNull(); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('leaves out the note when there is none', async () => { + await renderWithProviders( + <PackageBlock + titleId="t" + eyebrow="e" + title="Titel" + image={newborn.image} + pkg={pkg} + onRequest={onRequest} + > + <a href="/contact">Actie</a> + </PackageBlock>, + ); + expect(screen.queryByText(/Aanbetaling/)).toBeNull(); + }); +}); diff --git a/web/src/components/PackageBlock/PackageBlock.tsx b/web/src/components/PackageBlock/PackageBlock.tsx new file mode 100644 index 0000000..397af93 --- /dev/null +++ b/web/src/components/PackageBlock/PackageBlock.tsx @@ -0,0 +1,94 @@ +import type { ReactNode } from 'react'; +import { Box, Flex, Heading, Text } from '@chakra-ui/react'; +import Eyebrow from '@/components/Eyebrow/Eyebrow'; +import MediaText from '@/components/MediaText/MediaText'; +import type { ContentImage, FrameColor, PricingPackage } from '@/content/types'; +import { formatPrice } from '@/lib/formatPrice'; + +type PackageBlockProps = { + // Id of the h2, which names the section around the block + titleId: string; + eyebrow: string; + title: string; + image: ContentImage; + frameColor?: FrameColor; + // Present: the price and the features. Absent: the on-request text. + pkg?: PricingPackage; + onRequest: { price: string; text: string }; + // Small print below the actions, e.g. the deposit + note?: string; + 'data-testid'?: string; + // The actions below the text, e.g. link buttons + children: ReactNode; +}; + +// The offer of a shoot page (FR-ST-07, BR-SP-60..62): a small square photo +// next to the price and either the features of the package or the text for +// a shoot without a fixed price. The variant follows from `pkg` alone. +export default function PackageBlock({ + titleId, + eyebrow, + title, + image, + frameColor, + pkg, + onRequest, + note, + 'data-testid': testId, + children, +}: PackageBlockProps) { + return ( + <MediaText + image={image} + aspectRatio="1 / 1" + mediaSize="small" + frameColor={frameColor} + data-testid={testId} + > + <Eyebrow>{eyebrow}</Eyebrow> + <Heading as="h2" id={titleId} textStyle="sectionTitle"> + {title} + </Heading> + <Text + fontFamily="heading" + fontSize="2.25rem" + lineHeight="1.2" + color="accent.deep" + mt={4} + > + {pkg ? formatPrice(pkg.price) : onRequest.price} + </Text> + {pkg ? ( + <Box as="ul" role="list" listStyle="none" m={0} p={0} mt={5}> + {pkg.features.map((feature, index) => ( + <Box + as="li" + key={`${index}-${feature}`} + py={3} + color="ink.soft" + borderTopWidth="1px" + borderColor="sand" + borderBottomWidth={ + index === pkg.features.length - 1 ? '1px' : 0 + } + > + {feature} + </Box> + ))} + </Box> + ) : ( + <Text color="ink.soft" mt={4}> + {onRequest.text} + </Text> + )} + <Flex wrap="wrap" align="center" columnGap={7} rowGap={3} mt={7}> + {children} + </Flex> + {note && ( + <Text fontSize="0.875rem" color="ink.soft" mt={5}> + {note} + </Text> + )} + </MediaText> + ); +} diff --git a/web/src/components/PageIntro/PageIntro.test.tsx b/web/src/components/PageIntro/PageIntro.test.tsx index 7db443c..429485c 100644 --- a/web/src/components/PageIntro/PageIntro.test.tsx +++ b/web/src/components/PageIntro/PageIntro.test.tsx @@ -28,4 +28,46 @@ describe('PageIntro', () => { 'Contact', ); }); + + it('renders exactly the old markup when the new props are left out', async () => { + const { container } = await renderWithProviders( + <PageIntro eyebrow="Werk" title="Portfolio"> + Intro + </PageIntro>, + ); + const section = container.querySelector('section')!; + expect(section.hasAttribute('aria-labelledby')).toBe(false); + expect([...section.children].map((child) => child.tagName)).toEqual([ + 'P', + 'H1', + 'P', + ]); + expect(section.querySelector('h1')!.hasAttribute('id')).toBe(false); + }); + + it('names the section by the h1 and shows the breadcrumb above the label', async () => { + const { container } = await renderWithProviders( + <PageIntro + eyebrow="Newborn" + title="Newbornshoot" + titleId="intro-title" + breadcrumb={<nav aria-label="Kruimelpad">Pad</nav>} + > + Intro + </PageIntro>, + ); + expect( + screen.getByRole('region', { name: 'Newbornshoot' }), + ).toBeInTheDocument(); + expect(screen.getByRole('heading', { level: 1 })).toHaveAttribute( + 'id', + 'intro-title', + ); + const nav = screen.getByRole('navigation', { name: 'Kruimelpad' }); + expect( + nav.compareDocumentPosition(screen.getByText('Newborn')) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(await axeResults(container)).toHaveNoViolations(); + }); }); diff --git a/web/src/components/PageIntro/PageIntro.tsx b/web/src/components/PageIntro/PageIntro.tsx index c43da7c..76006a5 100644 --- a/web/src/components/PageIntro/PageIntro.tsx +++ b/web/src/components/PageIntro/PageIntro.tsx @@ -1,29 +1,38 @@ import type { ReactNode } from 'react'; -import { Container, Heading, Text } from '@chakra-ui/react'; +import { Box, Container, Heading, Text } from '@chakra-ui/react'; import Eyebrow from '@/components/Eyebrow/Eyebrow'; type PageIntroProps = { title: string; eyebrow?: string; + // Id of the h1; the section is then named by it + titleId?: string; + // E.g. a Breadcrumb, shown above the eyebrow + breadcrumb?: ReactNode; children?: ReactNode; }; // Bovenste blok van een gewone pagina (.page-head in het design): label, -// de enige h1 van de pagina en een korte intro +// de enige h1 van de pagina en een korte intro. Optioneel een kruimelpad +// erboven en een id voor de h1 (de sectie krijgt daar zijn naam van). export default function PageIntro({ title, eyebrow, + titleId, + breadcrumb, children, }: PageIntroProps) { return ( <Container as="section" + aria-labelledby={titleId} pt="pageTop" pb={{ base: 8, md: 12, lg: 16 }} textAlign="center" > + {breadcrumb && <Box mb={{ base: 6, md: 7 }}>{breadcrumb}</Box>} {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>} - <Heading as="h1" textStyle="pageTitle" mb={4}> + <Heading as="h1" id={titleId} textStyle="pageTitle" mb={4}> {title} </Heading> {children && ( diff --git a/web/src/components/PhotoMosaic/PhotoMosaic.test.tsx b/web/src/components/PhotoMosaic/PhotoMosaic.test.tsx new file mode 100644 index 0000000..3515502 --- /dev/null +++ b/web/src/components/PhotoMosaic/PhotoMosaic.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, screen } from '@testing-library/react'; +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import type { ContentImage } from '@/content/types'; +import { contentImage } from '@/test/arbitraries'; +import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import PhotoMosaic from './PhotoMosaic'; + +const photo = (n: number): ContentImage => ({ + src: `/foto-${n}.jpg`, + alt: `Foto ${n}`, + width: 800, + height: 1200, +}); +const photos = (count: number) => + Array.from({ length: count }, (_, index) => photo(index + 1)); + +describe('PhotoMosaic', () => { + it.each([ + [2, 2], + [3, 3], + [4, 4], + [5, 4], + ])('shows %i photos as %i tiles', async (count, tiles) => { + const { container } = await renderWithProviders( + <PhotoMosaic images={photos(count)} data-testid="mosaic" />, + ); + const list = screen.getByTestId('mosaic'); + expect(list.tagName).toBe('UL'); + expect(screen.getAllByRole('listitem')).toHaveLength(tiles); + expect(screen.getAllByRole('img')).toHaveLength(tiles); + expect( + screen.getAllByRole('img').map((img) => img.getAttribute('alt')), + ).toEqual(photos(tiles).map((image) => image.alt)); + expect(container.querySelector('a, button')).toBeNull(); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('renders nothing without photos', async () => { + const { container } = await renderWithProviders( + <PhotoMosaic images={[]} />, + ); + expect(container.querySelector('ul')).toBeNull(); + }); + + it('places the tiles in a 4 x 2 grid from md and in two columns below', async () => { + await renderWithProviders(<PhotoMosaic images={photos(4)} />); + const rules = cssRulesFor(screen.getByRole('list')).join('\n'); + expect(rules).toContain('repeat(2, minmax(0, 1fr))'); + expect(rules).toMatch( + /min-width: 48rem[^}]*repeat\(4, minmax\(0, 1fr\)\)/, + ); + const second = cssRulesFor(screen.getAllByRole('listitem')[1]).join( + '\n', + ); + expect(second).toContain('span 2'); + expect(second).toMatch(/min-width: 48rem[^}]*grid-column: 3 ?\/ ?5/); + }); + + it('shows min(n, 4) photos with the given alt texts, in order (invariant)', async () => { + const images = fc.array(contentImage, { minLength: 2, maxLength: 6 }); + for (const sample of fc.sample(images, { numRuns: 6 })) { + const unique = sample.map((image, index) => ({ + ...image, + src: `${index}${image.src}`, + })); + await renderWithProviders(<PhotoMosaic images={unique} />); + const shown = screen.queryAllByRole('img'); + const expected = unique.slice(0, 4); + expect(document.querySelectorAll('li > img')).toHaveLength( + expected.length, + ); + expect( + [...document.querySelectorAll('li > img')].map((img) => + img.getAttribute('alt'), + ), + ).toEqual(expected.map((image) => image.alt)); + expect(shown.length).toBeLessThanOrEqual(4); + cleanup(); + } + }); +}); diff --git a/web/src/components/PhotoMosaic/PhotoMosaic.tsx b/web/src/components/PhotoMosaic/PhotoMosaic.tsx new file mode 100644 index 0000000..388fc34 --- /dev/null +++ b/web/src/components/PhotoMosaic/PhotoMosaic.tsx @@ -0,0 +1,69 @@ +import { Box } from '@chakra-ui/react'; +import DeferredImage from '@/components/DeferredImage/DeferredImage'; +import Reveal from '@/components/Reveal/Reveal'; +import type { ContentImage } from '@/content/types'; +import { MOSAIC_MAX_PHOTOS, mosaicLayout } from '@/lib/mosaicLayout'; + +type PhotoMosaicProps = { + images: readonly ContentImage[]; + 'data-testid'?: string; +}; + +// A mosaic of up to four photos (FR-ST-05, BR-SP-30b..35): a 4 x 2 grid from +// `md`, two columns on phones. Only a picture: no link, no button, no +// hover effect. The photos fill their cells, so their own size never sets a +// row height. Renders nothing without photos. +export default function PhotoMosaic({ + images, + 'data-testid': testId, +}: PhotoMosaicProps) { + const shown = images.slice(0, MOSAIC_MAX_PHOTOS); + const tiles = mosaicLayout(shown.length); + if (tiles.length === 0) return null; + + return ( + <Box + as="ul" + role="list" + listStyle="none" + m={0} + p={0} + display="grid" + gridTemplateColumns={{ + base: 'repeat(2, minmax(0, 1fr))', + md: 'repeat(4, minmax(0, 1fr))', + }} + gridTemplateRows={{ + md: 'repeat(2, clamp(12rem, 22vw, 18.75rem))', + }} + gap="gridGap" + data-testid={testId} + > + {tiles.map((tile, index) => ( + <Reveal + as="li" + key={shown[index].src} + delay={index * 0.08} + position="relative" + overflow="hidden" + bg="paper.deep" + gridColumn={{ + base: tile.wide ? 'span 2' : 'auto', + md: tile.column, + }} + gridRow={{ md: tile.row }} + aspectRatio={{ base: tile.phoneRatio, md: 'auto' }} + > + <DeferredImage + image={shown[index]} + position="absolute" + inset={0} + w="100%" + h="100%" + objectFit="cover" + /> + </Reveal> + ))} + </Box> + ); +} diff --git a/web/src/components/ProcessTimeline/ProcessTimeline.test.tsx b/web/src/components/ProcessTimeline/ProcessTimeline.test.tsx new file mode 100644 index 0000000..689f793 --- /dev/null +++ b/web/src/components/ProcessTimeline/ProcessTimeline.test.tsx @@ -0,0 +1,144 @@ +import { cleanup, screen, within } from '@testing-library/react'; +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { processIcons } from '@/components/shoots/ProcessIcons/ProcessIcons'; +import shootPageShared from '@/content/shootPageShared'; +import { PROCESS_STEP_ORDER } from '@/lib/shootPageView'; +import { timelineSteps } from '@/test/arbitraries'; +import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import ProcessTimeline from './ProcessTimeline'; + +const six = PROCESS_STEP_ORDER.map((id) => { + const Icon = processIcons[id]; + return { + id, + title: shootPageShared.process.steps[id].title, + text: shootPageShared.process.steps[id].text, + icon: <Icon />, + }; +}); + +describe('ProcessTimeline', () => { + it('lists six steps in order, each with an h3 and a text', async () => { + const { container } = await renderWithProviders( + <ProcessTimeline steps={six} data-testid="timeline" />, + ); + const list = screen.getByRole('list'); + expect(list.tagName).toBe('OL'); + const items = within(list).getAllByRole('listitem'); + expect(items).toHaveLength(6); + items.forEach((item, index) => { + expect( + within(item).getByRole('heading', { level: 3 }), + ).toHaveTextContent(six[index].title); + expect(within(item).getByText(six[index].text)).toBeInTheDocument(); + }); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('puts the text above the line for even indexes and below for odd ones', async () => { + await renderWithProviders(<ProcessTimeline steps={six} />); + const positions = screen + .getAllByRole('listitem') + .map((item) => + item + .querySelector('[data-text-position]')! + .getAttribute('data-text-position'), + ); + expect(positions).toEqual([ + 'above', + 'below', + 'above', + 'below', + 'above', + 'below', + ]); + }); + + it('fills only the last marker and hides every marker and line from assistive technology', async () => { + const { container } = await renderWithProviders( + <ProcessTimeline steps={six} data-testid="timeline" />, + ); + const markers = screen.getAllByTestId('timeline-marker'); + expect(markers.map((m) => m.getAttribute('data-filled'))).toEqual([ + 'false', + 'false', + 'false', + 'false', + 'false', + 'true', + ]); + for (const marker of markers) { + expect(marker).toHaveAttribute('aria-hidden', 'true'); + } + const lines = container.querySelectorAll('li > span'); + // One horizontal line per step, one vertical line per step but the + // last + expect(lines).toHaveLength(6 + 5); + for (const line of lines) { + expect(line).toHaveAttribute('aria-hidden', 'true'); + } + }); + + it('is one column up to lg and a grid of one column per step from lg', async () => { + await renderWithProviders(<ProcessTimeline steps={six} />); + const rules = cssRulesFor(screen.getByRole('list')).join('\n'); + expect(rules).toMatch( + /min-width: 64rem[^}]*repeat\(6, minmax\(0, 1fr\)\)/, + ); + expect(rules).toContain('max-width: 34rem'); + }); + + it('lines the markers up with subgrid rows from lg', async () => { + await renderWithProviders(<ProcessTimeline steps={six} />); + const rules = cssRulesFor(screen.getAllByRole('listitem')[0]).join(); + expect(rules).toContain('subgrid'); + }); + + it('lays out one step and works without icons, in the alt tone', async () => { + const { container } = await renderWithProviders( + <ProcessTimeline + tone="alt" + steps={[{ id: 'a', title: 'Eén', text: 'Alleen' }]} + />, + ); + expect(screen.getAllByRole('listitem')).toHaveLength(1); + expect(container.querySelectorAll('svg')).toHaveLength(0); + expect( + container.querySelector('li > span[aria-hidden]'), + ).not.toBeNull(); + }); + + it('renders nothing without steps', async () => { + const { container } = await renderWithProviders( + <ProcessTimeline steps={[]} />, + ); + expect(container.querySelector('ol')).toBeNull(); + }); + + it('keeps the order and adds no numbers for any steps (invariant)', async () => { + for (const steps of fc.sample(timelineSteps, { numRuns: 6 })) { + const { container } = await renderWithProviders( + <ProcessTimeline steps={steps} />, + ); + const items = container.querySelectorAll('ol > li'); + expect(items).toHaveLength(steps.length); + items.forEach((item, index) => { + expect(item.querySelectorAll('h3')).toHaveLength(1); + expect(item.querySelector('h3')!.textContent).toBe( + steps[index].title, + ); + // Nothing but the title and the text is visible text + expect(item.textContent).toBe( + steps[index].title + steps[index].text, + ); + for (const hidden of item.querySelectorAll('[aria-hidden]')) { + expect(hidden.textContent).toBe(''); + } + }); + cleanup(); + } + }); +}); diff --git a/web/src/components/ProcessTimeline/ProcessTimeline.tsx b/web/src/components/ProcessTimeline/ProcessTimeline.tsx new file mode 100644 index 0000000..876ecc8 --- /dev/null +++ b/web/src/components/ProcessTimeline/ProcessTimeline.tsx @@ -0,0 +1,164 @@ +import type { ReactNode } from 'react'; +import { Box, Flex, Heading, Text } from '@chakra-ui/react'; +import Reveal from '@/components/Reveal/Reveal'; + +// Height and width of a marker, and so the height of the middle row +const MARKER = '3.5rem'; + +type TimelineStep = { + id: string; + title: string; + text: string; + // A decorative icon, e.g. from ProcessIcons + icon?: ReactNode; +}; + +type ProcessTimelineProps = { + steps: readonly TimelineStep[]; + // The band colour: the markers use it to hide the line behind them + tone?: 'paper' | 'alt'; + 'data-testid'?: string; +}; + +// The steps of a process as a timeline (FR-ST-04, BR-SP-20..26): vertical +// with the text beside each marker below `lg`, horizontal from `lg` with +// the texts alternating above and below the line. One ordered list in both +// layouts, so the reading order is the order of the steps. The line, the +// markers and the icons are decoration only. +export default function ProcessTimeline({ + steps, + tone = 'paper', + 'data-testid': testId, +}: ProcessTimelineProps) { + if (steps.length === 0) return null; + const background = tone === 'alt' ? 'paper.alt' : 'paper'; + + return ( + <Reveal data-testid={testId}> + <Box + as="ol" + role="list" + listStyle="none" + m={0} + p={0} + maxW={{ base: '34rem', lg: 'none' }} + mx="auto" + display={{ lg: 'grid' }} + gridTemplateColumns={{ + lg: `repeat(${steps.length}, minmax(0, 1fr))`, + }} + gridTemplateRows={{ lg: `auto ${MARKER} auto` }} + > + {steps.map((step, index) => { + const first = index === 0; + const last = index === steps.length - 1; + const above = index % 2 === 0; + return ( + <Box + as="li" + key={step.id} + position="relative" + display="grid" + gridTemplateColumns={{ + base: `${MARKER} 1fr`, + lg: 'minmax(0, 1fr)', + }} + columnGap={{ base: 5, lg: 0 }} + pb={{ base: last ? 0 : 8, lg: 0 }} + gridRow={{ lg: '1 / 4' }} + // The rows of the list itself, so the markers line + // up whatever the text heights are. Subgrid is + // supported by every current browser; a style prop + // cannot hold a fallback for older ones. + gridTemplateRows={{ lg: 'subgrid' }} + > + {/* The line down to the next marker (vertical + layout); the next marker hides its end */} + {!last && ( + <Box + as="span" + aria-hidden="true" + display={{ base: 'block', lg: 'none' }} + position="absolute" + left={`calc(${MARKER} / 2 - 1px)`} + top={`calc(${MARKER} / 2)`} + bottom={`calc(${MARKER} / -2)`} + w="2px" + bg="sand" + /> + )} + {/* The line through the marker (horizontal + layout), from the first to the last centre */} + <Box + as="span" + aria-hidden="true" + display={{ base: 'none', lg: 'block' }} + gridRow={{ lg: 2 }} + gridColumn={{ lg: 1 }} + alignSelf="center" + h="2px" + bg="sand" + ml={first ? '50%' : 0} + mr={last ? '50%' : 0} + /> + <Flex + aria-hidden="true" + data-testid={ + testId ? `${testId}-marker` : undefined + } + data-filled={last ? 'true' : 'false'} + position="relative" + zIndex={1} + align="center" + justify="center" + w={MARKER} + h={MARKER} + borderRadius="full" + borderWidth="1.5px" + borderColor="accent.deep" + bg={last ? 'accent.deep' : background} + color={last ? 'white' : 'accent.deep'} + gridRow={{ base: 1, lg: 2 }} + gridColumn={1} + justifySelf={{ lg: 'center' }} + > + {step.icon} + </Flex> + <Box + data-text-position={above ? 'above' : 'below'} + gridColumn={{ base: 2, lg: 1 }} + gridRow={{ base: 1, lg: above ? 1 : 3 }} + alignSelf={{ + base: 'start', + lg: above ? 'end' : 'start', + }} + pt={{ base: 3, lg: above ? 0 : 6 }} + pb={{ lg: above ? 6 : 0 }} + px={{ lg: 3 }} + textAlign={{ lg: 'center' }} + > + <Heading + as="h3" + fontFamily="heading" + fontWeight="normal" + fontSize="xl" + lineHeight="1.2" + > + {step.title} + </Heading> + <Text + mt={2} + fontSize="0.9375rem" + lineHeight="1.6" + color="ink.soft" + > + {step.text} + </Text> + </Box> + </Box> + ); + })} + </Box> + </Reveal> + ); +} diff --git a/web/src/components/StatusPage/NotFound.tsx b/web/src/components/StatusPage/NotFound.tsx index dd69fd7..add323c 100644 --- a/web/src/components/StatusPage/NotFound.tsx +++ b/web/src/components/StatusPage/NotFound.tsx @@ -1,14 +1,45 @@ +import { useRouterState } from '@tanstack/react-router'; +import { isShootSectionPath } from '@/lib/isShootSectionPath'; +import LinkButton from '../LinkButton'; import StatusPage from './StatusPage'; // Pagina voor een onbekende URL, binnen de shell (FR-09). Een globale // not-found heeft geen eigen route-head; React 19 zet <title> en <meta> // daarom zelf in <head> en haalt ze weer weg bij het verlaten (BR-404-02). +// Onder /soorten-fotoshoots/ komt er een knop naar het overzicht bij +// (FR-ST-14). export default function NotFound() { + const pathname = useRouterState({ + select: (routerState) => routerState.location.pathname, + }); + return ( <> <title>Pagina niet gevonden | Andrea Slop Fotografie - + + + Terug naar Soorten fotoshoots + + + Terug naar home + + + ) : undefined + } + > Deze pagina bestaat niet (meer). Misschien is de link verouderd of zit er een typfout in het adres. diff --git a/web/src/components/StatusPage/StatusPage.test.tsx b/web/src/components/StatusPage/StatusPage.test.tsx index 5e70da2..cb2e2f9 100644 --- a/web/src/components/StatusPage/StatusPage.test.tsx +++ b/web/src/components/StatusPage/StatusPage.test.tsx @@ -29,6 +29,35 @@ describe('NotFound', () => { document.head.querySelector('meta[name="robots"]'), ).toHaveAttribute('content', 'noindex'); }); + + it('toont onder /soorten-fotoshoots/ twee knoppen in vaste volgorde', async () => { + const { container } = await renderWithProviders(, { + path: '/soorten-fotoshoots/niet-bestaande-shoot', + }); + const links = screen.getAllByRole('link'); + expect(links.map((link) => link.textContent)).toEqual([ + 'Terug naar Soorten fotoshoots', + 'Terug naar home', + ]); + expect(links[0]).toHaveAttribute('href', '/soorten-fotoshoots'); + expect(links[1]).toHaveAttribute('href', '/'); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('herkent het prefix hoofdletterongevoelig', async () => { + await renderWithProviders(, { + path: '/Soorten-Fotoshoots/x', + }); + expect(screen.getAllByRole('link')).toHaveLength(2); + expect( + screen.getByRole('link', { name: 'Terug naar Soorten fotoshoots' }), + ).toHaveAttribute('href', '/soorten-fotoshoots'); + }); + + it('houdt buiten de sectie één knop', async () => { + await renderWithProviders(, { path: '/bestaat-niet' }); + expect(screen.getAllByRole('link')).toHaveLength(1); + }); }); describe('ErrorPage', () => { diff --git a/web/src/components/shoots/ProcessIcons/ProcessIcons.test.tsx b/web/src/components/shoots/ProcessIcons/ProcessIcons.test.tsx new file mode 100644 index 0000000..af0f341 --- /dev/null +++ b/web/src/components/shoots/ProcessIcons/ProcessIcons.test.tsx @@ -0,0 +1,41 @@ +import { render } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { PROCESS_STEP_ORDER } from '@/lib/shootPageView'; +import { axeResults } from '@/test/axe'; +import { processIcons } from './ProcessIcons'; + +describe('processIcons', () => { + it('has exactly one icon for every step of the process', () => { + expect(Object.keys(processIcons).sort()).toEqual( + [...PROCESS_STEP_ORDER].sort(), + ); + }); + + it.each(PROCESS_STEP_ORDER)( + 'draws the %s icon as a hidden, unfocusable 24 px svg without a title', + (id) => { + const Icon = processIcons[id]; + const { container } = render(); + const svg = container.querySelector('svg')!; + expect(svg).toHaveAttribute('aria-hidden', 'true'); + expect(svg).toHaveAttribute('focusable', 'false'); + expect(svg).toHaveAttribute('viewBox', '0 0 24 24'); + expect(svg).toHaveAttribute('width', '24'); + expect(svg).toHaveAttribute('height', '24'); + expect(svg.querySelector('title')).toBeNull(); + expect(svg.children.length).toBeGreaterThan(0); + }, + ); + + it('has no accessibility violations', async () => { + const { container } = render( +
+ {PROCESS_STEP_ORDER.map((id) => { + const Icon = processIcons[id]; + return ; + })} +
, + ); + expect(await axeResults(container)).toHaveNoViolations(); + }); +}); diff --git a/web/src/components/shoots/ProcessIcons/ProcessIcons.tsx b/web/src/components/shoots/ProcessIcons/ProcessIcons.tsx new file mode 100644 index 0000000..d0498f7 --- /dev/null +++ b/web/src/components/shoots/ProcessIcons/ProcessIcons.tsx @@ -0,0 +1,76 @@ +import type { ReactElement, ReactNode } from 'react'; +import type { ProcessStepId } from '@/content/types'; + +// One decorative 24 x 24 icon of the process timeline (design E, stroke +// icons in the text colour). Hidden from assistive technology: the step +// title says everything. +function Icon({ children }: { children: ReactNode }) { + return ( + + ); +} + +// The icon of every step; the Record makes a missing step a compile error +export const processIcons: Record ReactElement> = { + // Envelope + aanvragen: () => ( + + + + + ), + // Calendar with a heart + datum: () => ( + + + + + + + ), + // Coin + aanbetaling: () => ( + + + + + + ), + // Camera + shoot: () => ( + + + + + ), + // Sliders + bewerking: () => ( + + + + + + + ), + // Picture + oplevering: () => ( + + + + + + ), +}; diff --git a/web/src/components/shoots/ShootBlock/ShootBlock.test.tsx b/web/src/components/shoots/ShootBlock/ShootBlock.test.tsx index cd642b7..a63ea69 100644 --- a/web/src/components/shoots/ShootBlock/ShootBlock.test.tsx +++ b/web/src/components/shoots/ShootBlock/ShootBlock.test.tsx @@ -79,4 +79,31 @@ describe('ShootBlock', () => { expect(main).not.toHaveAttribute('loading', 'lazy'); expect(detail).toHaveAttribute('loading', 'lazy'); }); + + it.each([ + ['newborn', 'Lees meer over de newbornshoot'], + ['zwangerschap', 'Lees meer over de zwangerschapsshoot'], + ['gezin', 'Lees meer over de gezinsshoot'], + ['loveshoot', 'Lees meer over de loveshoot'], + ['portret', 'Lees meer over de portretshoot'], + ])('links %s to its own page with the text "%s"', async (id, text) => { + await renderBlock(id); + const link = screen.getByRole('link', { name: text }); + expect(link).toHaveAttribute('href', `/soorten-fotoshoots/${id}`); + expect(link).toBe(screen.getByTestId(`shoot-${id}-readmore`)); + // The visible text is the name: no aria-label + expect(link).not.toHaveAttribute('aria-label'); + }); + + it('puts the page link first in the row, before the contact link', async () => { + await renderBlock('newborn', { portfolioLink: true }); + const links = within( + screen.getByRole('article', { name: 'Newborn' }), + ).getAllByRole('link'); + expect(links.map((link) => link.getAttribute('data-testid'))).toEqual([ + 'shoot-newborn-readmore', + 'shoot-newborn-contact', + 'shoot-newborn-portfolio', + ]); + }); }); diff --git a/web/src/components/shoots/ShootBlock/ShootBlock.tsx b/web/src/components/shoots/ShootBlock/ShootBlock.tsx index ae74192..e5a2f1e 100644 --- a/web/src/components/shoots/ShootBlock/ShootBlock.tsx +++ b/web/src/components/shoots/ShootBlock/ShootBlock.tsx @@ -4,7 +4,9 @@ import { Box, Flex, Heading, Link, Stack, Text } from '@chakra-ui/react'; import { Link as RouterLink } from '@tanstack/react-router'; import MediaText from '@/components/MediaText/MediaText'; import type { PricingPackage, ShootType } from '@/content/types'; +import { readMoreLabel } from '@/lib/readMoreLabel'; import { shootContactLink, shootPortfolioLink } from '@/lib/shootLinks'; +import { shootPagePath } from '@/lib/shootPages'; type ShootBlockProps = { shoot: ShootType; @@ -21,7 +23,7 @@ type ShootBlockProps = { const linkStyle = { py: 2.5, display: 'inline-block' } as const; // One kind of shoot (design .shoot): its photo next to the name, the text -// and the links. The article is the anchor (#newborn) and is named by its +// and the links, the first of which leads to the shoot's own page. The article is the anchor (#newborn) and is named by its // heading. export default function ShootBlock({ shoot, @@ -59,6 +61,16 @@ export default function ShootBlock({ ))} + {/* The visible text already differs per shoot, so no + aria-label is needed to tell the links apart */} + + + {readMoreLabel(shoot)} + + {/* Five links say "Stuur een berichtje"; the full name tells screen reader users which shoot each is about. diff --git a/web/src/components/shoots/ShootList/ShootList.test.tsx b/web/src/components/shoots/ShootList/ShootList.test.tsx index 080007b..901b164 100644 --- a/web/src/components/shoots/ShootList/ShootList.test.tsx +++ b/web/src/components/shoots/ShootList/ShootList.test.tsx @@ -74,4 +74,23 @@ describe('ShootList', () => { ); expect(tones).toEqual([false, true, false, true, false]); }); + + it('gives every shoot its own page link, first in its row, with a unique name', async () => { + await renderList(); + const ids = shootTypes.map((shoot) => shoot.id); + const names = ids.map((id) => { + const link = screen.getByTestId(`shoot-${id}-readmore`); + expect(link).toHaveAttribute('href', `/soorten-fotoshoots/${id}`); + const article = link.closest('article')!; + expect(within(article).getAllByRole('link')[0]).toBe(link); + return link.textContent; + }); + expect(new Set(names).size).toBe(ids.length); + // The other links are still there + for (const id of ids) { + expect( + screen.getByTestId(`shoot-${id}-contact`), + ).toBeInTheDocument(); + } + }); }); diff --git a/web/src/components/shoots/ShootPage/ShootPage.test.tsx b/web/src/components/shoots/ShootPage/ShootPage.test.tsx index 6099ec4..28c24e3 100644 --- a/web/src/components/shoots/ShootPage/ShootPage.test.tsx +++ b/web/src/components/shoots/ShootPage/ShootPage.test.tsx @@ -1,26 +1,66 @@ -import { screen } from '@testing-library/react'; +import { screen, within } from '@testing-library/react'; import { describe, expect, it } from 'vitest'; +import loveshootPage from '@/content/shootPages/loveshoot'; import newbornPage from '@/content/shootPages/newborn'; import shootPageShared from '@/content/shootPageShared'; import packages from '@/content/packages'; import shootTypes from '@/content/shootTypes'; import siteContent from '@/content/siteContent'; -import { shootPageView } from '@/lib/shootPageView'; +import type { ShootTypeId } from '@/content/types'; +import { shootPageView, type ShootPageView } from '@/lib/shootPageView'; import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; import { renderWithProviders } from '@/test/renderWithProviders'; import ShootPage from './ShootPage'; -const view = shootPageView('newborn', newbornPage, { +const sources = { shootTypes, packages, shared: shootPageShared, site: siteContent, portfolioShoots: [], -}); +}; + +const viewOf = (id: ShootTypeId, page = newbornPage) => { + const view = shootPageView(id, page, { + ...sources, + portfolioShoots: [id], + }); + if (view === undefined) throw new Error(`no view for ${id}`); + return view; +}; + +const view = viewOf('newborn'); +const loveshootView = viewOf('loveshoot', loveshootPage as typeof newbornPage); +const withoutFaq: ShootPageView = (() => { + const copy = shootPageView( + 'newborn', + { ...newbornPage, faq: { ...newbornPage.faq, items: [] } }, + sources, + ); + if (copy === undefined) throw new Error('no view'); + return copy; +})(); + +// The heading levels and texts in page order +const outline = (container: HTMLElement) => + [...container.querySelectorAll('h1, h2, h3, h4, h5, h6')].map( + (heading) => ({ + level: Number(heading.tagName[1]), + text: heading.textContent, + }), + ); + +// No heading level is skipped when going down the page +const expectNoSkippedLevel = (levels: number[]) => { + expect(levels[0]).toBe(1); + levels.slice(1).forEach((level, index) => { + expect(level).toBeLessThanOrEqual(levels[index] + 1); + }); +}; describe('ShootPage', () => { it('toont label, de enige h1 en de intro', async () => { - if (view === undefined) throw new Error('no view for newborn'); const { container } = await renderWithProviders( , ); @@ -32,4 +72,129 @@ describe('ShootPage', () => { expect(screen.getByText(view.intro.text)).toBeInTheDocument(); expect(await axeResults(container)).toHaveNoViolations(); }); + + it('has a clean heading outline for newborn: h1, h2 per section, h3 per step', async () => { + const { container } = await renderWithProviders( + , + ); + const headings = outline(container); + expectNoSkippedLevel(headings.map((heading) => heading.level)); + expect(headings.filter((h) => h.level === 1)).toHaveLength(1); + expect(headings.filter((h) => h.level === 3)).toHaveLength(6); + expect( + headings.filter((h) => h.level === 2).map((h) => h.text), + ).toEqual([ + ...view.stories.map((story) => story.title), + view.process.title, + view.photos!.title, + view.faq!.title, + view.offer.title, + view.closing.title, + ]); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('has a clean heading outline for the loveshoot, without a mosaic', async () => { + const { container } = await renderWithProviders( + , + ); + expectNoSkippedLevel(outline(container).map((h) => h.level)); + expect(container.querySelector('#impressie')).toBeNull(); + expect(screen.queryByTestId('photo-mosaic')).toBeNull(); + expect(container.querySelector('#vragen')).not.toBeNull(); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('leaves out the FAQ section and keeps the outline valid when there are no questions', async () => { + const { container } = await renderWithProviders( + , + ); + expect(container.querySelector('#vragen')).toBeNull(); + expect(screen.queryByTestId('faq-list')).toBeNull(); + expectNoSkippedLevel(outline(container).map((h) => h.level)); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('names every section by an existing heading and offers the anchors', async () => { + const { container } = await renderWithProviders( + , + ); + const sections = container.querySelectorAll('section'); + expect(sections.length).toBe(view.stories.length + 6); + for (const section of sections) { + const target = section.getAttribute('aria-labelledby')!; + expect(target).toBeTruthy(); + expect(container.querySelector(`#${target}`)).not.toBeNull(); + } + for (const anchor of [ + 'zo-werkt-het', + 'impressie', + 'vragen', + 'pakket', + ]) { + expect(container.querySelector(`section#${anchor}`)).not.toBeNull(); + } + }); + + it('never gives two adjacent bands the same colour', async () => { + const { container } = await renderWithProviders( + , + ); + const sections = [ + ...screen + .getByTestId('shoot-page') + .querySelectorAll(':scope > section'), + ]; + const alt = sections.map((section) => + cssRulesFor(section).join().includes('var(--slp-colors-paper-alt)'), + ); + // The intro is paper; every band after it alternates + // The intro and the first story are both paper on purpose: the + // story has no space above it and continues the intro (flushTop). + // From the first story on, the bands alternate. + expect(alt[0]).toBe(false); + const bands = alt.slice(1); + bands.forEach((isAlt, index) => { + expect(isAlt).toBe(index % 2 === 1); + }); + expect(sections).toHaveLength(view.stories.length + 6); + expect(container).toBeTruthy(); + }); + + it('shows the breadcrumb, the package with its actions and the closing button', async () => { + await renderWithProviders(); + const crumb = screen.getByTestId('shoot-breadcrumb'); + expect(within(crumb).getAllByRole('link')).toHaveLength(2); + const offer = screen.getByTestId('package-block'); + expect( + within(offer).getByRole('link', { name: view.offer.bookLabel }), + ).toHaveAttribute('href', '/contact?pakket=newborn'); + expect( + within(offer).getByRole('link', { name: view.offer.askLabel }), + ).toHaveAttribute('href', '/contact'); + expect( + within(screen.getByTestId('shoot-closing')).getByRole('link', { + name: view.closing.buttonLabel, + }), + ).toHaveAttribute('href', '/contact?pakket=newborn'); + expect( + screen.getByRole('link', { + name: `Bekijk meer ${view.shoot.photosLabel}`, + }), + ).toHaveAttribute('href', '/portfolio?shoot=newborn'); + }); + + it('shows one primary button and no price for a shoot on request', async () => { + await renderWithProviders(); + const offer = screen.getByTestId('package-block'); + expect( + within(offer).getByText(loveshootView.offer.onRequest.price), + ).toBeInTheDocument(); + expect(within(offer).getAllByRole('link')).toHaveLength(1); + expect( + within(offer).getByRole('link', { + name: loveshootView.offer.onRequest.linkLabel, + }), + ).toHaveAttribute('href', '/contact'); + }); }); diff --git a/web/src/components/shoots/ShootPage/ShootPage.tsx b/web/src/components/shoots/ShootPage/ShootPage.tsx index 396345a..803bfd3 100644 --- a/web/src/components/shoots/ShootPage/ShootPage.tsx +++ b/web/src/components/shoots/ShootPage/ShootPage.tsx @@ -1,17 +1,217 @@ +import type { ReactElement } from 'react'; +import { Box, Flex, Grid, Heading, Link, useRecipe } from '@chakra-ui/react'; +// The router's own Link keeps the route types, so `search` is checked +// against the target route (as in ShootBlock) +import { Link as RouterLink } from '@tanstack/react-router'; +import Breadcrumb from '@/components/Breadcrumb/Breadcrumb'; +import CallToAction from '@/components/CallToAction/CallToAction'; +import Eyebrow from '@/components/Eyebrow/Eyebrow'; +import FaqList from '@/components/FaqList/FaqList'; +import PackageBlock from '@/components/PackageBlock/PackageBlock'; import PageIntro from '@/components/PageIntro/PageIntro'; +import PageSection from '@/components/PageSection/PageSection'; +import PhotoMosaic from '@/components/PhotoMosaic/PhotoMosaic'; +import ProcessTimeline from '@/components/ProcessTimeline/ProcessTimeline'; +import RichParagraph from '@/components/RichParagraph/RichParagraph'; +import SectionHeading from '@/components/SectionHeading/SectionHeading'; +import { processIcons } from '@/components/shoots/ProcessIcons/ProcessIcons'; +import StoryBlocks from '@/components/shoots/StoryBlocks/StoryBlocks'; +import { shootPageBands, type SectionBand } from '@/lib/shootPageBands'; import type { ShootPageView } from '@/lib/shootPageView'; type ShootPageProps = { view: ShootPageView; }; -// One shoot page. For now only the page head with the h1; unit 2 adds the -// sections in the order of the page structure. +// Links under or beside a text: room around them for a 44px touch target +const linkStyle = { py: 2.5, display: 'inline-block' } as const; + +// One shoot page (FR-ST-02..08): the intro with the breadcrumb, the story +// blocks, the process timeline, the photos and the FAQ when there are any, +// the offer and the closing block, in the order and colours of +// shootPageBands. Everything comes from the view; nothing is stored here. export default function ShootPage({ view }: ShootPageProps) { - const { intro } = view; + const { intro, shoot, offer } = view; + const linkButton = useRecipe({ key: 'linkButton' }); + // The accent button style for the router's own Link, which keeps the + // route types, so `search` is checked against /contact (as PriceCard) + const accentButton = linkButton({ variant: 'accent' }); + const bands = shootPageBands(view); + const tone = (id: SectionBand['id']) => + bands.find((band) => band.id === id)?.tone ?? 'paper'; + return ( - - {intro.text} - + + + } + > + {intro.text} + + + + + + + { + // An id without an icon gets none (BR-SP-74) + const Icon: (() => ReactElement) | undefined = + processIcons[step.id]; + return { + id: step.id, + title: step.title, + text: step.text, + icon: Icon ? : undefined, + }; + })} + tone={tone('process')} + data-testid="process-timeline" + /> + + + {view.photos && ( + + + + {view.photos.eyebrow} + + {view.photos.title} + + + {view.photos.portfolioLink && ( + + + Bekijk meer {shoot.photosLabel} + + + )} + + + + )} + + {view.faq && ( + + + + {view.faq.eyebrow} + + {view.faq.title} + + + + + + + )} + + + + {offer.pkg ? ( + <> + + + {offer.bookLabel} + + + + + {offer.askLabel} + + + + ) : ( + + + {offer.onRequest.linkLabel} + + + )} + + + + } + tone={tone('closing')} + data-testid="shoot-closing" + > + + + {view.closing.buttonLabel} + + + + ); } diff --git a/web/src/components/shoots/StoryBlocks/StoryBlocks.test.tsx b/web/src/components/shoots/StoryBlocks/StoryBlocks.test.tsx new file mode 100644 index 0000000..652493d --- /dev/null +++ b/web/src/components/shoots/StoryBlocks/StoryBlocks.test.tsx @@ -0,0 +1,119 @@ +import { screen, within } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import loveshootPage from '@/content/shootPages/loveshoot'; +import newbornPage from '@/content/shootPages/newborn'; +import type { StoryBlock } from '@/content/types'; +import { axeResults } from '@/test/axe'; +import { cssRulesFor } from '@/test/cssRules'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import StoryBlocks from './StoryBlocks'; + +const tone = (element: HTMLElement) => + cssRulesFor(element).join().includes('var(--slp-colors-paper-alt)') + ? 'alt' + : 'paper'; + +describe('StoryBlocks', () => { + it('shows one section per newborn story, each named by its h2', async () => { + const stories = newbornPage.stories; + const { container } = await renderWithProviders( + , + ); + expect(container.querySelectorAll('section')).toHaveLength(4); + for (const story of stories) { + const section = screen.getByTestId(`story-${story.id}`); + expect(screen.getByRole('region', { name: story.title })).toBe( + section, + ); + expect( + within(section).getByRole('heading', { level: 2 }), + ).toHaveTextContent(story.title); + } + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('loads only the first photo with priority and alternates the tones', async () => { + const stories = newbornPage.stories; + await renderWithProviders( + , + ); + const images = screen.getAllByRole('img'); + expect(images).toHaveLength(stories.length); + expect(images[0]).toHaveAttribute('fetchpriority', 'high'); + expect(images[0]).not.toHaveAttribute('loading', 'lazy'); + for (const image of images.slice(1)) { + expect(image).toHaveAttribute('loading', 'lazy'); + expect(image).not.toHaveAttribute('fetchpriority'); + } + expect( + stories.map((story) => + tone(screen.getByTestId(`story-${story.id}`)), + ), + ).toEqual(['paper', 'alt', 'paper', 'alt']); + }); + + it('gives the loveshoot one photo and three text-only bands', async () => { + const { container } = await renderWithProviders( + , + ); + expect(container.querySelectorAll('section')).toHaveLength(4); + expect(screen.getAllByRole('img')).toHaveLength(1); + for (const story of loveshootPage.stories.slice(1)) { + const section = screen.getByTestId(`story-${story.id}`); + expect(within(section).queryByRole('img')).toBeNull(); + expect( + within(section).getByRole('heading', { level: 2 }), + ).toHaveTextContent(story.title); + } + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('gives hostile story ids valid aria-labelledby targets', async () => { + const stories: StoryBlock[] = [ + { + id: 'Met Spatie', + eyebrow: 'a', + title: 'Een', + paragraphs: [['x']], + }, + { + id: '', + eyebrow: 'b', + title: 'Twee', + paragraphs: [['y']], + }, + ]; + const { container } = await renderWithProviders( + , + ); + for (const section of container.querySelectorAll('section')) { + const target = section.getAttribute('aria-labelledby')!; + expect(target).toMatch(/^[a-z0-9\-_]+$/); + expect(container.querySelector(`#${target}`)).not.toBeNull(); + } + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('renders nothing without stories', async () => { + const { container } = await renderWithProviders( + , + ); + expect(container.querySelector('section')).toBeNull(); + }); +}); diff --git a/web/src/components/shoots/StoryBlocks/StoryBlocks.tsx b/web/src/components/shoots/StoryBlocks/StoryBlocks.tsx new file mode 100644 index 0000000..6578d9e --- /dev/null +++ b/web/src/components/shoots/StoryBlocks/StoryBlocks.tsx @@ -0,0 +1,90 @@ +import { Box, Heading, Stack } from '@chakra-ui/react'; +import Eyebrow from '@/components/Eyebrow/Eyebrow'; +import MediaText from '@/components/MediaText/MediaText'; +import PageSection from '@/components/PageSection/PageSection'; +import Reveal from '@/components/Reveal/Reveal'; +import RichParagraph from '@/components/RichParagraph/RichParagraph'; +import type { FrameColor, StoryBlock } from '@/content/types'; +import { headingId } from '@/lib/headingId'; +import { storyLayout } from '@/lib/storyLayout'; + +type StoryBlocksProps = { + stories: readonly StoryBlock[]; + // Colour of the block behind every photo + frameColor: FrameColor; + // Start of the heading ids, so they cannot clash with other ids + idPrefix: string; +}; + +// The story blocks of a shoot page (FR-ST-03, BR-SP-10..14): one band per +// story, named by its h2. Tone, side, spacing and the photo's shape come +// from storyLayout. A story without a photo is a text-only band in a +// narrow column, with no frame and no empty column. +export default function StoryBlocks({ + stories, + frameColor, + idPrefix, +}: StoryBlocksProps) { + const layouts = storyLayout(stories); + + return ( + <> + {stories.map((story, index) => { + const layout = layouts[index]; + const titleId = `${headingId(idPrefix, story.id)}-title`; + const text = ( + <> + {story.eyebrow} + + {story.title} + + + {story.paragraphs.map((paragraph, number) => ( + // Static content: the order never changes + + ))} + + + ); + + return ( + + {story.image !== undefined && layout.media ? ( + + {text} + + ) : ( + + + {text} + + + )} + + ); + })} + + ); +} diff --git a/web/src/hooks/useDismiss.test.tsx b/web/src/hooks/useDismiss.test.tsx new file mode 100644 index 0000000..c07b870 --- /dev/null +++ b/web/src/hooks/useDismiss.test.tsx @@ -0,0 +1,114 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { useRef } from 'react'; +import { describe, expect, it, vi } from 'vitest'; +import useDismiss, { type DismissReason } from './useDismiss'; + +function Harness({ + active, + onDismiss, +}: { + active: boolean; + onDismiss: (reason: DismissReason) => void; +}) { + const ref = useRef(null); + useDismiss(ref, active, onDismiss); + return ( + <> +
+ +
+ + + ); +} + +describe('useDismiss', () => { + it('reports Escape while active', async () => { + const onDismiss = vi.fn(); + render(); + await userEvent.keyboard('{Escape}'); + expect(onDismiss).toHaveBeenCalledExactlyOnceWith('escape'); + }); + + it('ignores other keys', async () => { + const onDismiss = vi.fn(); + render(); + await userEvent.keyboard('a{Enter}{Tab}'); + expect(onDismiss).not.toHaveBeenCalled(); + }); + + it('reports a pointer down outside, not inside', async () => { + const onDismiss = vi.fn(); + render(); + await userEvent.click(screen.getByRole('button', { name: 'inside' })); + expect(onDismiss).not.toHaveBeenCalled(); + await userEvent.click(screen.getByRole('button', { name: 'outside' })); + expect(onDismiss).toHaveBeenCalledExactlyOnceWith('outside'); + }); + + it('reports nothing while inactive', async () => { + const onDismiss = vi.fn(); + render(); + await userEvent.keyboard('{Escape}'); + await userEvent.click(screen.getByRole('button', { name: 'outside' })); + expect(onDismiss).not.toHaveBeenCalled(); + }); + + it('starts and stops listening when active changes', async () => { + const onDismiss = vi.fn(); + const { rerender } = render( + , + ); + rerender(); + await userEvent.keyboard('{Escape}'); + expect(onDismiss).toHaveBeenCalledTimes(1); + rerender(); + await userEvent.keyboard('{Escape}'); + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('removes its listeners on unmount', async () => { + const onDismiss = vi.fn(); + const { unmount } = render(); + const remove = vi.spyOn(document, 'removeEventListener'); + unmount(); + expect(remove.mock.calls.map(([type]) => type).sort()).toEqual([ + 'keydown', + 'pointerdown', + ]); + await userEvent.keyboard('{Escape}'); + fireEvent.pointerDown(document.body); + expect(onDismiss).not.toHaveBeenCalled(); + }); + + it('calls the latest callback once without re-subscribing', async () => { + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render(); + const add = vi.spyOn(document, 'addEventListener'); + rerender(); + expect(add).not.toHaveBeenCalled(); + await userEvent.keyboard('{Escape}'); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('ignores a pointer down whose target is not a Node', () => { + const onDismiss = vi.fn(); + render(); + fireEvent.pointerDown(window); + expect(onDismiss).not.toHaveBeenCalled(); + }); + + it('ignores a pointer down when the ref is empty', () => { + const onDismiss = vi.fn(); + function Detached() { + useDismiss({ current: null }, true, onDismiss); + return null; + } + render(); + fireEvent.pointerDown(document.body); + expect(onDismiss).not.toHaveBeenCalled(); + }); +}); diff --git a/web/src/hooks/useDismiss.ts b/web/src/hooks/useDismiss.ts new file mode 100644 index 0000000..816895a --- /dev/null +++ b/web/src/hooks/useDismiss.ts @@ -0,0 +1,39 @@ +import { useEffect, useRef, type RefObject } from 'react'; + +export type DismissReason = 'escape' | 'outside'; + +// Reports Escape and a pointer down outside `ref` while `active` is true. +// It only listens: what a dismissal means is up to the caller (FR-ST-10). +// The listeners exist only while active and are removed on deactivation and +// unmount. A missing element or a target that is no Node is ignored. +export default function useDismiss( + ref: RefObject, + active: boolean, + onDismiss: (reason: DismissReason) => void, +) { + // The latest callback, so a new function identity does not re-subscribe + const callback = useRef(onDismiss); + useEffect(() => { + callback.current = onDismiss; + }, [onDismiss]); + + useEffect(() => { + if (!active) return; + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') callback.current('escape'); + }; + const onPointerDown = (event: PointerEvent) => { + const element = ref.current; + if (!element || !(event.target instanceof Node)) return; + if (!element.contains(event.target)) callback.current('outside'); + }; + + document.addEventListener('keydown', onKeyDown); + document.addEventListener('pointerdown', onPointerDown); + return () => { + document.removeEventListener('keydown', onKeyDown); + document.removeEventListener('pointerdown', onPointerDown); + }; + }, [active, ref]); +} diff --git a/web/src/lib/headingId.test.ts b/web/src/lib/headingId.test.ts new file mode 100644 index 0000000..3096f68 --- /dev/null +++ b/web/src/lib/headingId.test.ts @@ -0,0 +1,52 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { shootTypeId } from '@/test/arbitraries'; +import { headingId } from './headingId'; + +describe('headingId', () => { + it.each([ + ['story', 'verwachten', 'story-verwachten'], + ['story', 'Met Spatie', 'story-met-spatie'], + ['story', 'UPPER', 'story-upper'], + ['story', '', 'story---script-'], + ['story', '', 'story-'], + ['story', 'één', 'story---n'], + ['Story', 'a_b-c', 'story-a_b-c'], + ])('maps (%s, %s) to %s', (prefix, id, expected) => { + expect(headingId(prefix, id)).toBe(expected); + }); + + it('keeps the five real shoot ids readable', () => { + for (const id of [ + 'newborn', + 'zwangerschap', + 'gezin', + 'loveshoot', + 'portret', + ]) { + expect(headingId('shoot', id)).toBe(`shoot-${id}`); + } + }); + + it('only produces a-z, 0-9, - and _, and is deterministic (invariant)', () => { + fc.assert( + fc.property( + fc.oneof( + fc.string(), + fc.string({ unit: 'binary' }), + shootTypeId, + ), + fc.oneof( + fc.string(), + fc.string({ unit: 'binary' }), + fc.constantFrom('', ' ', '"', "'", '\u0130'), + ), + (prefix, id) => { + const result = headingId(prefix, id); + expect(result).toMatch(/^[a-z0-9\-_]*$/); + expect(headingId(prefix, id)).toBe(result); + }, + ), + ); + }); +}); diff --git a/web/src/lib/headingId.ts b/web/src/lib/headingId.ts new file mode 100644 index 0000000..1893f65 --- /dev/null +++ b/web/src/lib/headingId.ts @@ -0,0 +1,7 @@ +// An id for a heading that aria-labelledby can always point at: lower-case +// letters, digits, '-' and '_' only. Anything else, such as a space in a +// story id from the content, becomes '-' (BR-SP-72). The caller adds +// '-title' where the id belongs to a heading. +export function headingId(prefix: string, id: string): string { + return `${prefix}-${id}`.toLowerCase().replace(/[^a-z0-9\-_]/g, '-'); +} diff --git a/web/src/lib/isShootSectionPath.test.ts b/web/src/lib/isShootSectionPath.test.ts new file mode 100644 index 0000000..ced7b0c --- /dev/null +++ b/web/src/lib/isShootSectionPath.test.ts @@ -0,0 +1,52 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { isShootSectionPath } from './isShootSectionPath'; + +// Het prefix in willekeurige hoofd- en kleine letters +const prefixInRandomCase = fc + .array(fc.boolean(), { minLength: 20, maxLength: 20 }) + .map((flags) => + [...'/soorten-fotoshoots/'] + .map((ch, i) => (flags[i] ? ch.toUpperCase() : ch)) + .join(''), + ); + +describe('isShootSectionPath', () => { + it.each([ + ['/soorten-fotoshoots/niet-bestaande-shoot', true], + ['/Soorten-Fotoshoots/x', true], + ['/soorten-fotoshoots/', true], + ['/soorten-fotoshoots', false], + ['/soorten-fotoshootsx/abc', false], + ['/bestaat-niet', false], + ['/', false], + ])('%s geeft %s', (path, expected) => { + expect(isShootSectionPath(path)).toBe(expected); + }); + + it('is true voor elk pad met het prefix, in elke schrijfwijze (property)', () => { + fc.assert( + fc.property(prefixInRandomCase, fc.string(), (prefix, rest) => { + expect(isShootSectionPath(prefix + rest)).toBe(true); + }), + ); + }); + + it('is false voor paden zonder het prefix (property)', () => { + fc.assert( + fc.property( + fc + .string() + .filter( + (path) => + !path + .toLowerCase() + .startsWith('/soorten-fotoshoots/'), + ), + (path) => { + expect(isShootSectionPath(path)).toBe(false); + }, + ), + ); + }); +}); diff --git a/web/src/lib/isShootSectionPath.ts b/web/src/lib/isShootSectionPath.ts new file mode 100644 index 0000000..9b59401 --- /dev/null +++ b/web/src/lib/isShootSectionPath.ts @@ -0,0 +1,7 @@ +const SHOOT_SECTION_PREFIX = '/soorten-fotoshoots/'; + +// Staat het pad onder /soorten-fotoshoots/ (FR-ST-14)? Hoofdletterongevoelig, +// net als de router. Het overzicht zelf (zonder slash) hoort er niet bij. +export function isShootSectionPath(pathname: string): boolean { + return pathname.toLowerCase().startsWith(SHOOT_SECTION_PREFIX); +} diff --git a/web/src/lib/mosaicLayout.test.ts b/web/src/lib/mosaicLayout.test.ts new file mode 100644 index 0000000..a580a3a --- /dev/null +++ b/web/src/lib/mosaicLayout.test.ts @@ -0,0 +1,96 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { mosaicCount } from '@/test/arbitraries'; +import { + MOSAIC_MAX_PHOTOS, + mosaicLayout, + type MosaicTile, +} from './mosaicLayout'; + +// The grid cells ("column,row") a tile covers, from its 'start / end' strings +function cells(tile: MosaicTile): string[] { + const [c0, c1] = tile.column.split(' / ').map(Number); + const [r0, r1] = tile.row.split(' / ').map(Number); + const result: string[] = []; + for (let c = c0; c < c1; c++) { + for (let r = r0; r < r1; r++) result.push(`${c},${r}`); + } + return result; +} + +describe('mosaicLayout', () => { + it('gives nothing for 0, a negative or a fractional count', () => { + expect(mosaicLayout(0)).toEqual([]); + expect(mosaicLayout(-1)).toEqual([]); + expect(mosaicLayout(1.5)).toEqual([]); + expect(mosaicLayout(Number.NaN)).toEqual([]); + }); + + it('gives one wide tile for 1', () => { + expect(mosaicLayout(1)).toEqual([ + { column: '1 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, + ]); + }); + + it('gives two equal tiles for 2', () => { + expect(mosaicLayout(2)).toEqual([ + { column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, + { column: '3 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, + ]); + }); + + it('gives a large and two wide tiles for 3', () => { + expect(mosaicLayout(3).map((tile) => tile.phoneRatio)).toEqual([ + '4 / 3', + '3 / 2', + '3 / 2', + ]); + expect(mosaicLayout(3)[2]).toMatchObject({ + column: '3 / 5', + row: '2 / 3', + }); + }); + + it('gives design E for 4, and the same for 5 or more', () => { + expect(mosaicLayout(4)).toEqual([ + { column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, + { column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' }, + { column: '3 / 4', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, + { column: '4 / 5', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, + ]); + expect(mosaicLayout(5)).toEqual(mosaicLayout(4)); + expect(mosaicLayout(12)).toEqual(mosaicLayout(4)); + }); + + it('returns fresh objects, so a caller cannot change the layout', () => { + mosaicLayout(4)[0].column = 'x'; + expect(mosaicLayout(4)[0].column).toBe('1 / 3'); + }); + + it('fills the 4 x 2 grid without overlap and stays well formed (invariant)', () => { + fc.assert( + fc.property(mosaicCount, (count) => { + const tiles = mosaicLayout(count); + expect(mosaicLayout(count)).toEqual(tiles); + if (count <= 0) { + expect(tiles).toEqual([]); + return; + } + expect(tiles).toHaveLength(Math.min(count, MOSAIC_MAX_PHOTOS)); + const covered = tiles.flatMap(cells); + expect(new Set(covered).size).toBe(covered.length); + if (count >= 2) expect(covered).toHaveLength(8); + if (count >= 2) { + // (A single photo, never shown, spans the whole grid) + expect(tiles[0]).toMatchObject({ + column: '1 / 3', + row: '1 / 3', + }); + expect(tiles.filter((tile) => !tile.wide).length % 2).toBe( + 0, + ); + } + }), + ); + }); +}); diff --git a/web/src/lib/mosaicLayout.ts b/web/src/lib/mosaicLayout.ts new file mode 100644 index 0000000..2f2447e --- /dev/null +++ b/web/src/lib/mosaicLayout.ts @@ -0,0 +1,50 @@ +// The photo mosaic of a shoot page: a 4 x 2 grid from `md`, two columns on +// phones (FR-ST-05). Each tile says where it sits; the component only +// draws them. + +// The most photos the mosaic shows; more stay in the content +export const MOSAIC_MAX_PHOTOS = 4; + +export interface MosaicTile { + // CSS grid-column from `md`, e.g. '1 / 3' + column: string; + // CSS grid-row from `md` + row: string; + // Spans both columns below `md` + wide: boolean; + // Aspect ratio of the tile below `md` + phoneRatio: '4 / 3' | '3 / 2' | '1 / 1'; +} + +const large: MosaicTile = { + column: '1 / 3', + row: '1 / 3', + wide: true, + phoneRatio: '4 / 3', +}; + +const layouts: Record<1 | 2 | 3 | 4, readonly MosaicTile[]> = { + // Never shown (the view needs at least two photos), kept so that the + // function is total + 1: [{ column: '1 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }], + 2: [large, { ...large, column: '3 / 5' }], + 3: [ + large, + { column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' }, + { column: '3 / 5', row: '2 / 3', wide: true, phoneRatio: '3 / 2' }, + ], + 4: [ + large, + { column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' }, + { column: '3 / 4', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, + { column: '4 / 5', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, + ], +}; + +// The tiles for `count` photos. Nothing for a count below 1 or one that is +// not a whole number (fail safe); five or more get the layout for four. +export function mosaicLayout(count: number): MosaicTile[] { + if (!Number.isInteger(count) || count < 1) return []; + const key = Math.min(count, MOSAIC_MAX_PHOTOS) as 1 | 2 | 3 | 4; + return layouts[key].map((tile) => ({ ...tile })); +} diff --git a/web/src/lib/navCurrent.test.ts b/web/src/lib/navCurrent.test.ts new file mode 100644 index 0000000..41500e7 --- /dev/null +++ b/web/src/lib/navCurrent.test.ts @@ -0,0 +1,200 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import type { NavItem } from '../navigation'; +import { knownRoutePath, uniqueShootTypes } from '../test/arbitraries'; +import { pathname } from '../test/navArbitraries'; +import { isItemCurrent, isSectionCurrent } from './navCurrent'; +import { shootNavItems } from './shootNavItems'; + +// The comparison rule written out once more: lower case, one trailing slash +const normalise = (path: string) => { + const lower = path.toLowerCase(); + return lower.length > 1 && lower.endsWith('/') ? lower.slice(0, -1) : lower; +}; + +const item = fc.record({ to: knownRoutePath, label: fc.string() }); + +// The overview with a random set of shoot pages as children +const parent = uniqueShootTypes.map((shoots): NavItem => ({ + to: '/soorten-fotoshoots', + label: 'Soorten fotoshoots', + children: shootNavItems(shoots), +})); + +describe('isItemCurrent', () => { + it('is true exactly when the normalised paths are equal (invariant)', () => { + fc.assert( + fc.property(item, pathname, (nav, path) => { + expect(isItemCurrent(nav, path)).toBe( + normalise(nav.to) === normalise(path), + ); + }), + ); + }); + + it('is true for its own path in every spelling (invariant)', () => { + fc.assert( + fc.property(item, (nav) => { + for (const spelling of [ + nav.to, + `${nav.to}/`, + nav.to.toUpperCase(), + `${nav.to.toUpperCase()}/`, + ]) { + expect(isItemCurrent(nav, spelling)).toBe(true); + } + }), + ); + }); + + it('is not changed by letter case or one added trailing slash (idempotency)', () => { + fc.assert( + fc.property(item, pathname, (nav, path) => { + // '' and '/' have no "added slash" twin that means the same + fc.pre(path.length > 0 && path !== '/'); + const result = isItemCurrent(nav, path); + expect(isItemCurrent(nav, path.toUpperCase())).toBe( + isItemCurrent(nav, path.toLowerCase()), + ); + // Adding a slash to a path without one gives the same answer + fc.pre(!path.endsWith('/')); + expect(isItemCurrent(nav, `${path}/`)).toBe(result); + }), + ); + }); + + it('is false for a path that normalises differently (invariant)', () => { + fc.assert( + fc.property(item, pathname, (nav, path) => { + fc.pre(normalise(nav.to) !== normalise(path)); + expect(isItemCurrent(nav, path)).toBe(false); + }), + ); + }); + + it('accepts the item path with a trailing slash and other case', () => { + const nav: NavItem = { to: '/portfolio', label: 'Portfolio' }; + expect(isItemCurrent(nav, '/portfolio')).toBe(true); + expect(isItemCurrent(nav, '/portfolio/')).toBe(true); + expect(isItemCurrent(nav, '/Portfolio')).toBe(true); + expect(isItemCurrent(nav, '/')).toBe(false); + }); + + it('keeps the home page apart from every other path', () => { + const home: NavItem = { to: '/', label: 'Home' }; + expect(isItemCurrent(home, '/')).toBe(true); + expect(isItemCurrent(home, '')).toBe(false); + expect(isItemCurrent(home, '/portfolio')).toBe(false); + }); +}); + +describe('isSectionCurrent', () => { + it('is implied by isItemCurrent (invariant)', () => { + fc.assert( + fc.property(parent, pathname, (nav, path) => { + fc.pre(isItemCurrent(nav, path)); + expect(isSectionCurrent(nav, path)).toBe(true); + }), + ); + }); + + it('is implied by any child being current (invariant)', () => { + fc.assert( + fc.property(parent, fc.nat(), (nav, index) => { + const children = nav.children ?? []; + fc.pre(children.length > 0); + const child = children[index % children.length]; + expect(isSectionCurrent(nav, child.to)).toBe(true); + expect(isSectionCurrent(nav, `${child.to}/`)).toBe(true); + expect(isSectionCurrent(nav, child.to.toUpperCase())).toBe( + true, + ); + }), + ); + }); + + it('is true only for the item or a child (invariant)', () => { + fc.assert( + fc.property(parent, pathname, (nav, path) => { + const expected = + isItemCurrent(nav, path) || + (nav.children ?? []).some((child) => + isItemCurrent(child, path), + ); + expect(isSectionCurrent(nav, path)).toBe(expected); + }), + ); + }); + + it('is false for unrelated paths and prefix look-alikes (invariant)', () => { + fc.assert( + fc.property( + parent, + fc.constantFrom( + '/', + '/portfolio', + '/contact', + '/soorten-fotoshoots-extra', + '/soorten-fotoshootsX', + '/soorten-fotoshoots/newborn/extra', + '/soorten-fotoshoots/onbekend', + ), + (nav, path) => { + expect(isSectionCurrent(nav, path)).toBe(false); + }, + ), + ); + }); + + it('is false on the home page for the overview', () => { + const nav: NavItem = { + to: '/soorten-fotoshoots', + label: 'Soorten fotoshoots', + children: shootNavItems([]), + }; + expect(isSectionCurrent(nav, '/')).toBe(false); + }); + + it('marks the parent as section and the child as item on a shoot page', () => { + const child: NavItem = { + to: '/soorten-fotoshoots/newborn', + label: 'Newborn', + }; + const nav: NavItem = { + to: '/soorten-fotoshoots', + label: 'Soorten fotoshoots', + children: [child], + }; + expect(isSectionCurrent(nav, '/soorten-fotoshoots/newborn/')).toBe( + true, + ); + expect(isItemCurrent(child, '/soorten-fotoshoots/newborn/')).toBe(true); + expect(isItemCurrent(nav, '/soorten-fotoshoots/newborn/')).toBe(false); + }); + + it('works for an item without children', () => { + const nav: NavItem = { to: '/contact', label: 'Contact' }; + expect(isSectionCurrent(nav, '/contact')).toBe(true); + expect(isSectionCurrent(nav, '/portfolio')).toBe(false); + }); +}); + +describe('hostile pathnames', () => { + it('always gives a boolean and does not throw (invariant)', () => { + fc.assert( + fc.property(parent, fc.string(), (nav, path) => { + expect(typeof isItemCurrent(nav, path)).toBe('boolean'); + expect(typeof isSectionCurrent(nav, path)).toBe('boolean'); + }), + ); + }); + + it.each(['', '//', ' ', '%2F', '/%2F', 'a'.repeat(100_000)])( + 'handles %j without throwing', + (path) => { + const nav: NavItem = { to: '/', label: 'Home' }; + expect(() => isItemCurrent(nav, path)).not.toThrow(); + expect(() => isSectionCurrent(nav, path)).not.toThrow(); + }, + ); +}); diff --git a/web/src/lib/navCurrent.ts b/web/src/lib/navCurrent.ts new file mode 100644 index 0000000..bc42caf --- /dev/null +++ b/web/src/lib/navCurrent.ts @@ -0,0 +1,24 @@ +import type { NavItem } from '../navigation.ts'; + +// Lower case and without one trailing slash (not for "/"), the way the +// router matches a path (BR-NAV-04) +function normalise(path: string): string { + const lower = path.toLowerCase(); + return lower.length > 1 && lower.endsWith('/') ? lower.slice(0, -1) : lower; +} + +// Whether the item is the page at `pathname`. Pure string comparison: never +// throws and never renders the pathname (SECURITY-05, SECURITY-15). +export function isItemCurrent(item: NavItem, pathname: string): boolean { + return normalise(item.to) === normalise(pathname); +} + +// Whether the item or one of its children is the page at `pathname`; marks +// the parent while a page below it is open (D4) +export function isSectionCurrent(item: NavItem, pathname: string): boolean { + return ( + isItemCurrent(item, pathname) || + (item.children?.some((child) => isItemCurrent(child, pathname)) ?? + false) + ); +} diff --git a/web/src/lib/navMenuState.test.ts b/web/src/lib/navMenuState.test.ts new file mode 100644 index 0000000..64abc78 --- /dev/null +++ b/web/src/lib/navMenuState.test.ts @@ -0,0 +1,398 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { + navMenuEvent, + navMenuEvents, + navMenuState, + navMenuStateOn, +} from '../test/navArbitraries'; +import { + initialNavMenuState, + navMenuReducer, + type NavMenuEvent, + type NavMenuState, +} from './navMenuState'; + +const reduce = (events: readonly NavMenuEvent[], start = initialNavMenuState) => + events.reduce(navMenuReducer, start); + +const closed: NavMenuState = { ...initialNavMenuState }; +const mobile: NavMenuState = { ...closed, isDesktop: false }; +const desktop: NavMenuState = { ...closed, isDesktop: true }; +const mobileOpen: NavMenuState = { ...mobile, menuOpen: true }; +const mobileGroup: NavMenuState = { ...mobileOpen, groupOpen: true }; +const desktopOpen: NavMenuState = { ...desktop, submenuOpen: true }; + +// The invariants I1-I4 of the domain model +function expectInvariants(state: NavMenuState) { + if (state.submenuOpen) expect(state.isDesktop).toBe(true); + if (state.menuOpen) expect(state.isDesktop).toBe(false); + if (state.groupOpen) expect(state.menuOpen).toBe(true); + if (state.focusRequest === 'menuToggle') { + expect(state.isDesktop).toBe(false); + } + if (state.focusRequest === 'submenuToggle') { + expect(state.isDesktop).toBe(true); + } +} + +// An independent, deliberately plain model of the transition table, written +// per field instead of per event as the reducer does +function model(state: NavMenuState, event: NavMenuEvent) { + const next = { ...state }; + const everythingClosed = () => { + next.menuOpen = false; + next.groupOpen = false; + next.submenuOpen = false; + }; + if (event.type === 'viewport') { + next.isDesktop = event.isDesktop; + if (event.isDesktop) { + next.menuOpen = false; + next.groupOpen = false; + } else { + next.submenuOpen = false; + } + if (event.isDesktop && next.focusRequest === 'menuToggle') { + next.focusRequest = null; + } + if (!event.isDesktop && next.focusRequest === 'submenuToggle') { + next.focusRequest = null; + } + } else if (event.type === 'toggleMenu' && !state.isDesktop) { + next.menuOpen = !state.menuOpen; + next.groupOpen = next.menuOpen ? event.inSection : false; + } else if (event.type === 'toggleGroup' && state.menuOpen) { + next.groupOpen = !state.groupOpen; + } else if (event.type === 'toggleSubmenu' && state.isDesktop) { + next.submenuOpen = !state.submenuOpen; + } else if (event.type === 'escape' && state.menuOpen) { + next.menuOpen = false; + next.groupOpen = false; + next.focusRequest = event.focusInside ? 'menuToggle' : null; + } else if (event.type === 'escape' && state.submenuOpen) { + next.submenuOpen = false; + next.focusRequest = event.focusInside ? 'submenuToggle' : null; + } else if ( + (event.type === 'outside' || event.type === 'focusLeave') && + state.submenuOpen + ) { + next.submenuOpen = false; + } else if (event.type === 'linkChosen' || event.type === 'routeChanged') { + everythingClosed(); + next.focusRequest = null; + } else if (event.type === 'focusHandled') { + next.focusRequest = null; + } + return next; +} + +describe('navMenuReducer (stateful)', () => { + it('keeps I1-I4 and follows the model after every event (stateful)', () => { + fc.assert( + fc.property(navMenuEvents, (events) => { + let state = initialNavMenuState; + for (const event of events) { + const expected = model(state, event); + state = navMenuReducer(state, event); + expect(state).toEqual(expected); + expectInvariants(state); + } + }), + ); + }); + + it('starts all closed and keeps the invariants for any reached state', () => { + expectInvariants(initialNavMenuState); + fc.assert( + fc.property(navMenuState, (state) => { + expectInvariants(state); + }), + ); + }); + + it('returns the same object when an event does not apply (invariant)', () => { + fc.assert( + fc.property(navMenuState, navMenuEvent, (state, event) => { + const next = navMenuReducer(state, event); + if (JSON.stringify(next) === JSON.stringify(state)) { + expect(next).toBe(state); + } + }), + ); + }); +}); + +describe('navMenuReducer (idempotency)', () => { + it('ends all closed after routeChanged or linkChosen, twice as once (idempotency)', () => { + fc.assert( + fc.property( + navMenuState, + fc.constantFrom('routeChanged', 'linkChosen'), + (state, type) => { + const once = navMenuReducer(state, { type }); + expect(once.menuOpen).toBe(false); + expect(once.groupOpen).toBe(false); + expect(once.submenuOpen).toBe(false); + expect(once.focusRequest).toBeNull(); + expect(once.isDesktop).toBe(state.isDesktop); + expect(navMenuReducer(once, { type })).toEqual(once); + }, + ), + ); + }); + + it('closes the same on escape twice as once, apart from the focus request (idempotency)', () => { + fc.assert( + fc.property(navMenuState, fc.boolean(), (state, focusInside) => { + const event = { type: 'escape', focusInside } as const; + const once = navMenuReducer(state, event); + const twice = navMenuReducer(once, event); + expect({ ...twice, focusRequest: null }).toEqual({ + ...once, + focusRequest: null, + }); + }), + ); + }); + + it('closes the submenu on outside or focusLeave without touching the rest (invariant)', () => { + fc.assert( + fc.property( + navMenuState, + fc.constantFrom('outside', 'focusLeave'), + (state, type) => { + const once = navMenuReducer(state, { type }); + expect(once.menuOpen).toBe(state.menuOpen); + expect(once.groupOpen).toBe(state.groupOpen); + expect(once.focusRequest).toBe(state.focusRequest); + expect(once.submenuOpen).toBe(false); + expect(navMenuReducer(once, { type })).toBe(once); + }, + ), + ); + }); +}); + +describe('navMenuReducer (invariant)', () => { + it('gives back the original state after two submenu toggles on desktop (invariant)', () => { + fc.assert( + fc.property(navMenuStateOn(true), (state) => { + const twice = reduce( + [{ type: 'toggleSubmenu' }, { type: 'toggleSubmenu' }], + state, + ); + expect(twice).toEqual(state); + }), + ); + }); + + it('leaves no mobile state open after viewport(true) (invariant)', () => { + fc.assert( + fc.property(navMenuState, (state) => { + const next = navMenuReducer(state, { + type: 'viewport', + isDesktop: true, + }); + expect(next.isDesktop).toBe(true); + expect(next.menuOpen).toBe(false); + expect(next.groupOpen).toBe(false); + }), + ); + }); + + it('leaves no submenu open after viewport(false) (invariant)', () => { + fc.assert( + fc.property(navMenuState, (state) => { + const next = navMenuReducer(state, { + type: 'viewport', + isDesktop: false, + }); + expect(next.isDesktop).toBe(false); + expect(next.submenuOpen).toBe(false); + }), + ); + }); + + it('opens the menu with the group set to inSection and closes both (invariant)', () => { + fc.assert( + fc.property(fc.boolean(), (inSection) => { + const open = navMenuReducer(mobile, { + type: 'toggleMenu', + inSection, + }); + expect(open.menuOpen).toBe(true); + expect(open.groupOpen).toBe(inSection); + const shut = navMenuReducer(open, { + type: 'toggleMenu', + inSection, + }); + expect(shut.menuOpen).toBe(false); + expect(shut.groupOpen).toBe(false); + }), + ); + }); +}); + +describe('navMenuReducer (examples)', () => { + it('viewport sets the width and closes what no longer exists', () => { + expect( + navMenuReducer(initialNavMenuState, { + type: 'viewport', + isDesktop: true, + }), + ).toEqual(desktop); + expect( + navMenuReducer(mobileGroup, { type: 'viewport', isDesktop: true }), + ).toEqual(desktop); + expect( + navMenuReducer(desktopOpen, { type: 'viewport', isDesktop: false }), + ).toEqual(mobile); + }); + + it('viewport drops a focus request that no longer fits', () => { + expect( + navMenuReducer( + { ...desktop, focusRequest: 'submenuToggle' }, + { type: 'viewport', isDesktop: false }, + ).focusRequest, + ).toBeNull(); + expect( + navMenuReducer( + { ...mobile, focusRequest: 'menuToggle' }, + { type: 'viewport', isDesktop: true }, + ).focusRequest, + ).toBeNull(); + expect( + navMenuReducer( + { ...mobile, focusRequest: 'menuToggle' }, + { type: 'viewport', isDesktop: false }, + ).focusRequest, + ).toBe('menuToggle'); + }); + + it('viewport to the same width changes nothing and returns the same object', () => { + expect( + navMenuReducer(mobile, { type: 'viewport', isDesktop: false }), + ).toBe(mobile); + expect( + navMenuReducer(desktopOpen, { type: 'viewport', isDesktop: true }), + ).toBe(desktopOpen); + }); + + it('toggleMenu opens with the group expanded in the section, collapsed outside it', () => { + expect( + navMenuReducer(mobile, { type: 'toggleMenu', inSection: true }), + ).toEqual(mobileGroup); + expect( + navMenuReducer(mobile, { type: 'toggleMenu', inSection: false }), + ).toEqual(mobileOpen); + expect( + navMenuReducer(mobileGroup, { + type: 'toggleMenu', + inSection: true, + }), + ).toEqual(mobile); + }); + + it('toggleMenu on desktop is ignored', () => { + expect( + navMenuReducer(desktop, { type: 'toggleMenu', inSection: true }), + ).toBe(desktop); + }); + + it('toggleGroup flips the group while the menu is open', () => { + expect(navMenuReducer(mobileOpen, { type: 'toggleGroup' })).toEqual( + mobileGroup, + ); + expect(navMenuReducer(mobileGroup, { type: 'toggleGroup' })).toEqual( + mobileOpen, + ); + }); + + it('toggleGroup while the menu is closed is ignored', () => { + expect(navMenuReducer(mobile, { type: 'toggleGroup' })).toBe(mobile); + }); + + it('toggleSubmenu flips the submenu on desktop', () => { + expect(navMenuReducer(desktop, { type: 'toggleSubmenu' })).toEqual( + desktopOpen, + ); + expect(navMenuReducer(desktopOpen, { type: 'toggleSubmenu' })).toEqual( + desktop, + ); + }); + + it('toggleSubmenu on mobile is ignored', () => { + expect(navMenuReducer(mobile, { type: 'toggleSubmenu' })).toBe(mobile); + }); + + it('escape closes the mobile menu and asks for focus on the hamburger when focus is inside', () => { + expect( + navMenuReducer(mobileGroup, { type: 'escape', focusInside: true }), + ).toEqual({ ...mobile, focusRequest: 'menuToggle' }); + expect( + navMenuReducer(mobileGroup, { type: 'escape', focusInside: false }), + ).toEqual(mobile); + }); + + it('escape closes the submenu and asks for focus on its toggle when focus is inside', () => { + expect( + navMenuReducer(desktopOpen, { type: 'escape', focusInside: true }), + ).toEqual({ ...desktop, focusRequest: 'submenuToggle' }); + expect( + navMenuReducer(desktopOpen, { type: 'escape', focusInside: false }), + ).toEqual(desktop); + }); + + it('escape with nothing open is ignored', () => { + expect( + navMenuReducer(desktop, { type: 'escape', focusInside: true }), + ).toBe(desktop); + expect( + navMenuReducer(mobile, { type: 'escape', focusInside: true }), + ).toBe(mobile); + }); + + it('outside and focusLeave close the submenu without a focus request', () => { + expect(navMenuReducer(desktopOpen, { type: 'outside' })).toEqual( + desktop, + ); + expect(navMenuReducer(desktopOpen, { type: 'focusLeave' })).toEqual( + desktop, + ); + }); + + it('outside and focusLeave with the submenu closed are ignored', () => { + expect(navMenuReducer(desktop, { type: 'outside' })).toBe(desktop); + expect(navMenuReducer(desktop, { type: 'focusLeave' })).toBe(desktop); + expect(navMenuReducer(mobileGroup, { type: 'outside' })).toBe( + mobileGroup, + ); + }); + + it('linkChosen and routeChanged close everything', () => { + for (const type of ['linkChosen', 'routeChanged'] as const) { + expect(navMenuReducer(mobileGroup, { type })).toEqual(mobile); + expect(navMenuReducer(desktopOpen, { type })).toEqual(desktop); + expect(navMenuReducer(desktop, { type })).toBe(desktop); + } + }); + + it('focusHandled clears the request, or is ignored when there is none', () => { + const asked: NavMenuState = { + ...desktop, + focusRequest: 'submenuToggle', + }; + expect(navMenuReducer(asked, { type: 'focusHandled' })).toEqual( + desktop, + ); + expect(navMenuReducer(desktop, { type: 'focusHandled' })).toBe(desktop); + }); + + it('ignores an unknown event instead of opening anything', () => { + const unknown = { type: 'explode' } as unknown as NavMenuEvent; + expect(navMenuReducer(desktop, unknown)).toBe(desktop); + expect(navMenuReducer(mobileOpen, unknown)).toBe(mobileOpen); + }); +}); diff --git a/web/src/lib/navMenuState.ts b/web/src/lib/navMenuState.ts new file mode 100644 index 0000000..f7c5fc0 --- /dev/null +++ b/web/src/lib/navMenuState.ts @@ -0,0 +1,140 @@ +// The open/closed state of the navigation menus (FR-ST-10): the desktop +// submenu below "Soorten fotoshoots" and, below lg, the full-screen menu +// with its expandable group. One reducer, so the hamburger, the submenu, +// the group and the route listener cannot disagree. + +// Where the focus must go after a state change; cleared by `focusHandled` +export type FocusRequest = 'menuToggle' | 'submenuToggle' | null; + +// Invariants (checked by the property tests): +// I1 submenuOpen implies isDesktop +// I2 menuOpen implies !isDesktop +// I3 groupOpen implies menuOpen +// I4 focusRequest 'menuToggle' implies !isDesktop, 'submenuToggle' implies +// isDesktop +export interface NavMenuState { + // Viewport is at or above lg + isDesktop: boolean; + // The full-screen mobile menu + menuOpen: boolean; + // The "Soorten fotoshoots" sub-list inside the mobile menu + groupOpen: boolean; + // The desktop dropdown panel + submenuOpen: boolean; + focusRequest: FocusRequest; +} + +export type NavMenuEvent = + | { type: 'viewport'; isDesktop: boolean } + | { type: 'toggleMenu'; inSection: boolean } + | { type: 'toggleGroup' } + | { type: 'toggleSubmenu' } + | { type: 'escape'; focusInside: boolean } + | { type: 'outside' } + | { type: 'focusLeave' } + | { type: 'linkChosen' } + | { type: 'routeChanged' } + | { type: 'focusHandled' }; + +// Everything closed; the width is unknown until the first `viewport` event +export const initialNavMenuState: NavMenuState = { + isDesktop: false, + menuOpen: false, + groupOpen: false, + submenuOpen: false, + focusRequest: null, +}; + +// A focus request that cannot be met at this width is dropped (I4) +function fittingRequest(request: FocusRequest, isDesktop: boolean) { + if (request === 'menuToggle' && isDesktop) return null; + if (request === 'submenuToggle' && !isDesktop) return null; + return request; +} + +// The transition table of the navigation menus. An event that does not apply +// returns the same state object, so useReducer skips the re-render. Nothing +// is ever opened by a fallback (SECURITY-15). +export function navMenuReducer( + state: NavMenuState, + event: NavMenuEvent, +): NavMenuState { + switch (event.type) { + case 'viewport': { + const { isDesktop } = event; + const next: NavMenuState = { + isDesktop, + menuOpen: isDesktop ? false : state.menuOpen, + groupOpen: isDesktop ? false : state.groupOpen, + submenuOpen: isDesktop ? state.submenuOpen : false, + focusRequest: fittingRequest(state.focusRequest, isDesktop), + }; + return sameState(state, next) ? state : next; + } + case 'toggleMenu': + if (state.isDesktop) return state; + return state.menuOpen + ? { ...state, menuOpen: false, groupOpen: false } + : { ...state, menuOpen: true, groupOpen: event.inSection }; + case 'toggleGroup': + if (!state.menuOpen) return state; + return { ...state, groupOpen: !state.groupOpen }; + case 'toggleSubmenu': + if (!state.isDesktop) return state; + return { ...state, submenuOpen: !state.submenuOpen }; + case 'escape': + if (state.menuOpen) { + return { + ...state, + menuOpen: false, + groupOpen: false, + focusRequest: event.focusInside ? 'menuToggle' : null, + }; + } + if (state.submenuOpen) { + return { + ...state, + submenuOpen: false, + focusRequest: event.focusInside ? 'submenuToggle' : null, + }; + } + return state; + case 'outside': + case 'focusLeave': + if (!state.submenuOpen) return state; + return { ...state, submenuOpen: false }; + case 'linkChosen': + case 'routeChanged': { + const closed: NavMenuState = { + ...state, + menuOpen: false, + groupOpen: false, + submenuOpen: false, + focusRequest: null, + }; + return sameState(state, closed) ? state : closed; + } + case 'focusHandled': + if (state.focusRequest === null) return state; + return { ...state, focusRequest: null }; + default: + // A new event type without a case is a type error here (never); + // at run time an unknown event changes nothing + return ignore(state, event); + } +} + +function sameState(a: NavMenuState, b: NavMenuState) { + return ( + a.isDesktop === b.isDesktop && + a.menuOpen === b.menuOpen && + a.groupOpen === b.groupOpen && + a.submenuOpen === b.submenuOpen && + a.focusRequest === b.focusRequest + ); +} + +function ignore(state: NavMenuState, event: never): NavMenuState { + void event; + return state; +} diff --git a/web/src/lib/readMoreLabel.test.ts b/web/src/lib/readMoreLabel.test.ts new file mode 100644 index 0000000..1ac38f2 --- /dev/null +++ b/web/src/lib/readMoreLabel.test.ts @@ -0,0 +1,38 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import shootTypes from '@/content/shootTypes'; +import { uniqueShootTypes } from '@/test/arbitraries'; +import { readMoreLabel } from './readMoreLabel'; + +describe('readMoreLabel', () => { + it('names each of the five real shoots', () => { + expect(shootTypes.map(readMoreLabel)).toEqual([ + 'Lees meer over de newbornshoot', + 'Lees meer over de zwangerschapsshoot', + 'Lees meer over de gezinsshoot', + 'Lees meer over de loveshoot', + 'Lees meer over de portretshoot', + ]); + expect(new Set(shootTypes.map(readMoreLabel)).size).toBe(5); + }); + + it('starts with the fixed words and is unique for unique shoot labels (invariant)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + const unique = shoots.filter( + (shoot, index) => + shoots.findIndex( + (other) => + other.shootLabel.toLowerCase() === + shoot.shootLabel.toLowerCase(), + ) === index, + ); + const labels = unique.map(readMoreLabel); + for (const label of labels) { + expect(label.startsWith('Lees meer over de ')).toBe(true); + } + expect(new Set(labels).size).toBe(labels.length); + }), + ); + }); +}); diff --git a/web/src/lib/readMoreLabel.ts b/web/src/lib/readMoreLabel.ts new file mode 100644 index 0000000..6202f49 --- /dev/null +++ b/web/src/lib/readMoreLabel.ts @@ -0,0 +1,7 @@ +import type { ShootType } from '../content/types.ts'; + +// The text of the link from the overview to a shoot page (FR-ST-09). It +// differs per shoot, so no aria-label is needed to tell the links apart. +export function readMoreLabel(shoot: ShootType): string { + return `Lees meer over de ${shoot.shootLabel.toLowerCase()}`; +} diff --git a/web/src/lib/shootNavItems.test.ts b/web/src/lib/shootNavItems.test.ts new file mode 100644 index 0000000..c47da53 --- /dev/null +++ b/web/src/lib/shootNavItems.test.ts @@ -0,0 +1,75 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import shootTypes from '../content/shootTypes'; +import { uniqueShootTypes } from '../test/arbitraries'; +import { shootNavItems } from './shootNavItems'; +import { SHOOT_TYPES_PATH, shootIdFromPath, shootPagePath } from './shootPages'; + +describe('shootNavItems', () => { + it('gives one item per shoot (invariant)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + expect(shootNavItems(shoots)).toHaveLength(shoots.length); + }), + ); + }); + + it('keeps the order and uses the name as label (invariant)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + const items = shootNavItems(shoots); + expect(items.map((item) => item.label)).toEqual( + shoots.map((shoot) => shoot.name), + ); + }), + ); + }); + + it('links to the page of the same shoot (round trip)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + const items = shootNavItems(shoots); + items.forEach((item, index) => { + expect(shootIdFromPath(item.to)).toBe(shoots[index].id); + }); + }), + ); + }); + + it('links to a page below the overview (invariant)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + shootNavItems(shoots).forEach((item, index) => { + expect(item.to).toBe(shootPagePath(shoots[index].id)); + expect(item.to.startsWith(`${SHOOT_TYPES_PATH}/`)).toBe( + true, + ); + }); + }), + ); + }); + + it('has no other fields than to and label (invariant)', () => { + fc.assert( + fc.property(uniqueShootTypes, (shoots) => { + for (const item of shootNavItems(shoots)) { + expect(Object.keys(item).sort()).toEqual(['label', 'to']); + } + }), + ); + }); + + it('gives the five names of the real shoot types in order', () => { + expect(shootNavItems(shootTypes).map((item) => item.label)).toEqual([ + 'Newborn', + 'Zwangerschap', + 'Gezin', + 'Loveshoot', + 'Portretten', + ]); + }); + + it('gives an empty list for no shoots', () => { + expect(shootNavItems([])).toEqual([]); + }); +}); diff --git a/web/src/lib/shootNavItems.ts b/web/src/lib/shootNavItems.ts new file mode 100644 index 0000000..4dade32 --- /dev/null +++ b/web/src/lib/shootNavItems.ts @@ -0,0 +1,12 @@ +import type { ShootType } from '../content/types.ts'; +import type { NavItem } from '../navigation.ts'; +import { shootPagePath } from './shootPages.ts'; + +// The submenu items of the shoot types, one per shoot in the given order: +// the label is the shoot name, the target its page (FR-ST-10, BR-NAV-10) +export function shootNavItems(shoots: readonly ShootType[]): NavItem[] { + return shoots.map((shoot) => ({ + to: shootPagePath(shoot.id), + label: shoot.name, + })); +} diff --git a/web/src/lib/shootPageBands.test.ts b/web/src/lib/shootPageBands.test.ts new file mode 100644 index 0000000..ac7e53f --- /dev/null +++ b/web/src/lib/shootPageBands.test.ts @@ -0,0 +1,95 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import shootPageShared from '@/content/shootPageShared'; +import newbornPage from '@/content/shootPages/newborn'; +import loveshootPage from '@/content/shootPages/loveshoot'; +import packages from '@/content/packages'; +import shootTypes from '@/content/shootTypes'; +import siteContent from '@/content/siteContent'; +import { shootPageViewArb } from '@/test/arbitraries'; +import { shootPageBands } from './shootPageBands'; +import { shootPageView } from './shootPageView'; +import { storyLayout } from './storyLayout'; + +const sources = { + shootTypes, + packages, + shared: shootPageShared, + site: siteContent, + portfolioShoots: [], +}; + +describe('shootPageBands', () => { + it('gives the newborn page nine bands', () => { + const view = shootPageView('newborn', newbornPage, sources)!; + const bands = shootPageBands(view); + expect(bands).toHaveLength(9); + expect(bands.map((band) => band.id)).toEqual([ + ...view.stories.map((story) => `story-${story.id}`), + 'process', + 'photos', + 'faq', + 'offer', + 'closing', + ]); + expect(bands.map((band) => band.position)).toEqual([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, + ]); + expect(bands[0].tone).toBe('paper'); + expect(bands[1].tone).toBe('alt'); + }); + + it('leaves out the photos for loveshoot', () => { + const view = shootPageView('loveshoot', loveshootPage, sources)!; + const bands = shootPageBands(view); + expect(bands).toHaveLength(8); + expect(bands.map((band) => band.id)).not.toContain('photos'); + }); + + it('leaves out the FAQ of a view without questions', () => { + const view = shootPageView( + 'newborn', + { ...newbornPage, faq: { ...newbornPage.faq, items: [] } }, + sources, + )!; + const ids = shootPageBands(view).map((band) => band.id); + expect(ids).not.toContain('faq'); + expect(ids).toContain('photos'); + }); + + it('keeps the order, the alternation and the story tones for any view (invariant)', () => { + fc.assert( + fc.property(shootPageViewArb, (view) => { + const bands = shootPageBands(view); + expect(bands).toHaveLength( + view.stories.length + + 1 + + (view.photos ? 1 : 0) + + (view.faq ? 1 : 0) + + 2, + ); + bands.forEach((band, index) => { + expect(band.position).toBe(index); + expect(band.tone).toBe(index % 2 === 0 ? 'paper' : 'alt'); + }); + const tail = bands.slice(view.stories.length).map((b) => b.id); + expect(tail).toEqual([ + 'process', + ...(view.photos ? ['photos'] : []), + ...(view.faq ? ['faq'] : []), + 'offer', + 'closing', + ]); + expect( + bands.slice(0, view.stories.length).map((b) => b.id), + ).toEqual(view.stories.map((story) => `story-${story.id}`)); + const layout = storyLayout(view.stories); + layout.forEach((item, index) => { + expect(bands[index].tone).toBe(item.tone); + }); + // Story ids are unique in the generated content + expect(new Set(bands.map((b) => b.id)).size).toBe(bands.length); + }), + ); + }); +}); diff --git a/web/src/lib/shootPageBands.ts b/web/src/lib/shootPageBands.ts new file mode 100644 index 0000000..8452ee4 --- /dev/null +++ b/web/src/lib/shootPageBands.ts @@ -0,0 +1,29 @@ +import type { ShootPageView } from './shootPageView.ts'; + +export interface SectionBand { + id: `story-${string}` | 'process' | 'photos' | 'faq' | 'offer' | 'closing'; + // The band colour: paper at even positions, alt at odd ones + tone: 'paper' | 'alt'; + // 0 for the first story; the intro above it is not a band + position: number; +} + +// The bands of a shoot page in page order (BR-SP-70): the stories, the +// timeline, the photos and the FAQ when the view has them, the offer and +// the closing block. Tones alternate, so two bands never touch in the same +// colour; the intro above is always paper. +export function shootPageBands(view: ShootPageView): SectionBand[] { + const ids: SectionBand['id'][] = [ + ...view.stories.map((story) => `story-${story.id}` as const), + 'process', + ...(view.photos ? (['photos'] as const) : []), + ...(view.faq ? (['faq'] as const) : []), + 'offer', + 'closing', + ]; + return ids.map((id, position) => ({ + id, + tone: position % 2 === 0 ? 'paper' : 'alt', + position, + })); +} diff --git a/web/src/lib/storyLayout.test.ts b/web/src/lib/storyLayout.test.ts new file mode 100644 index 0000000..6141afb --- /dev/null +++ b/web/src/lib/storyLayout.test.ts @@ -0,0 +1,119 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import newbornPage from '@/content/shootPages/newborn'; +import loveshootPage from '@/content/shootPages/loveshoot'; +import type { StoryBlock } from '@/content/types'; +import { imageWithOrientation, storyBlock } from '@/test/arbitraries'; +import { LANDSCAPE_RATIO, storyLayout } from './storyLayout'; + +const story = (width?: number, height?: number): StoryBlock => ({ + id: 's', + eyebrow: 'e', + title: 't', + paragraphs: [['p']], + ...(width === undefined || height === undefined + ? {} + : { image: { src: '/a.jpg', alt: 'a', width, height } }), +}); + +describe('storyLayout', () => { + it('lays out the four real newborn stories', () => { + const layout = storyLayout(newbornPage.stories); + expect(layout.map((item) => item.media)).toEqual([ + { aspectRatio: '4 / 5', mediaSize: 'medium' }, + { aspectRatio: '3 / 2', mediaSize: 'half' }, + { aspectRatio: '4 / 5', mediaSize: 'medium' }, + { aspectRatio: '4 / 5', mediaSize: 'medium' }, + ]); + expect(layout.map((item) => item.tone)).toEqual([ + 'paper', + 'alt', + 'paper', + 'alt', + ]); + expect(layout.map((item) => item.reverse)).toEqual([ + false, + true, + false, + true, + ]); + expect(layout.map((item) => item.priority)).toEqual([ + true, + false, + false, + false, + ]); + expect(layout[0].spacing).toBe('flushTop'); + expect(layout[1].spacing).toBe('default'); + }); + + it('gives text-only stories no media and no priority', () => { + const layout = storyLayout(loveshootPage.stories); + expect(layout[0].media).toBeDefined(); + for (const item of layout.slice(1)) { + expect(item).not.toHaveProperty('media'); + expect(item.priority).toBe(false); + } + expect(storyLayout([story()])[0].priority).toBe(false); + }); + + it('switches to landscape at exactly 1.2', () => { + expect(LANDSCAPE_RATIO).toBe(1.2); + expect(storyLayout([story(120, 100)])[0].media?.aspectRatio).toBe( + '3 / 2', + ); + expect(storyLayout([story(119, 100)])[0].media?.aspectRatio).toBe( + '4 / 5', + ); + }); + + it('gives nothing for no stories', () => { + expect(storyLayout([])).toEqual([]); + }); + + it('alternates, and decides ratio and width by the photo (invariant)', () => { + fc.assert( + fc.property( + fc.array( + fc.tuple( + storyBlock, + fc.option(imageWithOrientation, { nil: undefined }), + ), + { maxLength: 8 }, + ), + (pairs) => { + const stories = pairs.map(([block, image]) => ({ + ...block, + image, + })); + const layout = storyLayout(stories); + expect(layout).toHaveLength(stories.length); + layout.forEach((item, index) => { + const { image } = stories[index]; + expect(item.tone).toBe( + index % 2 === 0 ? 'paper' : 'alt', + ); + expect(item.reverse).toBe(index % 2 === 1); + expect(item.priority).toBe( + index === 0 && image !== undefined, + ); + if (image === undefined) { + expect(item.media).toBeUndefined(); + return; + } + const landscape = + image.width >= LANDSCAPE_RATIO * image.height; + expect(item.media).toEqual( + landscape + ? { aspectRatio: '3 / 2', mediaSize: 'half' } + : { + aspectRatio: '4 / 5', + mediaSize: 'medium', + }, + ); + }); + }, + ), + ); + }); +}); diff --git a/web/src/lib/storyLayout.ts b/web/src/lib/storyLayout.ts new file mode 100644 index 0000000..1546828 --- /dev/null +++ b/web/src/lib/storyLayout.ts @@ -0,0 +1,44 @@ +import type { StoryBlock } from '../content/types.ts'; + +// A photo is landscape when it is at least this much wider than it is high +export const LANDSCAPE_RATIO = 1.2; + +export interface StoryLayout { + // Band colour; the same rule as shootPageBands gives the story bands + tone: 'paper' | 'alt'; + // flushTop: no space above the first block, below the page head + spacing: 'flushTop' | 'default'; + // Photo in the right-hand column from `lg` + reverse: boolean; + // Only the first story's photo may load with priority + priority: boolean; + // Absent for a story without a photo + media?: { + aspectRatio: '3 / 2' | '4 / 5'; + mediaSize: 'half' | 'medium'; + }; +} + +// How each story block is laid out (FR-ST-03): tone and side from the +// index, the photo's shape and column width from its proportions. +export function storyLayout(stories: readonly StoryBlock[]): StoryLayout[] { + return stories.map((story, index) => { + const { image } = story; + const landscape = + image !== undefined && + image.width >= LANDSCAPE_RATIO * image.height; + return { + tone: index % 2 === 0 ? 'paper' : 'alt', + spacing: index === 0 ? 'flushTop' : 'default', + reverse: index % 2 === 1, + priority: index === 0 && image !== undefined, + ...(image === undefined + ? {} + : { + media: landscape + ? { aspectRatio: '3 / 2', mediaSize: 'half' } + : { aspectRatio: '4 / 5', mediaSize: 'medium' }, + }), + }; + }); +} diff --git a/web/src/navSubmenu.test.tsx b/web/src/navSubmenu.test.tsx new file mode 100644 index 0000000..3fe9cdf --- /dev/null +++ b/web/src/navSubmenu.test.tsx @@ -0,0 +1,226 @@ +import { act, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import shootTypes from '@/content/shootTypes'; +import { shootPagePath } from '@/lib/shootPages'; +import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver'; +import { mockViewport } from '@/test/navViewport'; +import { renderApp } from '@/test/renderApp'; + +// The real route tree with the real navigation: current state (D4), closing +// on a route change and the mobile menu (FR-ST-10) + +// The homepage's review carousel (Zag) needs an IntersectionObserver and +// Element.scrollTo, which jsdom lacks (as in app.test.tsx) +beforeEach(() => { + vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver); + Element.prototype.scrollTo = () => {}; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + FakeIntersectionObserver.reset(); + // @ts-expect-error -- jsdom has no Element.scrollTo of its own + delete Element.prototype.scrollTo; +}); + +const PARENT = 'Soorten fotoshoots'; +const TOGGLE = 'Submenu Soorten fotoshoots'; + +const header = () => screen.getByRole('banner'); +const panel = () => document.getElementById('submenu-soorten-fotoshoots')!; +const footerNav = () => screen.getByRole('navigation', { name: 'Footermenu' }); +const toggle = () => screen.getByRole('button', { name: TOGGLE }); +const hamburger = () => screen.getByTestId('nav-menu-toggle'); + +// By text: the name of a link in a closed (hidden) panel is empty +const panelLinks = () => within(panel()).getAllByRole('link', { hidden: true }); +const panelLink = (text: string) => + panelLinks().find((link) => link.textContent === text)!; +const parentLink = () => within(header()).getByRole('link', { name: PARENT }); +const footerLink = () => + within(footerNav()).getByRole('link', { name: PARENT }); + +async function renderDesktop(path: string) { + mockViewport(1280); + const rendered = await renderApp(path); + // The shell is there once the lazy route has loaded + await screen.findByRole('main'); + return { ...rendered, user: userEvent.setup() }; +} + +async function renderMobile(path: string) { + const viewport = mockViewport(375); + const rendered = await renderApp(path); + await screen.findByRole('main'); + return { ...rendered, viewport, user: userEvent.setup() }; +} + +describe('current page in the navigation (D4)', () => { + it.each(shootTypes)( + 'marks $name in the panel, the section on the parent and nothing in the footer', + async (shoot) => { + await renderDesktop(shootPagePath(shoot.id)); + for (const link of panelLinks()) { + if (link.textContent === shoot.name) { + expect(link).toHaveAttribute('aria-current', 'page'); + } else { + expect(link).not.toHaveAttribute('aria-current'); + } + } + expect(parentLink()).not.toHaveAttribute('aria-current'); + expect(parentLink()).toHaveAttribute('data-section-current'); + expect(footerLink()).not.toHaveAttribute('aria-current'); + }, + ); + + it('marks the parent and the footer on the overview, and no panel link', async () => { + await renderDesktop('/soorten-fotoshoots'); + expect(parentLink()).toHaveAttribute('aria-current', 'page'); + expect(parentLink()).toHaveAttribute('data-section-current'); + expect(footerLink()).toHaveAttribute('aria-current', 'page'); + for (const link of panelLinks()) { + expect(link).not.toHaveAttribute('aria-current'); + } + }); + + it('marks no panel link and no section on another page', async () => { + await renderDesktop('/portfolio'); + for (const link of panelLinks()) { + expect(link).not.toHaveAttribute('aria-current'); + } + expect(parentLink()).not.toHaveAttribute('data-section-current'); + expect(parentLink()).not.toHaveAttribute('aria-current'); + }); + + it('treats a trailing slash like the plain path (BR-NAV-04)', async () => { + await renderDesktop('/soorten-fotoshoots/newborn/'); + expect(panelLink('Newborn')).toHaveAttribute('aria-current', 'page'); + expect(parentLink()).toHaveAttribute('data-section-current'); + expect(parentLink()).not.toHaveAttribute('aria-current'); + expect(footerLink()).not.toHaveAttribute('aria-current'); + }); + + it('shows the page on a case variant, underlines the section but marks no link (router case rule)', async () => { + await renderDesktop('/soorten-fotoshoots/Newborn'); + // The router matches case-insensitively and renders the page, but + // its exact aria-current compares case-sensitively (Step 2). The + // only mark left is the breadcrumb's own current item (BR-SP-01). + const current = document.querySelectorAll('[aria-current="page"]'); + expect(current).toHaveLength(1); + expect(current[0]).not.toHaveAttribute('href'); + expect(current[0].closest('nav')).toHaveAccessibleName('Kruimelpad'); + expect(parentLink()).toHaveAttribute('data-section-current'); + }); + + it('keeps the panel in step with the shoot types (single source)', async () => { + await renderDesktop('/'); + expect(panelLinks().map((link) => link.textContent)).toEqual( + shootTypes.map((shoot) => shoot.name), + ); + expect(panelLinks().map((link) => link.getAttribute('href'))).toEqual( + shootTypes.map((shoot) => shootPagePath(shoot.id)), + ); + }); +}); + +describe('desktop submenu and the router', () => { + it('closes when the route changes', async () => { + const { router, user } = await renderDesktop('/'); + await user.click(toggle()); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + await act(() => router.navigate({ to: '/portfolio' })); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('closes on a link choice, opens the page and focuses main (BR-NAV-26)', async () => { + const { user } = await renderDesktop('/'); + await user.click(toggle()); + await user.click( + within(panel()).getByRole('link', { name: 'Zwangerschap' }), + ); + await waitFor(() => + expect( + screen.getByRole('heading', { level: 1 }), + ).toBeInTheDocument(), + ); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + await waitFor(() => + expect(document.getElementById('main')).toHaveFocus(), + ); + expect(panelLink('Zwangerschap')).toHaveAttribute( + 'aria-current', + 'page', + ); + }); + + it('does not close on the first render', async () => { + const { user } = await renderDesktop('/'); + await user.click(toggle()); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + }); +}); + +describe('mobile menu and the router', () => { + it('closes when the route changes without a menu click', async () => { + const { router, user } = await renderMobile('/contact'); + await user.click(hamburger()); + expect(hamburger()).toHaveAttribute('aria-expanded', 'true'); + await act(() => router.navigate({ to: '/portfolio' })); + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('closes on the browser back button (BR-NAV-32)', async () => { + const { router, user } = await renderMobile('/contact'); + await act(() => router.navigate({ to: '/portfolio' })); + await user.click(hamburger()); + expect(hamburger()).toHaveAttribute('aria-expanded', 'true'); + await act(async () => router.history.back()); + await waitFor(() => + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'), + ); + expect(router.state.location.pathname).toBe('/contact'); + }); + + it('expands the group when it opens on a shoot page', async () => { + const { user } = await renderMobile('/soorten-fotoshoots/loveshoot'); + await user.click(hamburger()); + const group = within(document.getElementById('mobile-nav')!).getByRole( + 'button', + { name: TOGGLE }, + ); + expect(group).toHaveAttribute('aria-expanded', 'true'); + expect( + within(document.getElementById('mobile-nav')!).getByRole('link', { + name: 'Loveshoot', + }), + ).toHaveAttribute('aria-current', 'page'); + }); +}); + +describe('crossing the lg breakpoint', () => { + it('closes the mobile menu that no longer exists', async () => { + const { viewport, user } = await renderMobile('/contact'); + await user.click(hamburger()); + expect(hamburger()).toHaveAttribute('aria-expanded', 'true'); + viewport.resize(1280); + viewport.resize(375); + await waitFor(() => + expect(hamburger()).toHaveAttribute('aria-expanded', 'false'), + ); + expect(document.body.style.overflow).toBe(''); + }); + + it('closes the desktop submenu that no longer exists', async () => { + const rendered = await renderMobile('/contact'); + rendered.viewport.resize(1280); + await waitFor(() => expect(toggle()).toBeInTheDocument()); + await rendered.user.click(toggle()); + expect(toggle()).toHaveAttribute('aria-expanded', 'true'); + rendered.viewport.resize(375); + rendered.viewport.resize(1280); + await waitFor(() => + expect(toggle()).toHaveAttribute('aria-expanded', 'false'), + ); + }); +}); diff --git a/web/src/navigation.test.ts b/web/src/navigation.test.ts index 316c00b..14da7a7 100644 --- a/web/src/navigation.test.ts +++ b/web/src/navigation.test.ts @@ -1,5 +1,13 @@ import { describe, expect, it } from 'vitest'; -import { footerNav, mainNav } from './navigation'; +import shootTypes from './content/shootTypes'; +import { + SHOOT_TYPE_IDS, + SHOOT_TYPES_PATH, + shootIdFromPath, + shootPagePath, +} from './lib/shootPages'; +import { footerNav, hasChildren, mainNav } from './navigation'; +import sitePages from './sitePages'; describe('menu', () => { it('hoofdmenu heeft de vaste volgorde', () => { @@ -35,3 +43,66 @@ describe('menu', () => { } }); }); + +describe('submenu Soorten fotoshoots', () => { + const parent = mainNav.find((item) => item.to === SHOOT_TYPES_PATH); + + it('heeft de vijf shoots als kinderen, in de volgorde van de shoottypes', () => { + expect(parent?.children).toEqual( + shootTypes.map((shoot) => ({ + to: shootPagePath(shoot.id), + label: shoot.name, + })), + ); + expect(parent?.children?.map((child) => child.label)).toEqual([ + 'Newborn', + 'Zwangerschap', + 'Gezin', + 'Loveshoot', + 'Portretten', + ]); + }); + + it('heeft een menu-item voor elk shoottype en niets extra', () => { + expect( + parent?.children + ?.map((child) => shootIdFromPath(child.to)) + .toSorted(), + ).toEqual([...SHOOT_TYPE_IDS].toSorted()); + }); + + it('geeft alleen het hoofditem kinderen, op één niveau', () => { + const others = [ + ...mainNav.filter((item) => item !== parent), + ...footerNav, + ]; + for (const item of others) { + expect(item.children).toBeUndefined(); + } + for (const child of parent?.children ?? []) { + expect(child.children).toBeUndefined(); + } + }); + + it('hasChildren is alleen waar voor het hoofditem', () => { + expect(mainNav.filter(hasChildren)).toEqual([parent]); + expect(hasChildren({ to: '/', label: 'Home', children: [] })).toBe( + false, + ); + expect(hasChildren({ to: '/', label: 'Home' })).toBe(false); + }); + + it('heeft geen dubbele routes in het hoofditem en zijn kinderen', () => { + const paths = [ + parent?.to, + ...(parent?.children ?? []).map((c) => c.to), + ]; + expect(new Set(paths).size).toBe(paths.length); + }); + + it('linkt alleen naar geregistreerde, geïndexeerde pagina’s', () => { + for (const child of parent?.children ?? []) { + expect(sitePages[child.to]?.indexed).toBe(true); + } + }); +}); diff --git a/web/src/navigation.ts b/web/src/navigation.ts index d47e7b4..e019ba0 100644 --- a/web/src/navigation.ts +++ b/web/src/navigation.ts @@ -1,3 +1,5 @@ +import shootTypes from './content/shootTypes.ts'; +import { shootNavItems } from './lib/shootNavItems.ts'; import type { FileRoutesByTo } from './routeTree.gen.ts'; // Menu's verwijzen naar routes, en routes zijn code: het CMS kan geen @@ -7,6 +9,15 @@ export type RoutePath = keyof FileRoutesByTo; export interface NavItem { to: RoutePath; label: string; + // Sub-pages, one level only; an empty array counts as none + children?: readonly NavItem[]; +} + +// Whether the item has a submenu (a non-empty list of children) +export function hasChildren( + item: NavItem, +): item is NavItem & { children: readonly NavItem[] } { + return (item.children?.length ?? 0) > 0; } // Hoofdmenu: desktopnavigatie en mobiel menu @@ -14,7 +25,12 @@ export const mainNav: readonly NavItem[] = [ { to: '/', label: 'Home' }, { to: '/over-mij', label: 'Over mij' }, { to: '/portfolio', label: 'Portfolio' }, - { to: '/soorten-fotoshoots', label: 'Soorten fotoshoots' }, + { + to: '/soorten-fotoshoots', + label: 'Soorten fotoshoots', + // One source: a new shoot type shows up in the menu by itself (D5) + children: shootNavItems(shootTypes), + }, { to: '/contact', label: 'Contact' }, ]; diff --git a/web/src/shootPages.test.tsx b/web/src/shootPages.test.tsx new file mode 100644 index 0000000..66fedf9 --- /dev/null +++ b/web/src/shootPages.test.tsx @@ -0,0 +1,345 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { screen, within } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import packages from './content/packages'; +import shootPageShared from './content/shootPageShared'; +import shootTypes from './content/shootTypes'; +import { formatPrice } from './lib/formatPrice'; +import { readMoreLabel } from './lib/readMoreLabel'; +import { shootPagePath } from './lib/shootPages'; +import sitePages from './sitePages'; +import { FakeIntersectionObserver } from './test/fakeIntersectionObserver'; +import { axeResults } from './test/axe'; +import { cssRulesFor } from './test/cssRules'; +import { expectShell, renderApp } from './test/renderApp'; + +// The pages use IntersectionObserver (fade-in, deferred photos) and the +// homepage-style shell may use Element.scrollTo, which jsdom lacks +beforeEach(() => { + vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver); + Element.prototype.scrollTo = () => {}; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + FakeIntersectionObserver.reset(); + // @ts-expect-error -- jsdom has no Element.scrollTo of its own + delete Element.prototype.scrollTo; +}); + +const withPackage = ['newborn', 'zwangerschap', 'gezin']; +const mosaicTiles: Record = { newborn: 3 }; + +const renderShoot = async (id: string) => { + const path = shootPagePath(id as (typeof shootTypes)[number]['id']); + const result = await renderApp(path); + await screen.findByRole('heading', { level: 1 }); + return result; +}; + +const isAlt = (element: Element) => + cssRulesFor(element).join().includes('var(--slp-colors-paper-alt)'); + +describe('shoot pages', () => { + it.each(shootTypes.map((shoot) => shoot.id))( + '%s has a clean heading outline and the sections its data says', + async (id) => { + const { container } = await renderShoot(id); + expectShell(); + const main = screen.getByRole('main'); + + expect( + within(main).getAllByRole('heading', { level: 1 }), + ).toHaveLength(1); + // Six process steps; FAQ questions are summaries, not headings + expect( + within(main).getAllByRole('heading', { level: 3 }), + ).toHaveLength(6); + const levels = [ + ...main.querySelectorAll('h1, h2, h3, h4, h5, h6'), + ].map((heading) => Number(heading.tagName[1])); + levels.slice(1).forEach((level, index) => { + expect(level).toBeLessThanOrEqual(levels[index] + 1); + }); + // Every section is named by an existing heading + for (const section of main.querySelectorAll('section')) { + const target = section.getAttribute('aria-labelledby')!; + expect(main.querySelector(`#${target}`)).not.toBeNull(); + } + + expect(main.querySelector('#zo-werkt-het')).not.toBeNull(); + expect(main.querySelector('#vragen')).not.toBeNull(); + expect(main.querySelector('#pakket')).not.toBeNull(); + const tiles = mosaicTiles[id] ?? 0; + if (tiles > 0) { + expect(main.querySelector('#impressie')).not.toBeNull(); + expect( + within(screen.getByTestId('photo-mosaic')).getAllByRole( + 'listitem', + ), + ).toHaveLength(tiles); + } else { + expect(main.querySelector('#impressie')).toBeNull(); + expect(screen.queryByTestId('photo-mosaic')).toBeNull(); + } + + expect(await axeResults(container)).toHaveNoViolations(); + }, + ); + + it.each(shootTypes)( + '$id has a breadcrumb that ends at the page itself, and nothing else in main is current', + async ({ id, name }) => { + await renderShoot(id); + const crumb = screen.getByRole('navigation', { + name: 'Kruimelpad', + }); + expect(crumb).toBe(screen.getByTestId('shoot-breadcrumb')); + const items = within(crumb).getAllByRole('listitem'); + // Three items and two separators + expect( + items.filter((item) => !item.hasAttribute('aria-hidden')), + ).toHaveLength(3); + expect( + within(crumb).getByRole('link', { name: 'Home' }), + ).toHaveAttribute('href', '/'); + expect( + within(crumb).getByRole('link', { name: 'Soorten fotoshoots' }), + ).toHaveAttribute('href', '/soorten-fotoshoots'); + const current = within(crumb).getByText(name); + expect(current).toHaveAttribute('aria-current', 'page'); + + // The header and footer are checked on the whole page below + const marked = screen + .getByRole('main') + .querySelectorAll('[aria-current]'); + expect([...marked]).toEqual([current]); + }, + ); + + // Whole-page facet (BR-SP-03, application design D4). The header submenu + // child and the breadcrumb's last item both name the page itself, so the + // rule is "at most one in main and at most one in each menu", not one + // overall. The two menus (the header's, and the mobile menu which is a + // sibling of the header and only one of them shows at a time) each mark + // the shoot's own link; the parent link and the footer link are not + // current. + it.each(shootTypes)( + '$id marks only the page itself as current: once in main (breadcrumb) and once in each menu (submenu link)', + async ({ id, name }) => { + await renderShoot(id); + const header = screen.getByRole('banner'); + const main = screen.getByRole('main'); + const footer = screen.getByRole('contentinfo'); + const crumbCurrent = within( + screen.getByTestId('shoot-breadcrumb'), + ).getByText(name); + + const inMain = [...main.querySelectorAll('[aria-current]')]; + expect(inMain).toEqual([crumbCurrent]); + + const inHeader = [...header.querySelectorAll('[aria-current]')]; + expect(inHeader).toHaveLength(1); + expect(inHeader[0]).toHaveAttribute('aria-current', 'page'); + expect(inHeader[0]).toHaveAttribute('href', shootPagePath(id)); + // The parent stays unmarked for assistive technology + const parentLinks = [ + ...document.querySelectorAll( + 'header a[href="/soorten-fotoshoots"], #mobile-nav a[href="/soorten-fotoshoots"]', + ), + ]; + expect(parentLinks.length).toBeGreaterThan(0); + expect( + parentLinks.some((link) => link.hasAttribute('aria-current')), + ).toBe(false); + + expect(footer.querySelectorAll('[aria-current]')).toHaveLength(0); + const mobile = [ + ...document.querySelectorAll('#mobile-nav [aria-current]'), + ]; + expect(mobile).toHaveLength(1); + expect(mobile[0]).toHaveAttribute('aria-current', 'page'); + expect(mobile[0]).toHaveAttribute('href', shootPagePath(id)); + + // Nothing outside breadcrumb, header menu and mobile menu + expect( + document.querySelectorAll('[aria-current="page"]'), + ).toHaveLength(3); + }, + ); + + it.each(shootTypes)( + '$id shows the right offer, with the deposit note and a closing band of another tone', + async ({ id }) => { + await renderShoot(id); + const offer = screen.getByTestId('package-block'); + const note = shootPageShared.deposit.note.replace( + '{aanbetaling}', + formatPrice(shootPageShared.deposit.amount), + ); + const noteElement = within(offer).getByText( + (_, element) => + element?.textContent === note && element.tagName === 'P', + ); + + if (withPackage.includes(id)) { + const pkg = packages.find((item) => item.id === id)!; + expect( + within(offer).getByRole('link', { + name: 'Boek dit pakket', + }), + ).toHaveAttribute('href', `/contact?pakket=${id}`); + expect( + within(offer).getByRole('link', { + name: shootPageShared.offer.askLabel, + }), + ).toHaveAttribute('href', '/contact'); + expect( + within(offer).getByText( + (_, element) => + element?.tagName === 'P' && + element.textContent === formatPrice(pkg.price), + ), + ).toBeInTheDocument(); + } else { + expect( + within(offer).getByText('Prijs op aanvraag'), + ).toBeInTheDocument(); + expect(within(offer).queryByRole('list')).toBeNull(); + const links = within(offer).getAllByRole('link'); + expect(links).toHaveLength(1); + expect(links[0]).toHaveAttribute('href', '/contact'); + } + // The note comes after the actions + const lastLink = within(offer).getAllByRole('link').at(-1)!; + expect( + lastLink.compareDocumentPosition(noteElement) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + + const packageBand = screen + .getByRole('main') + .querySelector('#pakket')!; + const closingBand = screen.getByTestId('shoot-closing'); + expect(isAlt(packageBand)).not.toBe(isAlt(closingBand)); + }, + ); + + it.each(shootTypes.map((shoot) => shoot.id))( + '%s loads only the first story photo with priority', + async (id) => { + await renderShoot(id); + const images = within(screen.getByRole('main')).getAllByRole('img'); + const first = within(screen.getByTestId('shoot-page')) + .getAllByRole('img') + .at(0)!; + expect(images[0]).toBe(first); + expect(first).not.toHaveAttribute('loading', 'lazy'); + expect(first).toHaveAttribute('fetchpriority', 'high'); + for (const image of images.slice(1)) { + expect(image).not.toHaveAttribute('loading', 'eager'); + expect(image).not.toHaveAttribute('fetchpriority'); + } + }, + ); +}); + +describe('overview page', () => { + it('gives every shoot a "Lees meer" link to its page, first in its row, with a unique name', async () => { + await renderApp('/soorten-fotoshoots'); + await screen.findByRole('heading', { level: 1 }); + const names: string[] = []; + for (const shoot of shootTypes) { + const link = screen.getByRole('link', { + name: readMoreLabel(shoot), + }); + expect(link).toHaveAttribute('href', shootPagePath(shoot.id)); + const article = link.closest('article')!; + expect(article.id).toBe(shoot.id); + expect(within(article).getAllByRole('link')[0]).toBe(link); + names.push(link.textContent!); + } + expect(new Set(names).size).toBe(shootTypes.length); + }); + + it('keeps the anchors and the old links', async () => { + await renderApp('/soorten-fotoshoots'); + await screen.findByRole('heading', { level: 1 }); + for (const shoot of shootTypes) { + expect( + screen.getByRole('article', { name: shoot.name }), + ).toHaveAttribute('id', shoot.id); + expect( + screen.getByTestId(`shoot-${shoot.id}-contact`), + ).toBeInTheDocument(); + } + }); + + it('links to each shoot page exactly once and to no other shoot path', async () => { + await renderApp('/soorten-fotoshoots'); + await screen.findByRole('heading', { level: 1 }); + const main = screen.getByRole('main'); + const hrefs = within(main) + .getAllByRole('link') + .map((link) => link.getAttribute('href')!) + .filter((href) => href.startsWith('/soorten-fotoshoots/')); + expect([...hrefs].sort()).toEqual( + shootTypes.map((shoot) => shootPagePath(shoot.id)).sort(), + ); + }); +}); + +// The size of a JPEG, read from its start-of-frame marker (baseline, +// extended, progressive or lossless), without an image library +function jpegSize(bytes: Uint8Array) { + expect([bytes[0], bytes[1]]).toEqual([0xff, 0xd8]); + let offset = 2; + while (offset + 9 < bytes.length) { + expect(bytes[offset]).toBe(0xff); + const marker = bytes[offset + 1]; + const length = (bytes[offset + 2] << 8) | bytes[offset + 3]; + const isFrame = + marker >= 0xc0 && + marker <= 0xcf && + ![0xc4, 0xc8, 0xcc].includes(marker); + if (isFrame) { + return { + height: (bytes[offset + 5] << 8) | bytes[offset + 6], + width: (bytes[offset + 7] << 8) | bytes[offset + 8], + }; + } + offset += 2 + length; + } + throw new Error('no frame marker in the JPEG'); +} + +describe('preview images of the shoot pages', () => { + it.each(shootTypes.map((shoot) => shoot.id))( + '%s has a registered 1200 x 630 JPEG of at most 150 KB', + (id) => { + const og = sitePages[shootPagePath(id)].ogImage; + expect(og).toBeDefined(); + expect(og!.path).toBe(`/og-${id}.jpg`); + expect(og!.width).toBe(1200); + expect(og!.height).toBe(630); + expect(og!.alt.trim()).not.toBe(''); + + const file = resolve( + import.meta.dirname, + '../public', + `og-${id}.jpg`, + ); + const bytes = readFileSync(file); + expect(bytes.length).toBeLessThanOrEqual(150 * 1024); + expect(jpegSize(bytes)).toEqual({ width: 1200, height: 630 }); + }, + ); + + it('uses no preview image twice in the registry', () => { + const paths = Object.values(sitePages).flatMap((page) => + page.ogImage ? [page.ogImage.path] : [], + ); + expect(new Set(paths).size).toBe(paths.length); + }); +}); diff --git a/web/src/sitePages.ts b/web/src/sitePages.ts index c7cc3b4..6a564fa 100644 --- a/web/src/sitePages.ts +++ b/web/src/sitePages.ts @@ -68,6 +68,12 @@ const sitePages: Record = { description: "Newbornshoot in Huizen en omgeving, bij jou thuis in het rustige ritme van je baby. Warme, spontane foto's van Andrea Slop Fotografie.", indexed: true, + ogImage: { + path: '/og-newborn.jpg', + width: 1200, + height: 630, + alt: 'Babyvuistje tussen een gebreide deken en een geruite doek', + }, }, '/soorten-fotoshoots/zwangerschap': { // DRAFT(CON-ST-03): awaiting Andrea's approval @@ -76,6 +82,12 @@ const sitePages: Record = { description: "Zwangerschapsshoot in Huizen en omgeving: leg deze bijzondere periode vast in spontane foto's. Ontdek de mogelijkheden van Andrea Slop Fotografie.", indexed: true, + ogImage: { + path: '/og-zwangerschap.jpg', + width: 1200, + height: 630, + alt: 'Zwangere buik in een zwarte jurk, omarmd door twee handen', + }, }, '/soorten-fotoshoots/gezin': { // DRAFT(CON-ST-03): awaiting Andrea's approval @@ -84,6 +96,12 @@ const sitePages: Record = { description: 'Gezinsshoot in Huizen en omgeving: echte momenten die laten zien hoe jullie nu samen zijn. Ontdek de mogelijkheden van Andrea Slop Fotografie.', indexed: true, + ogImage: { + path: '/og-gezin.jpg', + width: 1200, + height: 630, + alt: 'Jonge ouders kijken samen naar hun slapende pasgeboren baby', + }, }, '/soorten-fotoshoots/loveshoot': { // DRAFT(CON-ST-03): awaiting Andrea's approval @@ -92,6 +110,12 @@ const sitePages: Record = { description: "Loveshoot in Huizen en omgeving: leg jullie liefde vast in spontane, kleurrijke foto's. Ontdek de mogelijkheden van Andrea Slop Fotografie.", indexed: true, + ogImage: { + path: '/og-loveshoot.jpg', + width: 1200, + height: 630, + alt: 'Een stel ligt in de zon op een plaid in het gras, met de hoofden tegen elkaar', + }, }, '/soorten-fotoshoots/portret': { // DRAFT(CON-ST-03): awaiting Andrea's approval @@ -100,6 +124,12 @@ const sitePages: Record = { description: "Portretshoot in Huizen en omgeving, in de natuur of zakelijk. Spontane portretfoto's van Andrea Slop Fotografie.", indexed: true, + ogImage: { + path: '/og-portret.jpg', + width: 1200, + height: 630, + alt: 'Een vrouw met lang bruin haar in een witte blouse kijkt glimlachend omlaag, met bomen op de achtergrond', + }, }, '/contact': { title: 'Contact – fotoshoot boeken in Huizen', diff --git a/web/src/test/arbitraries.ts b/web/src/test/arbitraries.ts index 2dcc4a0..0bf6e6c 100644 --- a/web/src/test/arbitraries.ts +++ b/web/src/test/arbitraries.ts @@ -2,6 +2,7 @@ import fc from 'fast-check'; import type { ContactField, ContactValues } from '../contact/types'; import type { ContactFormEvent } from '../lib/contactFormReducer'; import type { LightboxEvent } from '../lib/lightboxReducer'; +import { shootPageView, type ShootPageView } from '../lib/shootPageView'; import type { Point } from '../lib/swipeDirection'; import type { ContentImage, @@ -673,3 +674,74 @@ export const slugInput: fc.Arbitrary = fc.oneof( fc.object(), ), ); + +// --- Shoot page UI (unit 2) --- + +// A photo whose proportions sit around the landscape threshold of 1.2: +// exactly on it, just below and just above, and anywhere else +export const imageWithOrientation: fc.Arbitrary = fc + .tuple( + contentImage, + fc.integer({ min: 20, max: 1500 }), + fc.constantFrom('exact', 'below', 'above', 'any'), + fc.integer({ min: 20, max: 4000 }), + ) + .map(([base, step, kind, anyWidth]) => { + // A height divisible by 5, so that 1.2 x height is a whole number + const height = step * 5; + const edge = step * 6; + const width = + kind === 'exact' + ? edge + : kind === 'below' + ? edge - 1 + : kind === 'above' + ? edge + 1 + : anyWidth; + return { ...base, width, height }; + }); + +// Counts around the mosaic sizes, below zero included +export const mosaicCount = fc.integer({ min: -3, max: 12 }); + +// One step of a timeline with hostile strings +const hostileText = fc.oneof( + fc.string({ minLength: 1, maxLength: 30 }), + fc.constantFrom( + '', + '<', + '>', + '&', + 'x'.repeat(120), + ' ', + ' ', + 'ac&d', + ), +); + +// 1 to 8 timeline steps with unique ids +export const timelineSteps = fc.uniqueArray( + fc.record({ id: slug, title: hostileText, text: hostileText }), + { selector: (step) => step.id, minLength: 1, maxLength: 8 }, +); + +// A shoot page view built the way the route builds it: stories 0 to 6, the +// photos present or not, the FAQ present or not, a package or none +export const shootPageViewArb: fc.Arbitrary = fc + .tuple(shootType, uniquePackages, shootPageShared, anySiteContent) + .chain(([shoot, packages, shared, site]) => + shootPageContent(shoot.id, [ + shoot.image, + ...(shoot.detailImage ? [shoot.detailImage] : []), + ]).map((page) => { + const view = shootPageView(shoot.id, page, { + shootTypes: [shoot], + packages, + shared, + site, + portfolioShoots: [shoot.id], + }); + if (view === undefined) throw new Error('no view for a valid case'); + return view; + }), + ); diff --git a/web/src/test/navArbitraries.ts b/web/src/test/navArbitraries.ts new file mode 100644 index 0000000..54ef470 --- /dev/null +++ b/web/src/test/navArbitraries.ts @@ -0,0 +1,115 @@ +import fc from 'fast-check'; +import { + initialNavMenuState, + navMenuReducer, + type NavMenuEvent, + type NavMenuState, +} from '../lib/navMenuState'; +import { shootPagePath } from '../lib/shootPages'; +import { knownRoutePath, shootTypeId } from './arbitraries'; + +// Generators of the navigation submenu unit (unit 3). Kept apart from +// arbitraries.ts, which other units edit as well. + +// Any menu event with a random payload; viewport, toggles and escape are +// weighted up so sequences actually open and close things +export const navMenuEvent: fc.Arbitrary = fc.oneof( + { + weight: 4, + arbitrary: fc + .boolean() + .map((isDesktop) => ({ type: 'viewport' as const, isDesktop })), + }, + { + weight: 4, + arbitrary: fc + .boolean() + .map((inSection) => ({ type: 'toggleMenu' as const, inSection })), + }, + { weight: 3, arbitrary: fc.constant({ type: 'toggleGroup' as const }) }, + { weight: 4, arbitrary: fc.constant({ type: 'toggleSubmenu' as const }) }, + { + weight: 4, + arbitrary: fc + .boolean() + .map((focusInside) => ({ type: 'escape' as const, focusInside })), + }, + { weight: 2, arbitrary: fc.constant({ type: 'outside' as const }) }, + { weight: 2, arbitrary: fc.constant({ type: 'focusLeave' as const }) }, + { weight: 1, arbitrary: fc.constant({ type: 'linkChosen' as const }) }, + { weight: 1, arbitrary: fc.constant({ type: 'routeChanged' as const }) }, + { weight: 2, arbitrary: fc.constant({ type: 'focusHandled' as const }) }, +); + +// A sequence of up to 40 menu events +export const navMenuEvents: fc.Arbitrary = fc.array( + navMenuEvent, + { maxLength: 40 }, +); + +// A state reached from the initial one by random events, so it satisfies the +// invariants by construction (I1-I4 are checked on it by the tests) +export const navMenuState: fc.Arbitrary = navMenuEvents.map( + (events) => events.reduce(navMenuReducer, initialNavMenuState), +); + +// The same, restricted to a viewport: a state that has seen that width +export const navMenuStateOn = ( + isDesktop: boolean, +): fc.Arbitrary => + navMenuEvents.map((events) => + [{ type: 'viewport', isDesktop } as const, ...events].reduce( + navMenuReducer, + initialNavMenuState, + ), + ); + +// Strings that must never break a path comparison +const hostilePathname = fc.constantFrom( + '', + '/', + '//', + '///', + ' ', + '/ soorten-fotoshoots', + '/soorten-fotoshoots%2F', + '/soorten-fotoshoots/%2e%2e/', + '/soorten-fotoshoots\newborn', + '/soorten-fotoshoots?x=1', + '/soorten-fotoshoots#top', + '\u0000', + '/İNDEX', + 'a'.repeat(5000), +); + +// Prefix look-alikes of the overview: not the overview, not a shoot page +const lookAlike = fc.constantFrom( + '/soorten-fotoshoots-extra', + '/soorten-fotoshootsX', + '/soorten-fotoshoot', + '/soorten-fotoshoots/newborns', + '/soorten-fotoshoots/newborn/extra', + '/x/soorten-fotoshoots', +); + +// The ways a visitor or the router may spell a path +const spelling = (path: string) => + fc.constantFrom( + path, + `${path}/`, + path.toUpperCase(), + `${path.toUpperCase()}/`, + ); + +// A pathname: known routes and shoot pages in several spellings (trailing +// slash, letter case), prefix look-alikes and hostile strings +export const pathname: fc.Arbitrary = fc.oneof( + { weight: 4, arbitrary: knownRoutePath.chain(spelling) }, + { + weight: 4, + arbitrary: shootTypeId.chain((id) => spelling(shootPagePath(id))), + }, + { weight: 2, arbitrary: lookAlike }, + { weight: 2, arbitrary: hostilePathname }, + { weight: 1, arbitrary: fc.string() }, +); diff --git a/web/src/test/navViewport.ts b/web/src/test/navViewport.ts new file mode 100644 index 0000000..f3e201f --- /dev/null +++ b/web/src/test/navViewport.ts @@ -0,0 +1,74 @@ +import { act } from '@testing-library/react'; +import { afterEach, vi } from 'vitest'; + +// Makes window.matchMedia answer for a viewport of `width` px, so Chakra's +// breakpoint hooks (min-width queries) and prefers-reduced-motion behave as +// in a browser. jsdom has no layout and ignores @media rules, so the +// responsive display of the desktop list and the mobile menu is applied by a +// style element here (the browser check is Step 17). The stub is undone by +// vi.restoreAllMocks() in the global afterEach. +const styleId = 'nav-viewport-style'; + +afterEach(() => document.getElementById(styleId)?.remove()); + +export function mockViewport(width: number, { reducedMotion = false } = {}) { + type Listener = (event: { media: string; matches: boolean }) => void; + const listeners: { query: string; listener: Listener }[] = []; + let current = width; + + const matches = (query: string) => { + if (query.includes('prefers-reduced-motion')) return reducedMotion; + const min = /min-width:\s*([\d.]+)(px|em|rem)/.exec(query); + if (!min) return false; + return current >= parseFloat(min[1]) * (min[2] === 'px' ? 1 : 16); + }; + + vi.spyOn(window, 'matchMedia').mockImplementation( + (query: string) => + ({ + get matches() { + return matches(query); + }, + media: query, + onchange: null, + addEventListener: (_type: string, listener: Listener) => { + listeners.push({ query, listener }); + }, + removeEventListener: (_type: string, listener: Listener) => { + const index = listeners.findIndex( + (entry) => entry.listener === listener, + ); + if (index >= 0) listeners.splice(index, 1); + }, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }) as unknown as MediaQueryList, + ); + + // At lg and up the desktop list shows and the mobile menu is gone + const applyLayout = () => { + document.getElementById(styleId)?.remove(); + if (current < 992) return; + const style = document.createElement('style'); + style.id = styleId; + style.textContent = + 'nav[aria-label="Hoofdmenu"] > ul { display: flex !important; }' + + '#mobile-nav { display: none !important; }'; + document.head.append(style); + }; + applyLayout(); + + return { + // Resizes the "window" and tells every listener, like a browser does + resize(next: number) { + current = next; + applyLayout(); + act(() => { + for (const { query, listener } of [...listeners]) { + listener({ media: query, matches: matches(query) }); + } + }); + }, + }; +}