Pakketblok: elk aantal pakketten, filterchips, swipe-rij op mobiel en optionele banner
Pure logica (splitsen, chips, filter, labels), useSwipeRow en usePackageFilter, ContactPreselect voor het formulier, kaarten in stijl B en tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
- **Feature Slug**: redesign-modern-timetravel
|
||||
- **Project Type**: Brownfield
|
||||
- **Start Date**: 2026-11-09T13:00:00Z
|
||||
- **Current Stage**: CONSTRUCTION - U2 b-modern-sections Code Generation (in progress)
|
||||
- **Current Stage**: CONSTRUCTION - U3 packages-block Code Generation plan (awaiting approval)
|
||||
- **Branch**: feature/redesign-modern-timetravel
|
||||
|
||||
## Workspace State
|
||||
|
||||
@@ -586,3 +586,63 @@
|
||||
**Context**: CMS phase 2 unblocked pending the merge; U2 Code Generation starts.
|
||||
|
||||
---
|
||||
|
||||
## U2 Code Generation Complete
|
||||
|
||||
**Timestamp**: 2026-11-10T11:00:00Z
|
||||
|
||||
**User Input**: "Approve plan."
|
||||
|
||||
**AI Response**: "Executed all 9 steps of b-modern-sections-code-generation-plan.md. Tests 10 files/56 tests before, 13 files/122 tests after, all passed; lint 0 errors (2 pre-existing warnings); build OK, Sora/Instrument Sans removed from dist. Code commit on feature/redesign-modern-timetravel, no push. Deviations flagged in construction/b-modern-sections/code/summary.md (display headline from the design, panel filler text, no browser screenshots possible)."
|
||||
|
||||
**Context**: Code Generation U2 complete; awaiting the user's approval before U3.
|
||||
|
||||
---
|
||||
|
||||
## Correction: ASF Branch Merge NOT Authorized
|
||||
|
||||
**Timestamp**: 2026-11-10T11:30:00Z
|
||||
|
||||
**User Input**: "(cross-session message from CMS & API relaying Bryan's correction: feature/identity-email-notifications may NOT go to master yet; Bryan wants to test first; a merge follows only after his explicit go; a merge on Bryan's behalf is only passed on if he says so himself)"
|
||||
|
||||
**AI Response**: "Earlier today the AI read the user's remark 'ik denk dat de cms sessie ook wel kan mergen ...' as authorization to merge and relayed it to AndreaSlopFotografie, the builder and CMS & API. That was a misreading. Retracted to AndreaSlopFotografie and to the builder (SLS Software - CMS): no merge, no rebase, no phase 2; builder stays on stand-by. No merge had taken place. Lesson: ask for explicit confirmation before relaying an action as a decision when the wording is ambiguous."
|
||||
|
||||
**Context**: CMS phase 2 remains blocked on Bryan's explicit go.
|
||||
|
||||
---
|
||||
|
||||
## U2 Approved; U3 Functional Design Question Answered
|
||||
|
||||
**Timestamp**: 2026-11-10T12:30:00Z
|
||||
|
||||
**User Input**: "Akkoord, ga naar u3" / "Ik wil beide methoden kunnen gebruiken. Ik denk namelijk dat ik bij SLP Software begin met de op maat aanpak als p0akket, maar deze methode is voor Andrea Slop Fotografie mogelijk wel handig."
|
||||
|
||||
**AI Response**: "U2 approved, starting U3 (packages-block) Functional Design. Banner question: both presentations must be possible. Decision: a package can be shown as a normal card or as the black 'Past er niets bij?' banner under the cards, chosen per site by a frontend setting (bannerSlugs in content.ts, empty for SLP: Maatwerk stays a card); a later additive API field (layout: card|banner, CMS extension, not now) can take over the choice per offering. Chips from 4 packages are independent of the banner."
|
||||
|
||||
**Context**: Functional Design U3.
|
||||
|
||||
---
|
||||
|
||||
## U3 Functional Design Complete
|
||||
|
||||
**Timestamp**: 2026-11-10T13:10:00Z
|
||||
|
||||
**User Input**: "(none)"
|
||||
|
||||
**AI Response**: "Generated packages-block-functional-design-plan.md, packages-block-fd-questions.md and construction/packages-block/functional-design/{domain-entities, business-rules (BR-U3-1..12), business-logic-model, frontend-components}.md with Mermaid diagrams. Key decisions: any number of packages; banner vs card chosen per site by packagesSettings.bannerSlugs (empty for SLP so Maatwerk stays a card; fallback banner texts; later additive API field layout); chips from 4 card packages with categories; swipe row below sm with snap, dots as buttons, featured scrolled into view; skeleton/error with retry/empty states; CTA sets preselect (slug, key) and scrolls to #contact. Completion message presented; awaiting approval."
|
||||
|
||||
**Context**: Functional Design U3 complete; next is Code Generation plan for U3.
|
||||
|
||||
---
|
||||
|
||||
## U3 Functional Design Approved; Code Generation Plan Ready
|
||||
|
||||
**Timestamp**: 2026-11-10T13:30:00Z
|
||||
|
||||
**User Input**: "ga verder"
|
||||
|
||||
**AI Response**: "U3 Functional Design approved. Created construction/plans/packages-block-code-generation-plan.md (7 steps). Plan approval prompt presented."
|
||||
|
||||
**Context**: Code Generation Part 1 for U3.
|
||||
|
||||
---
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
# Code Summary — packages-block (U3)
|
||||
|
||||
## What was built
|
||||
- **Pure logic** (`src/shared/packages/packageLogic.ts`): `splitPackages`, `deriveChips`, `filterCards`, `resultLabel`, `initialIndex`, `activeIndexFromScroll`.
|
||||
- **Hooks**: `usePackageFilter` (cards, banner packages, chips, active chip with fallback to "Alles", visible list, status label), `useSwipeRow` (start position on the featured card, rAF-throttled scroll sync for the dots, smooth `scrollTo` unless reduced motion).
|
||||
- **Contact hand-over** (`src/shared/contact/`): `ContactPreselectContext`/`Provider`/`useContactPreselect` (`subject` = package slug, `key` increments per click); the provider is mounted in `RootLayout`; U4 consumes it.
|
||||
- **Components**: `PackagesSection` (B styling: alt background, heading, intro, chips + live status line, list, banner, states), `FilterChips`, `PackageList` (one render path: scroll-snap swipe row below `sm`, grid 2 columns from `sm`, 3 above 1000px), `SwipeDots` (buttons with labels, `aria-current`, mobile only, hidden at one card), `PackageCard` (flat block, featured in brand red with "Meest gekozen" badge, CTA sets preselect and scrolls to `#contact`), `PackageBanner` (black "Past er niets bij?" block), `PackageCardSkeleton` (square, 3 in the same container).
|
||||
- **Settings** (`content.ts`): `packagesSettings = { bannerSlugs: [], chipThreshold: 4, bannerTitle, bannerFallback }`; `PackageCardData` gains optional `category`, `categoryId`, `displayOrder`.
|
||||
- **Token tweak**: B light `--color-surface-2` is now white (the card colour of the canvas).
|
||||
- **Heading**: "Drie manieren om te starten." with exactly three card packages, otherwise "Manieren om te starten."
|
||||
|
||||
## How a site chooses card vs banner
|
||||
Put the package slug in `packagesSettings.bannerSlugs` (e.g. `['maatwerk']`): it is then shown as the black banner under the cards (always visible, independent of the active chip) and not as a card; with no matching package the fallback texts are used. SLP Software keeps the list empty, so Maatwerk is a normal card. A later additive API field `layout: card | banner` can replace the setting.
|
||||
|
||||
## Verification (Step 13.5, real output)
|
||||
- Before this unit (after U2): 13 files / 122 tests. After: **14 files / 154 tests passed**; `pnpm lint` 0 errors (same 2 warnings); `pnpm build` OK (JS 453 kB, CSS 57.8 kB). Snap utilities and the `min-[1001px]` breakpoint are generated.
|
||||
- Tests cover: pure logic (split, chip threshold 3 vs 4, blank categories, filter, singular/plural label, initial index, scroll-to-index), the live three packages (no chips/banner, Maatwerk a card, heading), loading/error with retry/empty, six packages with chips and counts and filtering, banner via setting (kept for every chip, fallback, CTA preselect), preselect key increments and scroll to `#contact`, swipe row roles/classes/dots/click/reduced motion/scroll sync with mocked layout, accessibility attributes.
|
||||
|
||||
## Notes for review
|
||||
- **No `category` yet in the live API**: chips stay hidden until the CMS-U1 API is deployed (by design); with the current three packages the block looks like before, in the new style.
|
||||
- Real swipe feel, card widths at 360px and the dark look need a browser check (no layout engine in the tests).
|
||||
- Prettier touched two unrelated files; both were reverted.
|
||||
|
||||
## Hand-offs
|
||||
- U4: read `useContactPreselect()` in the form (subject options = packages + "Overig"; apply when `key` changes; unknown subject ignored).
|
||||
- U5: reuse `packageLogic`, `usePackageFilter`, `useSwipeRow`, `ContactPreselect*`; only the presentation (2006 style) is new.
|
||||
- CMS: optional future `layout` field on offerings (additive, not needed now).
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
# Business Logic Model — packages-block (U3)
|
||||
|
||||
## Data flow
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
box rgba(99,179,237,0.4) Browser
|
||||
participant V as Visitor
|
||||
participant PS as PackagesSection
|
||||
participant HK as usePackageFilter
|
||||
end
|
||||
box rgba(154,230,180,0.4) CMS API
|
||||
participant A as offerings
|
||||
end
|
||||
PS->>A: GET offerings
|
||||
A-->>PS: package array
|
||||
PS->>HK: split and derive chips
|
||||
HK-->>PS: cards, chips, banner
|
||||
V->>PS: choose a chip
|
||||
PS->>HK: set active chip
|
||||
HK-->>PS: filtered cards
|
||||
V->>PS: click Kies button
|
||||
PS->>PS: set preselect and scroll to contact
|
||||
```
|
||||
|
||||
Text alternative: the section loads the offerings, the filter hook splits cards and banner and derives chips, a chip choice filters the cards, and a Kies button sets the contact preselect and scrolls.
|
||||
|
||||
## Pure functions (unit-testable, `src/shared/packages/`)
|
||||
- `splitPackages(packages, bannerSlugs) -> { cards, banners }`
|
||||
- `deriveChips(cards, threshold) -> Chip[] | null` (null = no chips)
|
||||
- `filterCards(cards, activeId) -> PackageCardData[]`
|
||||
- `resultLabel(count, hasBanner) -> string` ("1 pakket ...", "3 pakketten ...")
|
||||
- `initialIndex(visible) -> number` (index of the featured card, else 0)
|
||||
- `activeIndexFromScroll(scrollLeft, itemWidths|itemOffsets, viewportWidth) -> number` (nearest snap position)
|
||||
|
||||
## Hooks
|
||||
- `usePackageFilter(packages, settings)`: state `activeId`; returns `{ cards, banners, chips, activeId, setActive, visible, label }`; resets `activeId` to `all` when the chosen category disappears.
|
||||
- `useSwipeRow(itemCount, initialIndex)`: returns `{ ref, activeIndex, scrollToIndex }`; on mount and when `itemCount`/filter key changes scrolls to `initialIndex` (instant); listens to `scroll` (throttled by `requestAnimationFrame`) to update `activeIndex`; uses `scrollTo({behavior})` with `smooth` unless reduced motion.
|
||||
- `useContactPreselect` (context from U3, consumed by U4): `{ subject, key, select(subject) }`.
|
||||
|
||||
## Error handling
|
||||
- API error: error state with retry (`refetch`); loading: skeletons; empty list: info text.
|
||||
- Unknown/absent `category`: package only under "Alles".
|
||||
- `bannerSlugs` containing an unknown slug: fallback banner from settings.
|
||||
- No `ResizeObserver`/`IntersectionObserver` required (scroll event + offsets); jsdom-safe.
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Business Rules — packages-block (U3)
|
||||
|
||||
| Id | Rule |
|
||||
|---|---|
|
||||
| BR-U3-1 | The block works with any number of packages (0..n) from the API; nothing is hard-coded to three. Array order = display order; no client-side sorting. |
|
||||
| BR-U3-2 | **Split**: packages whose `slug` is in `packagesSettings.bannerSlugs` are *banner packages*; all others are *card packages*. Default (empty list): everything is a card, so Maatwerk is a card at SLP Software. |
|
||||
| BR-U3-3 | **Chips** appear only when the number of card packages is at least `chipThreshold` (4) **and** there is at least one category. Chips: "Alles" plus the distinct non-empty categories of card packages in order of first appearance, each with its count. Selecting a chip shows only that category; "Alles" shows all card packages. Packages without category show only under "Alles". Chip state is not persisted. |
|
||||
| BR-U3-4 | **Result count**: below the chips a polite status line "N pakket(ten) met vaste prijs" (plus ", plus maatwerk" when a banner is shown); announced to screen readers when the filter changes. |
|
||||
| BR-U3-5 | **Layout**: from the `sm` breakpoint up a grid (3 columns, 2 columns up to 1000px); below it a **horizontal swipe row** (CSS scroll-snap, `snap-x snap-mandatory`, cards ~85% wide so the next card peeks) for any number of packages. The row works without JavaScript; JS only drives the dots and the initial position. |
|
||||
| BR-U3-6 | **Banner**: when banner packages exist (or `bannerSlugs` is non-empty without a match, using `bannerFallback`), a black banner is shown below the cards with title, text, price label/note and a CTA to `#contact`. The banner is always visible regardless of the active chip. With an empty `bannerSlugs` no banner is rendered. (Both presentations remain possible per site; a later additive API field `layout: card \| banner` can replace the setting without changing the UI.) |
|
||||
| BR-U3-7 | **Featured**: the featured package is styled with the brand colour and the "Meest gekozen" corner badge. In the swipe row the featured card is scrolled into view on first display (centered); if none is featured, the first card. After a filter change the row returns to its start (or the featured card if it is still visible). |
|
||||
| BR-U3-8 | **Dots** (mobile only): one real `<button>` per visible card, `aria-label="Pakket {n} van {total}: {title}"`, `aria-current` on the active one; clicking scrolls that card into view. The active dot follows the scroll position. Hidden when there is only one card. |
|
||||
| BR-U3-9 | **CTA** "Kies …" (card) and the banner CTA: sets the preselect (`subject = slug`, `key + 1`) and scrolls to `#contact`. Without JavaScript the link still jumps to `#contact`. |
|
||||
| BR-U3-10 | **Loading**: skeletons while loading — 3 in the grid, in the swipe row too (no layout shift). **Error**: message "Pakketten konden niet worden geladen." with a "Opnieuw proberen" button (refetch). **Empty** (0 packages): short text "Binnenkort meer informatie. Neem contact op voor een voorstel." and the banner when configured. |
|
||||
| BR-U3-11 | **Accessibility**: section labelled by its heading; chips are buttons with `aria-pressed`; cards are `article`s with an `h3`; the price is plain text; focus order = chips → cards (links) → banner; all touch targets ≥ 44px; swipe row is focusable/keyboard scrollable (`tabindex=0`, `role="group"`, `aria-label="Pakketten"`); animation (smooth scroll) respects reduced motion. |
|
||||
| BR-U3-12 | **Theme**: B light/dark tokens; E styling is U5. Square corners, flat blocks, as in the canvas. |
|
||||
|
||||
## Decision flow: split and chips
|
||||
```mermaid
|
||||
graph TD
|
||||
S([Packages loaded]) --> SP{Slug in bannerSlugs}
|
||||
SP -->|"yes"| B[Banner package]
|
||||
SP -->|"no"| C[Card package]
|
||||
C --> T{Card count at least threshold and a category exists}
|
||||
T -->|"yes"| CH[Show chips and counts]
|
||||
T -->|"no"| NC[No chips]
|
||||
B --> BN[Show banner under the cards]
|
||||
CH --> V[Filter cards by active chip]
|
||||
NC --> V
|
||||
classDef start fill:#CE93D8,stroke:#6A1B9A,color:#000;
|
||||
classDef decision fill:#FFF59D,stroke:#F57F17,color:#000;
|
||||
classDef step fill:#63b3ed,stroke:#2b6cb0,color:#000;
|
||||
class S start;
|
||||
class SP,T decision;
|
||||
class B,C,CH,NC,BN,V step;
|
||||
```
|
||||
|
||||
Text alternative: packages are split into cards and banner packages by slug; chips show when enough cards with categories exist; the active chip filters the cards; banner packages render under the cards.
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Domain Entities — packages-block (U3)
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
API[GET api v1 offerings] -->|"array of"| PK[PackageCardData]
|
||||
PK -->|"optional"| CAT[category name or null]
|
||||
PK -->|"flag"| FEA[featured]
|
||||
CFG[Site settings bannerSlugs] -->|"selects"| BAN[Banner package]
|
||||
PK -->|"split by settings"| CARDS[Card packages]
|
||||
PK -->|"split by settings"| BAN
|
||||
CARDS -->|"derives"| CHIPS[FilterChip list]
|
||||
CHIPS -->|"active id"| VIS[Visible cards]
|
||||
VIS --> ROW[Grid or swipe row]
|
||||
ROW -->|"CTA click"| PRE[Preselect subject and key]
|
||||
classDef data fill:#63b3ed,stroke:#2b6cb0,color:#000;
|
||||
classDef derived fill:#9ae6b4,stroke:#2f855a,color:#000;
|
||||
classDef cfg fill:#f6e05e,stroke:#c05621,color:#000;
|
||||
class API,PK,CAT,FEA data;
|
||||
class CARDS,BAN,CHIPS,VIS,ROW,PRE derived;
|
||||
class CFG cfg;
|
||||
```
|
||||
|
||||
Text alternative: offerings from the API are split into card packages and banner packages by a site setting; the cards produce filter chips, the active chip selects the visible cards shown in a grid or swipe row; a card button creates a preselect for the contact form.
|
||||
|
||||
## PackageCardData (extended)
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `id`, `slug`, `title`, `description`, `price`, `priceNote`, `features[]`, `ctaLabel`, `featured?` | as before | `price` is rendered verbatim |
|
||||
| `category?` | `string \| null` | category name from the CMS (CMS-U1); `null`/absent = no chip |
|
||||
| `categoryId?`, `displayOrder?` | additive CMS fields | ignored by the UI |
|
||||
|
||||
## Site settings (content.ts)
|
||||
| Setting | Type | Default | Meaning |
|
||||
|---|---|---|---|
|
||||
| `packagesSettings.bannerSlugs` | `string[]` | `[]` | packages shown as the black "Past er niets bij?" banner instead of a card. SLP: empty (Maatwerk is a card); Andrea-style sites may list `maatwerk` |
|
||||
| `packagesSettings.chipThreshold` | `number` | `4` | chips appear when the number of card packages is at least this (FR-8) |
|
||||
| `packagesSettings.bannerFallback` | `{ title, text, priceLabel, priceNote, ctaLabel }` | design texts | used only when `bannerSlugs` is non-empty and no package matches |
|
||||
|
||||
## FilterChip (derived)
|
||||
`{ id: 'all' | categoryName, label, count }`; "Alles" first; categories in order of first appearance among card packages; counts only count card packages; packages without category appear only under "Alles".
|
||||
|
||||
## Preselect (shared with U4)
|
||||
`ContactPreselect { subject: string | null; key: number }`: `subject` = package `slug`; `key` increments on every CTA click.
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# Frontend Components — packages-block (U3)
|
||||
|
||||
## Component hierarchy
|
||||
```mermaid
|
||||
graph TD
|
||||
pg[LandingPage] --> ps[PackagesSection]
|
||||
ps --> hd[SectionHeading]
|
||||
ps --> fc[FilterChips]
|
||||
ps --> st[ResultStatus]
|
||||
ps --> sk[PackageSkeletons]
|
||||
ps --> er[PackagesError]
|
||||
ps --> em[PackagesEmpty]
|
||||
ps --> pl[PackageList]
|
||||
pl --> sr[SwipeRow]
|
||||
pl --> pc[PackageCard]
|
||||
sr --> dt[SwipeDots]
|
||||
ps --> bn[PackageBanner]
|
||||
ps -.uses.-> q[usePackagesQuery]
|
||||
ps -.uses.-> f[usePackageFilter]
|
||||
sr -.uses.-> sw[useSwipeRow]
|
||||
pc -.uses.-> pre[useContactPreselect]
|
||||
bn -.uses.-> pre
|
||||
classDef page fill:#2196F3,stroke:#0d47a1,color:#000;
|
||||
classDef ui fill:#4CAF50,stroke:#2e7d32,color:#000;
|
||||
classDef hook fill:#9C27B0,stroke:#4a148c,color:#000;
|
||||
class pg,ps page;
|
||||
class hd,fc,st,sk,er,em,pl,sr,dt,pc,bn ui;
|
||||
class q,f,sw,pre hook;
|
||||
```
|
||||
|
||||
Text alternative: the packages section shows a heading, optional filter chips, a status line, then skeletons, an error, an empty note or the package list (grid or swipe row with dots) and an optional banner; hooks provide data, filtering, swipe state and the contact preselect.
|
||||
|
||||
## Components
|
||||
| Component | Props / state |
|
||||
|---|---|
|
||||
| `PackagesSection` | none; data from `usePackagesQuery`, settings from `content.ts`; renders `#pakketten` as `<section aria-labelledby>` on `bg-surface` (alt colour) |
|
||||
| `FilterChips` | `chips`, `activeId`, `onSelect`; `role="group" aria-label="Filter pakketten"`; square chips, active = ink background |
|
||||
| `ResultStatus` | `label`; `aria-live="polite"` |
|
||||
| `PackageList` | `packages`, `featuredIndex`; grid on `sm+`, `SwipeRow` below (same cards rendered once, layout switched by CSS: `flex snap-x` below `sm`, `grid` above) |
|
||||
| `SwipeDots` | `count`, `activeIndex`, `titles`, `onSelect`; `sm:hidden` |
|
||||
| `PackageCard` | `pkg`; featured styling; CTA link `#contact` with `onClick` select + scroll; `data-testid=package-card-{id}` |
|
||||
| `PackageBanner` | `pkg` or fallback; black block; CTA like the card |
|
||||
| `PackageSkeletons`, `PackagesError` (retry), `PackagesEmpty` | as BR-U3-10 |
|
||||
|
||||
## User interaction flows
|
||||
- Chip click → filter, row resets, status line announces the new count.
|
||||
- Swipe/scroll → active dot follows; dot click → smooth scroll to the card.
|
||||
- "Kies …" → preselect + scroll to `#contact`.
|
||||
|
||||
## Form validation rules
|
||||
None.
|
||||
|
||||
## API integration points
|
||||
`GET /api/v1/offerings` via the existing `usePackagesQuery` (type gains `category?`).
|
||||
|
||||
## Acceptance tests
|
||||
1. 3 packages, empty `bannerSlugs`: 3 cards, no chips, no banner, Maatwerk is a card.
|
||||
2. 6 packages with 2 categories: chips "Alles (6)", categories with counts; selecting filters; packages without category only under "Alles"; threshold boundary 3 vs 4.
|
||||
3. `bannerSlugs=['maatwerk']`: that package is rendered as the banner, not as a card, and stays visible when a chip is active; fallback banner when the slug does not match.
|
||||
4. Result label singular/plural and announcement on change.
|
||||
5. Swipe row: scroll container has snap classes, group role and label; initial scroll position at the featured card; dots count/labels/`aria-current`; dot click scrolls; scroll updates the active dot (jsdom with mocked offsets); reduced motion → non-smooth.
|
||||
6. CTA sets preselect (`slug`, key increments) and anchors to `#contact`.
|
||||
7. Loading skeletons, error with retry (refetch called), empty state.
|
||||
8. Pure functions table-driven (split, chips, filter, label, initialIndex, activeIndexFromScroll).
|
||||
9. Accessibility: chips `aria-pressed`, cards `h3`, touch target classes, landmark label.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Code Generation Plan — packages-block (U3)
|
||||
|
||||
Single source of truth for U3 Code Generation. Inputs: Functional Design in `construction/packages-block/functional-design/` (BR-U3-1..12), `unit-of-work.md` (U3), requirements FR-7..FR-12 (B part), canvas `PakkettenModern.dc.html`, U1/U2 results.
|
||||
|
||||
## Unit context
|
||||
- **Workspace root** `K:\Development\SlpSoftware\Projects\SlpSoftware`, branch `feature/redesign-modern-timetravel`; modify in place; one commit; no push.
|
||||
- **Dependencies**: U1, U2. **External**: `category` in the public offerings response (CMS-U1, done on the CMS branch, not deployed): the UI works without it (no chips). **Blocks**: U4 (preselect context), U5 (shared logic).
|
||||
- **Not in U3**: contact form (U4), E styling (U5), CMS changes.
|
||||
|
||||
## Files
|
||||
- M `src/features/landing/data/content.ts` (`category?`, `packagesSettings`), `src/features/landing/hooks/usePackagesQuery.ts` (type only), `src/features/landing/components/PackagesSection.tsx`, `PackageCard.tsx`, `PackageCardSkeleton.tsx`, `src/features/landing/__tests__/PackagesSection.test.tsx`
|
||||
- C `src/shared/packages/{packageLogic.ts,usePackageFilter.ts,useSwipeRow.ts}`, `src/shared/contact/ContactPreselectContext.tsx`
|
||||
- C `src/features/landing/components/{FilterChips,PackageList,SwipeDots,PackageBanner,PackagesStates}.tsx`
|
||||
- C tests: `src/shared/packages/__tests__/{packageLogic.test.ts,useSwipeRow.test.tsx}`, `src/features/landing/__tests__/PackagesBlock.test.tsx`
|
||||
- Docs: `construction/packages-block/code/summary.md`
|
||||
|
||||
## Steps
|
||||
- [x] **Step 1 — Pure logic** (`packageLogic.ts`): `splitPackages`, `deriveChips`, `filterCards`, `resultLabel`, `initialIndex`, `activeIndexFromScroll`; types for `Chip`, `PackagesSettings`. Table-driven tests incl. boundary 3/4, missing category, unknown banner slug, label singular/plural.
|
||||
- [x] **Step 2 — Content/settings**: `PackageCardData.category?/categoryId?/displayOrder?`; `packagesSettings` (`bannerSlugs: []`, `chipThreshold: 4`, `bannerFallback`); heading text unchanged (live copy).
|
||||
- [x] **Step 3 — Hooks**: `usePackageFilter` (active chip, reset when category disappears), `useSwipeRow` (initial/instant position, rAF-throttled scroll listener, `scrollToIndex` smooth unless reduced motion), `ContactPreselectContext` (provider + `useContactPreselect`, key increments; default no-op outside provider so U3 works standalone); provider mounted in `RootLayout`.
|
||||
- [x] **Step 4 — Components**: `FilterChips` (buttons, `aria-pressed`, group label), `PackageList` (one render path: `flex snap-x snap-mandatory overflow-x-auto` below `sm`, `grid` 3/2 columns from `sm`; scroll container `tabIndex=0 role=group aria-label=Pakketten`), `SwipeDots` (buttons with labels, `aria-current`, hidden at 1 card and on `sm+`), `PackageCard` restyled to B (square, white/dark card, featured brand block with "Meest gekozen" badge, price in wide Archivo, feature list with squares, CTA ink button / white on featured; CTA sets preselect + scrolls), `PackageBanner` (black block), `PackagesStates` (skeletons incl. swipe row, error with retry, empty), `PackagesSection` rewritten (alt background, heading, intro, chips, status line, list, banner).
|
||||
- [x] **Step 5 — Tests**: the nine acceptance tests of `frontend-components.md` (3 vs 6 packages, categories, banner via settings and fallback, label/announcement, swipe row roles/classes/initial position/dots/scroll sync with mocked layout, CTA preselect, loading/error-retry/empty, pure functions, accessibility attributes); update `PackagesSection.test.tsx` for the new markup.
|
||||
- [x] **Step 6 — Build and test (automatic, Step 13.5)**: `pnpm lint`, `pnpm test`, `pnpm build`; fix until green; report real counts.
|
||||
- [x] **Step 7 — Docs and commit**: `construction/packages-block/code/summary.md` (files, behaviour, settings, how a site enables the banner, hand-offs for U4/U5, CMS note: `category` shows once the CMS-U1 API is deployed); one commit (Dutch message, `Co-Authored-By`), no push.
|
||||
|
||||
## Explicitly NOT touched
|
||||
Contact section/form, nav/hero/about/process (U2), theme code (U1), `src/variants/e`, CMS repos.
|
||||
|
||||
## Risks
|
||||
- jsdom has no layout: swipe sync tests mock `offsetLeft`/`clientWidth`/`scrollLeft`; real scroll feel needs a browser check by the user.
|
||||
- Until the CMS API is deployed the live API has no `category`: chips stay hidden (by design).
|
||||
- The mock data of 6 packages in tests uses the categories Websites and Onderhoud.
|
||||
|
||||
## Traceability
|
||||
FR-7..FR-12 (B), NFR-1, NFR-2; BR-U3-1..12; Security Baseline: no new external requests, no `dangerouslySetInnerHTML`, plain-text rendering of API strings.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# Functional Design Questions — packages-block (U3)
|
||||
|
||||
Asked interactively in chat (2026-11-10); the answer is copied here.
|
||||
|
||||
## Question 1 — Maatwerk as card or as banner
|
||||
- A) Banner from 4 packages on (the `maatwerk` package becomes the banner)
|
||||
- B) Always a banner
|
||||
- C) Maatwerk stays a card, no banner
|
||||
- X) Other
|
||||
|
||||
[Answer]: X — Both presentations must be possible. SLP Software starts with "op maat" as a normal package (card); the banner variant may be useful for Andrea Slop Fotografie. Resolved as a per-site choice (see business rule BR-U3-6).
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# Functional Design Plan — packages-block (U3)
|
||||
|
||||
- [x] Analyze unit context (unit-of-work.md U3, requirements FR-7..FR-12, contract § 7, canvas `PakkettenModern.dc.html`, current `PackagesSection`)
|
||||
- [x] Resolve design questions (`packages-block-fd-questions.md`)
|
||||
- [x] Generate `business-logic-model.md`
|
||||
- [x] Generate `business-rules.md`
|
||||
- [x] Generate `domain-entities.md`
|
||||
- [x] Generate `frontend-components.md`
|
||||
- [x] Validate against requirements and the U1/U2 results
|
||||
@@ -5,6 +5,7 @@ import { VariantRenderer } from './VariantRenderer';
|
||||
import { TransitionOverlay } from './TransitionOverlay';
|
||||
import { LiveRegion } from './LiveRegion';
|
||||
import { VariantAlert } from './VariantAlert';
|
||||
import { ContactPreselectProvider } from '../../shared/contact/ContactPreselectProvider';
|
||||
import { UmamiAnalytics } from '../shared/UmamiAnalytics';
|
||||
import { SentryTestButton } from '../shared/SentryTestButton';
|
||||
|
||||
@@ -12,19 +13,21 @@ export function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="font-sans min-h-screen bg-bg text-[17px] leading-[1.55] text-text">
|
||||
<UmamiAnalytics />
|
||||
<VariantRenderer
|
||||
b={
|
||||
<>
|
||||
<header>
|
||||
<Nav />
|
||||
</header>
|
||||
<main id="main" tabIndex={-1} className="outline-none">
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<ContactPreselectProvider>
|
||||
<VariantRenderer
|
||||
b={
|
||||
<>
|
||||
<header>
|
||||
<Nav />
|
||||
</header>
|
||||
<main id="main" tabIndex={-1} className="outline-none">
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</ContactPreselectProvider>
|
||||
<TransitionOverlay />
|
||||
<LiveRegion />
|
||||
<VariantAlert />
|
||||
|
||||
@@ -1,96 +1,339 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { PackagesSection } from '../components/PackagesSection';
|
||||
import { packages } from '../data/content';
|
||||
import { packages, packagesSettings, type PackageCardData } from '../data/content';
|
||||
import { ContactPreselectProvider } from '../../../shared/contact/ContactPreselectProvider';
|
||||
import { useContactPreselect } from '../../../shared/contact/useContactPreselect';
|
||||
import { clearMatchMedia, mockMatchMedia } from '../../../test/matchMedia';
|
||||
import { REDUCED_MOTION_QUERY } from '../../../shared/hooks/usePrefersReducedMotion';
|
||||
|
||||
function renderWithQueryClient() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
function PreselectProbe() {
|
||||
const { subject, key } = useContactPreselect();
|
||||
return <span data-testid="preselect">{`${subject ?? '-'}:${key}`}</span>;
|
||||
}
|
||||
|
||||
function renderSection() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PackagesSection />
|
||||
<ContactPreselectProvider>
|
||||
<PackagesSection />
|
||||
<PreselectProbe />
|
||||
<div id="contact" />
|
||||
</ContactPreselectProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function mockFetchOnce(response: Response) {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(response),
|
||||
function mockApi(data: unknown, init: ResponseInit = { status: 200 }) {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(data), init)));
|
||||
}
|
||||
|
||||
function pkg(slug: string, extra: Partial<PackageCardData> = {}): PackageCardData {
|
||||
return {
|
||||
id: `id_${slug}`,
|
||||
slug,
|
||||
title: `Titel ${slug}`,
|
||||
description: `Omschrijving ${slug}`,
|
||||
price: '€ 100',
|
||||
priceNote: 'eenmalig',
|
||||
features: ['een', 'twee'],
|
||||
ctaLabel: `Kies ${slug}`,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
const six: PackageCardData[] = [
|
||||
pkg('landing', { category: 'Websites' }),
|
||||
pkg('website', { category: 'Websites', featured: true }),
|
||||
pkg('webshop', { category: 'Websites' }),
|
||||
pkg('onderhoud', { category: 'Onderhoud' }),
|
||||
pkg('hosting', { category: 'Onderhoud' }),
|
||||
pkg('zonder'),
|
||||
];
|
||||
|
||||
async function loaded() {
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('package-card-skeleton')).not.toBeInTheDocument(),
|
||||
);
|
||||
}
|
||||
|
||||
describe('PackagesSection', () => {
|
||||
beforeEach(() => {
|
||||
// Force a deterministic relative URL regardless of the developer's local
|
||||
// .env.local (VITE_API_BASE_URL is only meant to override this outside tests).
|
||||
vi.stubEnv('VITE_API_BASE_URL', '');
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
clearMatchMedia();
|
||||
packagesSettings.bannerSlugs = [];
|
||||
});
|
||||
|
||||
it('fetches packages from /api/v1/offerings and renders one PackageCard per package', async () => {
|
||||
mockFetchOnce(new Response(JSON.stringify(packages), { status: 200 }));
|
||||
describe('with the three live packages', () => {
|
||||
it('fetches /api/v1/offerings and renders one card per package, no chips, no banner', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
|
||||
renderWithQueryClient();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('package-card-skeleton')).not.toBeInTheDocument();
|
||||
expect(fetch).toHaveBeenCalledWith('/api/v1/offerings');
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(packages.length);
|
||||
for (const p of packages) {
|
||||
expect(screen.getByTestId(`package-card-${p.id}`)).toBeInTheDocument();
|
||||
}
|
||||
expect(screen.queryByRole('group', { name: 'Filter pakketten' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('package-banner')).not.toBeInTheDocument();
|
||||
// Maatwerk is a normal card at SLP Software.
|
||||
expect(screen.getByTestId('package-card-pakket_03')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent(
|
||||
'Drie manieren om te starten',
|
||||
);
|
||||
expect(screen.getByTestId('packages-status')).toHaveTextContent(
|
||||
'3 pakketten met vaste prijs',
|
||||
);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/v1/offerings');
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(packages.length);
|
||||
for (const pkg of packages) {
|
||||
expect(screen.getByTestId(`package-card-${pkg.id}`)).toBeInTheDocument();
|
||||
expect(screen.getByText(pkg.title)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('marks the featured package as "Meest gekozen"', async () => {
|
||||
mockFetchOnce(new Response(JSON.stringify(packages), { status: 200 }));
|
||||
|
||||
renderWithQueryClient();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Meest gekozen')).toBeInTheDocument();
|
||||
it('marks the featured package as "Meest gekozen"', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
expect(await screen.findByText('Meest gekozen')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows skeleton placeholders while the request is in flight, reserving the grid space', async () => {
|
||||
let resolveFetch: (response: Response) => void;
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockReturnValue(
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
describe('states (BR-U3-10)', () => {
|
||||
it('shows three skeletons while loading and reserves the same container', async () => {
|
||||
let resolveFetch: (r: Response) => void;
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockReturnValue(new Promise<Response>((resolve) => (resolveFetch = resolve))),
|
||||
);
|
||||
renderSection();
|
||||
expect(screen.getAllByTestId('package-card-skeleton')).toHaveLength(3);
|
||||
expect(screen.queryByTestId('packages-status')).not.toBeInTheDocument();
|
||||
resolveFetch!(new Response(JSON.stringify(packages), { status: 200 }));
|
||||
await loaded();
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(3);
|
||||
});
|
||||
|
||||
it('shows an error with a retry button that refetches', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 500 }))
|
||||
.mockResolvedValue(new Response(JSON.stringify(packages), { status: 200 })),
|
||||
);
|
||||
renderSection();
|
||||
expect(await screen.findByTestId('packages-error')).toHaveTextContent(
|
||||
'Pakketten konden niet worden geladen.',
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('packages-retry'));
|
||||
await waitFor(() => expect(screen.getByTestId('package-card-pakket_01')).toBeInTheDocument());
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('shows a short note when there are no packages', async () => {
|
||||
mockApi([]);
|
||||
renderSection();
|
||||
expect(await screen.findByTestId('packages-empty')).toHaveTextContent(
|
||||
'Binnenkort meer informatie.',
|
||||
);
|
||||
expect(screen.queryByTestId('packages-grid')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('six packages with categories', () => {
|
||||
it('shows chips with counts, filters on click and announces the count', async () => {
|
||||
mockApi(six);
|
||||
renderSection();
|
||||
await loaded();
|
||||
|
||||
const group = screen.getByRole('group', { name: 'Filter pakketten' });
|
||||
const chips = within(group).getAllByRole('button');
|
||||
expect(chips.map((c) => c.textContent)).toEqual(['Alles6', 'Websites3', 'Onderhoud2']);
|
||||
expect(chips[0]).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('Manieren om te starten');
|
||||
expect(screen.getByTestId('packages-status')).toHaveTextContent(
|
||||
'6 pakketten met vaste prijs',
|
||||
);
|
||||
|
||||
fireEvent.click(chips[2]);
|
||||
expect(chips[2]).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(chips[0]).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(2);
|
||||
expect(screen.getByTestId('packages-status')).toHaveTextContent(
|
||||
'2 pakketten met vaste prijs',
|
||||
);
|
||||
expect(screen.queryByTestId('package-card-id_landing')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('package-card-id_hosting')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(chips[0]);
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(6);
|
||||
});
|
||||
|
||||
it('has no chips with three card packages even when they have categories', async () => {
|
||||
mockApi(six.slice(0, 3));
|
||||
renderSection();
|
||||
await loaded();
|
||||
expect(screen.queryByRole('group', { name: 'Filter pakketten' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('banner (BR-U3-6)', () => {
|
||||
it('renders the listed slug as the banner instead of a card and keeps it for every chip', async () => {
|
||||
packagesSettings.bannerSlugs = ['maatwerk'];
|
||||
mockApi([
|
||||
...six,
|
||||
pkg('maatwerk', {
|
||||
description: 'Op maat gemaakt',
|
||||
price: 'Op maat',
|
||||
priceNote: 'offerte na intake',
|
||||
ctaLabel: 'Vraag offerte aan',
|
||||
}),
|
||||
),
|
||||
);
|
||||
]);
|
||||
renderSection();
|
||||
await loaded();
|
||||
|
||||
renderWithQueryClient();
|
||||
const banner = screen.getByTestId('package-banner');
|
||||
expect(banner).toHaveTextContent('Past er niets bij?');
|
||||
expect(banner).toHaveTextContent('Op maat gemaakt');
|
||||
expect(banner).toHaveTextContent('Vraag offerte aan');
|
||||
expect(screen.queryByTestId('package-card-id_maatwerk')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('packages-status')).toHaveTextContent(', plus maatwerk');
|
||||
|
||||
expect(screen.getAllByTestId('package-card-skeleton')).toHaveLength(packages.length);
|
||||
|
||||
resolveFetch!(new Response(JSON.stringify(packages), { status: 200 }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('package-card-skeleton')).toHaveLength(0);
|
||||
fireEvent.click(screen.getByTestId('package-chip-cat:Onderhoud'));
|
||||
expect(screen.getByTestId('package-banner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses the fallback texts when no package matches the configured slug', async () => {
|
||||
packagesSettings.bannerSlugs = ['maatwerk'];
|
||||
mockApi(packages.filter((p) => p.slug !== 'maatwerk'));
|
||||
renderSection();
|
||||
await loaded();
|
||||
expect(screen.getByTestId('package-banner')).toHaveTextContent(
|
||||
packagesSettings.bannerFallback.text,
|
||||
);
|
||||
});
|
||||
|
||||
it('banner button preselects the package and jumps to the contact block', async () => {
|
||||
packagesSettings.bannerSlugs = ['maatwerk'];
|
||||
mockApi([...packages.slice(0, 2), pkg('maatwerk')]);
|
||||
renderSection();
|
||||
await loaded();
|
||||
fireEvent.click(screen.getByTestId('package-banner-cta'));
|
||||
expect(screen.getByTestId('preselect')).toHaveTextContent('maatwerk:1');
|
||||
});
|
||||
expect(screen.getByTestId('packages-grid').children.length).toBe(packages.length);
|
||||
});
|
||||
|
||||
it('shows an error message when the API request fails', async () => {
|
||||
mockFetchOnce(new Response(null, { status: 500, statusText: 'Internal Server Error' }));
|
||||
describe('contact preselect (BR-U3-9)', () => {
|
||||
it('sets the slug and increments the key on every click and scrolls to #contact', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const cta = screen.getByTestId('package-cta-pakket_02');
|
||||
expect(cta).toHaveAttribute('href', '#contact');
|
||||
fireEvent.click(cta);
|
||||
expect(screen.getByTestId('preselect')).toHaveTextContent('website:1');
|
||||
fireEvent.click(cta);
|
||||
expect(screen.getByTestId('preselect')).toHaveTextContent('website:2');
|
||||
expect(Element.prototype.scrollIntoView).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
renderWithQueryClient();
|
||||
describe('swipe row (BR-U3-5, 7, 8, 11)', () => {
|
||||
it('is a focusable labelled group with snap classes and cards that peek', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const row = screen.getByRole('group', { name: 'Pakketten' });
|
||||
expect(row).toHaveAttribute('tabindex', '0');
|
||||
expect(row).toHaveClass('snap-x', 'snap-mandatory', 'overflow-x-auto', 'sm:grid');
|
||||
expect(row.children[0]).toHaveClass('w-[85%]', 'snap-center');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('packages-error')).toBeInTheDocument();
|
||||
it('offers one labelled dot per card with the featured card active first', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const dots = within(screen.getByTestId('swipe-dots')).getAllByRole('button');
|
||||
expect(dots).toHaveLength(3);
|
||||
expect(dots[1]).toHaveAttribute('aria-label', 'Pakket 2 van 3: Website');
|
||||
expect(dots[1]).toHaveAttribute('aria-current', 'true');
|
||||
expect(dots[0]).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
it('scrolls to a card when its dot is clicked (smooth, or instant under reduced motion)', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const row = screen.getByTestId('packages-grid');
|
||||
const scrollTo = vi.fn();
|
||||
row.scrollTo = scrollTo as unknown as typeof row.scrollTo;
|
||||
fireEvent.click(within(screen.getByTestId('swipe-dots')).getAllByRole('button')[2]);
|
||||
expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'smooth' }));
|
||||
expect(within(screen.getByTestId('swipe-dots')).getAllByRole('button')[2]).toHaveAttribute(
|
||||
'aria-current',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not animate the scroll under reduced motion', async () => {
|
||||
mockMatchMedia({ [REDUCED_MOTION_QUERY]: true });
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const row = screen.getByTestId('packages-grid');
|
||||
const scrollTo = vi.fn();
|
||||
row.scrollTo = scrollTo as unknown as typeof row.scrollTo;
|
||||
fireEvent.click(within(screen.getByTestId('swipe-dots')).getAllByRole('button')[0]);
|
||||
expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'auto' }));
|
||||
});
|
||||
|
||||
it('follows the scroll position with the active dot', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
const row = screen.getByTestId('packages-grid');
|
||||
Object.defineProperty(row, 'clientWidth', { value: 360, configurable: true });
|
||||
Array.from(row.children).forEach((child, i) => {
|
||||
Object.defineProperty(child, 'offsetLeft', { value: 24 + i * 316, configurable: true });
|
||||
Object.defineProperty(child, 'offsetWidth', { value: 300, configurable: true });
|
||||
});
|
||||
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
|
||||
cb(0);
|
||||
return 1;
|
||||
});
|
||||
row.scrollLeft = 632;
|
||||
fireEvent.scroll(row);
|
||||
const dots = within(screen.getByTestId('swipe-dots')).getAllByRole('button');
|
||||
await waitFor(() => expect(dots[2]).toHaveAttribute('aria-current', 'true'));
|
||||
});
|
||||
|
||||
it('hides the dots with a single package', async () => {
|
||||
mockApi([packages[0]]);
|
||||
renderSection();
|
||||
await loaded();
|
||||
expect(screen.queryByTestId('swipe-dots')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('accessibility (BR-U3-11)', () => {
|
||||
it('labels the section by its heading and renders each package as an article with an h3', async () => {
|
||||
mockApi(packages);
|
||||
renderSection();
|
||||
await loaded();
|
||||
expect(screen.getByRole('region', { name: /manieren om te starten/i })).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('article')).toHaveLength(3);
|
||||
expect(screen.getAllByRole('heading', { level: 3 })).toHaveLength(3);
|
||||
expect(screen.getByTestId('packages-status')).toHaveAttribute('aria-live', 'polite');
|
||||
});
|
||||
|
||||
it('gives chips a 44px touch target', async () => {
|
||||
mockApi(six);
|
||||
renderSection();
|
||||
await loaded();
|
||||
expect(screen.getByTestId('package-chip-all')).toHaveClass('min-h-[44px]');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Chip } from '../../../shared/packages/packageLogic';
|
||||
|
||||
interface FilterChipsProps {
|
||||
chips: Chip[];
|
||||
activeId: string;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
/** Square filter chips of design B (BR-U3-3, BR-U3-11). */
|
||||
export function FilterChips({ chips, activeId, onSelect }: FilterChipsProps) {
|
||||
return (
|
||||
<div role="group" aria-label="Filter pakketten" className="flex flex-wrap gap-2">
|
||||
{chips.map((chip) => {
|
||||
const active = chip.id === activeId;
|
||||
return (
|
||||
<button
|
||||
key={chip.id}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() => onSelect(chip.id)}
|
||||
data-testid={`package-chip-${chip.id}`}
|
||||
className={`min-h-[44px] border-2 border-text px-5 text-[15px] font-bold ${
|
||||
active ? 'bg-text text-bg' : 'bg-transparent text-text'
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
<span className="ml-2 font-medium opacity-80">{chip.count}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { PackageCardData, PackagesSettings } from '../data/content';
|
||||
import { handleAnchorClick } from '../../../utils/scrollToHash';
|
||||
import { useContactPreselect } from '../../../shared/contact/useContactPreselect';
|
||||
|
||||
interface PackageBannerProps {
|
||||
/** The package shown as banner, or undefined to use the fallback texts. */
|
||||
pkg?: PackageCardData;
|
||||
settings: PackagesSettings;
|
||||
}
|
||||
|
||||
/** Black "Past er niets bij?" banner under the cards (BR-U3-6). */
|
||||
export function PackageBanner({ pkg, settings }: PackageBannerProps) {
|
||||
const { select } = useContactPreselect();
|
||||
const text = pkg?.description ?? settings.bannerFallback.text;
|
||||
const price = pkg?.price ?? settings.bannerFallback.priceLabel;
|
||||
const note = pkg?.priceNote ?? settings.bannerFallback.priceNote;
|
||||
const cta = pkg?.ctaLabel ?? settings.bannerFallback.ctaLabel;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="mt-4 flex flex-wrap items-center justify-between gap-x-14 gap-y-8 bg-inv p-[clamp(28px,4vw,48px)] text-white"
|
||||
data-testid="package-banner"
|
||||
>
|
||||
<div className="flex-[1_1_340px]">
|
||||
<h3 className="mb-2.5 text-[clamp(30px,3.4vw,44px)] font-extrabold leading-none tracking-[-0.02em] [font-stretch:112%]">
|
||||
{settings.bannerTitle}
|
||||
</h3>
|
||||
<p className="max-w-[52ch] text-[#cfcac5]">{text}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-8 gap-y-5">
|
||||
<div>
|
||||
<div className="text-4xl font-extrabold leading-none tracking-[-0.02em] [font-stretch:125%]">
|
||||
{price}
|
||||
</div>
|
||||
<div className="mt-1.5 text-sm text-[#b9b3ae]">{note}</div>
|
||||
</div>
|
||||
<a
|
||||
href="#contact"
|
||||
onClick={(event) => {
|
||||
if (pkg) {
|
||||
select(pkg.slug);
|
||||
}
|
||||
handleAnchorClick(event, '#contact');
|
||||
}}
|
||||
className="bg-white px-[26px] py-[17px] text-base font-bold text-[#0e0d0d] no-underline hover:opacity-90"
|
||||
data-testid="package-banner-cta"
|
||||
>
|
||||
{cta}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,49 +1,63 @@
|
||||
import type { PackageCardData } from '../data/content';
|
||||
import { handleAnchorClick } from '../../../utils/scrollToHash';
|
||||
import { useContactPreselect } from '../../../shared/contact/useContactPreselect';
|
||||
|
||||
/** Package card of design B: flat block, featured package in the brand colour with a badge. */
|
||||
export function PackageCard({ pkg }: { pkg: PackageCardData }) {
|
||||
const { select } = useContactPreselect();
|
||||
const featured = Boolean(pkg.featured);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`relative flex flex-col rounded border p-8 transition-all hover:-translate-y-1 ${
|
||||
pkg.featured
|
||||
? 'border-accent-line bg-surface-2'
|
||||
: 'border-line bg-surface hover:border-accent-line'
|
||||
<article
|
||||
className={`relative flex h-full flex-col px-9 pb-9 pt-10 ${
|
||||
featured ? 'bg-brand text-on-brand' : 'bg-surface-2 text-text'
|
||||
}`}
|
||||
data-testid={`package-card-${pkg.id}`}
|
||||
>
|
||||
{pkg.featured && (
|
||||
<span className="font-mono absolute -top-3 left-7 rounded-full bg-accent px-3 py-1 text-[0.7rem] font-bold uppercase tracking-wide text-[var(--color-accent-contrast)]">
|
||||
{featured && (
|
||||
<span className="absolute right-0 top-0 bg-[#0e0d0d] px-3.5 py-2 text-[13px] font-bold text-white">
|
||||
Meest gekozen
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono mb-3.5 text-[0.78rem] text-accent">{pkg.slug}</span>
|
||||
<h3 className="mb-2.5 text-xl font-bold">{pkg.title}</h3>
|
||||
<p className="mb-6 text-[0.95rem] text-muted">{pkg.description}</p>
|
||||
<div className="font-mono mb-1 text-3xl font-bold">
|
||||
<h3 className="mb-2.5 text-[30px] font-extrabold leading-[1.05] tracking-[-0.02em] [font-stretch:112%]">
|
||||
{pkg.title}
|
||||
</h3>
|
||||
<p className={`mb-9 text-base ${featured ? 'text-on-brand' : 'text-muted'}`}>
|
||||
{pkg.description}
|
||||
</p>
|
||||
<div className="text-[clamp(40px,4vw,54px)] font-extrabold leading-none tracking-[-0.03em] [font-stretch:125%]">
|
||||
{pkg.price}
|
||||
<small className="mt-0.5 block text-[0.78rem] font-normal text-muted">{pkg.priceNote}</small>
|
||||
</div>
|
||||
<ul className="my-6 flex-1 list-none">
|
||||
<div className={`mt-2 text-sm ${featured ? 'text-on-brand' : 'text-muted'}`}>
|
||||
{pkg.priceNote}
|
||||
</div>
|
||||
<ul className="my-8 flex-1 list-none p-0 text-[15px]">
|
||||
{pkg.features.map((feature) => (
|
||||
<li key={feature} className="relative mb-2.5 pl-6 text-[0.93rem] text-muted">
|
||||
<span className="font-mono absolute left-0 text-accent" aria-hidden="true">
|
||||
→
|
||||
</span>
|
||||
{feature}
|
||||
<li
|
||||
key={feature}
|
||||
className={`flex gap-3 border-t py-[9px] ${featured ? 'border-white/30' : 'border-line'}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`mt-[9px] h-[7px] w-[7px] flex-none ${featured ? 'bg-white' : 'bg-accent'}`}
|
||||
/>
|
||||
<span>{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<a
|
||||
href="#contact"
|
||||
onClick={(event) => handleAnchorClick(event, '#contact')}
|
||||
className={`rounded-lg px-6 py-3.5 text-center text-[0.98rem] font-semibold ${
|
||||
pkg.featured
|
||||
? 'bg-accent text-[var(--color-accent-contrast)] hover:bg-[var(--color-accent-hover)]'
|
||||
: 'border border-line text-text hover:border-accent-line'
|
||||
onClick={(event) => {
|
||||
select(pkg.slug);
|
||||
handleAnchorClick(event, '#contact');
|
||||
}}
|
||||
className={`block px-5 py-4 text-center text-base font-bold no-underline hover:opacity-90 ${
|
||||
featured ? 'bg-white text-[#0e0d0d]' : 'bg-text text-bg'
|
||||
}`}
|
||||
data-testid={`package-cta-${pkg.id}`}
|
||||
>
|
||||
{pkg.ctaLabel}
|
||||
</a>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
// Mirrors PackageCard's structure/spacing 1-to-1 so the grid doesn't reflow once
|
||||
// real data arrives — only the content becomes pulsing placeholder blocks.
|
||||
// Mirrors PackageCard's structure/spacing so the layout doesn't reflow once real data arrives;
|
||||
// only the content becomes pulsing placeholder blocks.
|
||||
export function PackageCardSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className="flex animate-pulse flex-col rounded border border-line bg-surface p-8"
|
||||
className="flex h-full animate-pulse flex-col bg-surface-2 px-9 pb-9 pt-10"
|
||||
data-testid="package-card-skeleton"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<div className="mb-3.5 h-[0.78rem] w-16 rounded bg-line" />
|
||||
<div className="mb-2.5 h-6 w-3/4 rounded bg-line" />
|
||||
<div className="mb-6 space-y-2">
|
||||
<div className="h-4 w-full rounded bg-line" />
|
||||
<div className="h-4 w-2/3 rounded bg-line" />
|
||||
<div className="mb-2.5 h-8 w-3/4 bg-line" />
|
||||
<div className="mb-9 space-y-2">
|
||||
<div className="h-4 w-full bg-line" />
|
||||
<div className="h-4 w-2/3 bg-line" />
|
||||
</div>
|
||||
<div className="mb-1 h-8 w-24 rounded bg-line" />
|
||||
<div className="mb-6 h-[0.78rem] w-28 rounded bg-line" />
|
||||
<ul className="my-6 flex-1 list-none space-y-2.5">
|
||||
<div className="h-12 w-32 bg-line" />
|
||||
<div className="mt-2 h-3.5 w-28 bg-line" />
|
||||
<ul className="my-8 flex-1 list-none space-y-3 p-0">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<li key={i} className="h-4 w-full rounded bg-line" />
|
||||
<li key={i} className="h-4 w-full bg-line" />
|
||||
))}
|
||||
</ul>
|
||||
<div className="h-[3.4rem] w-full rounded-lg bg-line" />
|
||||
<div className="h-[52px] w-full bg-line" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { PackageCardData } from '../data/content';
|
||||
import { initialIndex } from '../../../shared/packages/packageLogic';
|
||||
import { useSwipeRow } from '../../../shared/packages/useSwipeRow';
|
||||
import { PackageCard } from './PackageCard';
|
||||
import { PackageCardSkeleton } from './PackageCardSkeleton';
|
||||
import { SwipeDots } from './SwipeDots';
|
||||
|
||||
const SKELETON_COUNT = 3;
|
||||
|
||||
interface PackageListProps {
|
||||
packages: PackageCardData[];
|
||||
loading?: boolean;
|
||||
/** Changes when the filter changes so the swipe row returns to its start position. */
|
||||
resetKey: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One render path for all sizes (BR-U3-5): below `sm` a horizontal scroll-snap row with
|
||||
* peeking cards and dots, from `sm` a grid (2 columns, 3 above 1000px).
|
||||
*/
|
||||
export function PackageList({ packages, loading = false, resetKey }: PackageListProps) {
|
||||
const items: ReactNode[] = loading
|
||||
? Array.from({ length: SKELETON_COUNT }, (_, i) => <PackageCardSkeleton key={i} />)
|
||||
: packages.map((pkg) => <PackageCard key={pkg.id} pkg={pkg} />);
|
||||
const { ref, activeIndex, scrollToIndex } = useSwipeRow(
|
||||
items.length,
|
||||
loading ? 0 : initialIndex(packages),
|
||||
resetKey,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={ref}
|
||||
role="group"
|
||||
aria-label="Pakketten"
|
||||
tabIndex={0}
|
||||
data-testid="packages-grid"
|
||||
className="-mx-6 flex snap-x snap-mandatory items-stretch gap-4 overflow-x-auto px-6 pb-2 sm:mx-0 sm:grid sm:snap-none sm:grid-cols-2 sm:overflow-visible sm:px-0 sm:pb-0 min-[1001px]:grid-cols-3"
|
||||
>
|
||||
{items.map((item, index) => (
|
||||
<div key={index} className="w-[85%] flex-none snap-center sm:w-auto">
|
||||
{item}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{!loading && (
|
||||
<SwipeDots
|
||||
titles={packages.map((pkg) => pkg.title)}
|
||||
activeIndex={activeIndex}
|
||||
onSelect={scrollToIndex}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +1,87 @@
|
||||
import { packagesSettings } from '../data/content';
|
||||
import { usePackagesQuery } from '../hooks/usePackagesQuery';
|
||||
import { PackageCard } from './PackageCard';
|
||||
import { PackageCardSkeleton } from './PackageCardSkeleton';
|
||||
import { usePackageFilter } from '../../../shared/packages/usePackageFilter';
|
||||
import { FilterChips } from './FilterChips';
|
||||
import { PackageBanner } from './PackageBanner';
|
||||
import { PackageList } from './PackageList';
|
||||
|
||||
// Matches the fixed number of packages (see content.ts) so the skeleton grid has the
|
||||
// same shape as the loaded grid — no layout shift once the real cards arrive.
|
||||
const SKELETON_COUNT = 3;
|
||||
function headingFor(count: number): string {
|
||||
return count === 3 ? 'Drie manieren om te starten' : 'Manieren om te starten';
|
||||
}
|
||||
|
||||
/**
|
||||
* Packages block of design B: any number of packages, optional filter chips (4+), a swipe row on
|
||||
* mobile and an optional black banner (per-site setting). See Functional Design BR-U3-1..12.
|
||||
*/
|
||||
export function PackagesSection() {
|
||||
const { data: packages, isLoading, isError } = usePackagesQuery();
|
||||
const { data, isLoading, isError, refetch } = usePackagesQuery();
|
||||
const filter = usePackageFilter(data ?? [], packagesSettings);
|
||||
const loaded = !isLoading && !isError && data !== undefined;
|
||||
const banner = filter.hasBanner ? (
|
||||
<PackageBanner pkg={filter.banners[0]} settings={packagesSettings} />
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<section className="bg-gradient-to-b from-transparent via-surface/50 to-transparent py-[88px]">
|
||||
<div className="mx-auto max-w-[1080px] px-6">
|
||||
<div className="mb-[52px]">
|
||||
<span
|
||||
id="pakketten"
|
||||
className="font-mono block scroll-mt-16 text-sm uppercase tracking-wider text-accent"
|
||||
<section id="pakketten" aria-labelledby="pakketten-heading" className="bg-surface">
|
||||
<div className="mx-auto max-w-[1280px] px-6 pb-24 pt-20 sm:px-8 md:pb-[136px] md:pt-32">
|
||||
<div className="mb-12 flex flex-wrap items-end justify-between gap-x-16 gap-y-6 md:mb-[88px]">
|
||||
<h2
|
||||
id="pakketten-heading"
|
||||
className="max-w-[12ch] text-[clamp(40px,5.4vw,80px)] font-extrabold leading-[0.95] tracking-[-0.03em] [font-stretch:112%]"
|
||||
>
|
||||
// pakketten
|
||||
</span>
|
||||
<h2 className="font-display mt-3.5 text-3xl font-bold sm:text-4xl">
|
||||
Drie manieren om te starten
|
||||
{headingFor(loaded ? filter.cards.length : 3)}.
|
||||
</h2>
|
||||
<p className="mt-3 max-w-[56ch] text-muted">
|
||||
<p className="max-w-[40ch] text-body">
|
||||
Van één sterke pagina tot volledig maatwerk met eigen back-end. Elk pakket heeft een
|
||||
vaste scope en een vaste prijs.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-[22px] sm:grid-cols-3" data-testid="packages-grid">
|
||||
{isError ? (
|
||||
<p className="col-span-full text-center text-muted" data-testid="packages-error">
|
||||
Pakketten konden niet worden geladen. Probeer het later opnieuw.
|
||||
|
||||
{isError ? (
|
||||
<div className="text-center" data-testid="packages-error" role="alert">
|
||||
<p className="mb-4 text-muted">Pakketten konden niet worden geladen.</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void refetch()}
|
||||
data-testid="packages-retry"
|
||||
className="min-h-[44px] border-2 border-text px-5 text-[15px] font-bold"
|
||||
>
|
||||
Opnieuw proberen
|
||||
</button>
|
||||
</div>
|
||||
) : loaded && data.length === 0 ? (
|
||||
<div data-testid="packages-empty">
|
||||
<p className="mb-4 text-muted">
|
||||
Binnenkort meer informatie. Neem contact op voor een voorstel.
|
||||
</p>
|
||||
) : isLoading || !packages ? (
|
||||
Array.from({ length: SKELETON_COUNT }, (_, i) => <PackageCardSkeleton key={i} />)
|
||||
) : (
|
||||
packages.map((pkg) => <PackageCard key={pkg.id} pkg={pkg} />)
|
||||
)}
|
||||
</div>
|
||||
{banner}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{loaded && (
|
||||
<div className="mb-8 flex flex-wrap items-center justify-between gap-x-8 gap-y-4">
|
||||
{filter.chips ? (
|
||||
<FilterChips
|
||||
chips={filter.chips}
|
||||
activeId={filter.activeId}
|
||||
onSelect={filter.setActive}
|
||||
/>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<p
|
||||
className="text-[15px] text-muted"
|
||||
aria-live="polite"
|
||||
data-testid="packages-status"
|
||||
>
|
||||
{filter.label}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<PackageList packages={filter.visible} loading={!loaded} resetKey={filter.activeId} />
|
||||
{loaded && banner}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
interface SwipeDotsProps {
|
||||
titles: string[];
|
||||
activeIndex: number;
|
||||
onSelect: (index: number) => void;
|
||||
}
|
||||
|
||||
/** Dot indicator of the mobile swipe row; real buttons with labels (BR-U3-8). */
|
||||
export function SwipeDots({ titles, activeIndex, onSelect }: SwipeDotsProps) {
|
||||
if (titles.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="mt-5 flex justify-center gap-1 sm:hidden" data-testid="swipe-dots">
|
||||
{titles.map((title, index) => {
|
||||
const active = index === activeIndex;
|
||||
return (
|
||||
<button
|
||||
key={`${title}-${index}`}
|
||||
type="button"
|
||||
aria-label={`Pakket ${index + 1} van ${titles.length}: ${title}`}
|
||||
aria-current={active ? 'true' : undefined}
|
||||
onClick={() => onSelect(index)}
|
||||
className="flex h-11 w-8 items-center justify-center"
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`block h-2.5 w-2.5 rounded-full ${active ? 'bg-text' : 'bg-line'}`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -37,6 +37,21 @@ export interface PackageCardData {
|
||||
features: string[];
|
||||
ctaLabel: string;
|
||||
featured?: boolean;
|
||||
/** Category name from the CMS (null/absent = no chip). Additive API field. */
|
||||
category?: string | null;
|
||||
/** Additive API fields, ignored by the UI. */
|
||||
categoryId?: string | null;
|
||||
displayOrder?: number;
|
||||
}
|
||||
|
||||
export interface PackagesSettings {
|
||||
/** Slugs shown as the black banner under the cards instead of as a card (empty = none). */
|
||||
bannerSlugs: string[];
|
||||
/** Filter chips appear from this many card packages on (FR-8). */
|
||||
chipThreshold: number;
|
||||
/** Banner title and the texts used when `bannerSlugs` is set but no package matches. */
|
||||
bannerTitle: string;
|
||||
bannerFallback: { text: string; priceLabel: string; priceNote: string; ctaLabel: string };
|
||||
}
|
||||
|
||||
export interface ProcessStepData {
|
||||
@@ -129,6 +144,19 @@ export const packages: PackageCardData[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/** Per-site packages block settings. SLP Software: Maatwerk stays a normal card (no banner). */
|
||||
export const packagesSettings: PackagesSettings = {
|
||||
bannerSlugs: [],
|
||||
chipThreshold: 4,
|
||||
bannerTitle: 'Past er niets bij?',
|
||||
bannerFallback: {
|
||||
text: 'Grotere websites, een eigen back-end of andere .NET-projecten. Na een intake krijg je een offerte op maat.',
|
||||
priceLabel: 'Op maat',
|
||||
priceNote: 'offerte na intake',
|
||||
ctaLabel: 'Vraag offerte aan',
|
||||
},
|
||||
};
|
||||
|
||||
export const processSteps: ProcessStepData[] = [
|
||||
{
|
||||
label: 'stap 01 — intake',
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ html[data-variant='b'][data-mode='light'] {
|
||||
color-scheme: light;
|
||||
--color-bg: #ffffff;
|
||||
--color-surface: #f1efec;
|
||||
--color-surface-2: #faf8f5;
|
||||
--color-surface-2: #ffffff;
|
||||
--color-line: #e4e0dc;
|
||||
--color-text: #0e0d0d;
|
||||
--color-muted: #5c5753;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ContactPreselectContext, type ContactPreselect } from './contactPreselectContext';
|
||||
|
||||
export function ContactPreselectProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<{ subject: string | null; key: number }>({
|
||||
subject: null,
|
||||
key: 0,
|
||||
});
|
||||
|
||||
const select = useCallback((subject: string) => {
|
||||
setState((current) => ({ subject, key: current.key + 1 }));
|
||||
}, []);
|
||||
|
||||
const value = useMemo<ContactPreselect>(() => ({ ...state, select }), [state, select]);
|
||||
|
||||
return (
|
||||
<ContactPreselectContext.Provider value={value}>{children}</ContactPreselectContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
/**
|
||||
* Hand-over from a package card to the contact form (BR-U3-9): `subject` = package slug,
|
||||
* `key` increases on every click so the same choice can be applied again after the visitor
|
||||
* changed the field.
|
||||
*/
|
||||
export interface ContactPreselect {
|
||||
subject: string | null;
|
||||
key: number;
|
||||
select: (subject: string) => void;
|
||||
}
|
||||
|
||||
export const ContactPreselectContext = createContext<ContactPreselect>({
|
||||
subject: null,
|
||||
key: 0,
|
||||
select: () => {},
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { useContext } from 'react';
|
||||
import { ContactPreselectContext } from './contactPreselectContext';
|
||||
|
||||
export function useContactPreselect() {
|
||||
return useContext(ContactPreselectContext);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { PackageCardData } from '../../../features/landing/data/content';
|
||||
import {
|
||||
ALL_CHIP,
|
||||
activeIndexFromScroll,
|
||||
deriveChips,
|
||||
filterCards,
|
||||
initialIndex,
|
||||
resultLabel,
|
||||
splitPackages,
|
||||
} from '../packageLogic';
|
||||
|
||||
function pkg(slug: string, extra: Partial<PackageCardData> = {}): PackageCardData {
|
||||
return {
|
||||
id: `id_${slug}`,
|
||||
slug,
|
||||
title: slug,
|
||||
description: 'd',
|
||||
price: '€ 1',
|
||||
priceNote: 'n',
|
||||
features: [],
|
||||
ctaLabel: 'c',
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
const six = [
|
||||
pkg('a', { category: 'Websites' }),
|
||||
pkg('b', { category: 'Websites', featured: true }),
|
||||
pkg('c', { category: 'Onderhoud' }),
|
||||
pkg('d', { category: 'Onderhoud' }),
|
||||
pkg('e'),
|
||||
pkg('maatwerk', { category: null }),
|
||||
];
|
||||
|
||||
describe('splitPackages (BR-U3-2)', () => {
|
||||
it('keeps everything as a card by default', () => {
|
||||
const { cards, banners } = splitPackages(six, []);
|
||||
expect(cards).toHaveLength(6);
|
||||
expect(banners).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('moves listed slugs to the banner and keeps the order of the rest', () => {
|
||||
const { cards, banners } = splitPackages(six, ['maatwerk', 'unknown']);
|
||||
expect(banners.map((p) => p.slug)).toEqual(['maatwerk']);
|
||||
expect(cards.map((p) => p.slug)).toEqual(['a', 'b', 'c', 'd', 'e']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deriveChips (BR-U3-3)', () => {
|
||||
it('returns null below the threshold (3 vs 4)', () => {
|
||||
expect(deriveChips(six.slice(0, 3), 4)).toBeNull();
|
||||
expect(deriveChips(six.slice(0, 4), 4)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when no package has a category', () => {
|
||||
expect(deriveChips([pkg('a'), pkg('b'), pkg('c'), pkg('d')], 4)).toBeNull();
|
||||
});
|
||||
|
||||
it('lists Alles first, then categories in order of first appearance with counts', () => {
|
||||
const chips = deriveChips(six, 4)!;
|
||||
expect(chips.map((c) => [c.label, c.count])).toEqual([
|
||||
['Alles', 6],
|
||||
['Websites', 2],
|
||||
['Onderhoud', 2],
|
||||
]);
|
||||
expect(chips[0].id).toBe(ALL_CHIP);
|
||||
});
|
||||
|
||||
it('ignores blank category names', () => {
|
||||
const chips = deriveChips(
|
||||
[pkg('a', { category: ' ' }), pkg('b', { category: 'X' }), pkg('c'), pkg('d')],
|
||||
4,
|
||||
)!;
|
||||
expect(chips.map((c) => c.label)).toEqual(['Alles', 'X']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterCards', () => {
|
||||
it('shows all for Alles and only the category otherwise', () => {
|
||||
expect(filterCards(six, ALL_CHIP)).toHaveLength(6);
|
||||
expect(filterCards(six, 'cat:Websites').map((p) => p.slug)).toEqual(['a', 'b']);
|
||||
expect(filterCards(six, 'cat:Onderhoud').map((p) => p.slug)).toEqual(['c', 'd']);
|
||||
expect(filterCards(six, 'cat:Nope')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resultLabel (BR-U3-4)', () => {
|
||||
it.each([
|
||||
[1, false, '1 pakket met vaste prijs'],
|
||||
[3, false, '3 pakketten met vaste prijs'],
|
||||
[0, false, '0 pakketten met vaste prijs'],
|
||||
[5, true, '5 pakketten met vaste prijs, plus maatwerk'],
|
||||
])('%i packages, banner %s', (count, banner, expected) => {
|
||||
expect(resultLabel(count, banner)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('initialIndex (BR-U3-7)', () => {
|
||||
it('points at the featured card, else at the first', () => {
|
||||
expect(initialIndex(six)).toBe(1);
|
||||
expect(initialIndex([pkg('a'), pkg('b')])).toBe(0);
|
||||
expect(initialIndex([])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('activeIndexFromScroll', () => {
|
||||
const items = [
|
||||
{ offset: 24, width: 300 },
|
||||
{ offset: 340, width: 300 },
|
||||
{ offset: 656, width: 300 },
|
||||
];
|
||||
it.each([
|
||||
[0, 0],
|
||||
[160, 1],
|
||||
[316, 1],
|
||||
[632, 2],
|
||||
])('scrollLeft %i -> card %i (viewport 360)', (scrollLeft, expected) => {
|
||||
expect(activeIndexFromScroll(scrollLeft, 360, items)).toBe(expected);
|
||||
});
|
||||
|
||||
it('is 0 without items', () => {
|
||||
expect(activeIndexFromScroll(100, 360, [])).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { PackageCardData } from '../../features/landing/data/content';
|
||||
|
||||
export const ALL_CHIP = 'all';
|
||||
|
||||
export interface Chip {
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** BR-U3-2: packages whose slug is listed become banner packages, the rest are cards. */
|
||||
export function splitPackages(
|
||||
packages: PackageCardData[],
|
||||
bannerSlugs: string[],
|
||||
): { cards: PackageCardData[]; banners: PackageCardData[] } {
|
||||
const cards: PackageCardData[] = [];
|
||||
const banners: PackageCardData[] = [];
|
||||
for (const pkg of packages) {
|
||||
(bannerSlugs.includes(pkg.slug) ? banners : cards).push(pkg);
|
||||
}
|
||||
return { cards, banners };
|
||||
}
|
||||
|
||||
function categoryOf(pkg: PackageCardData): string | null {
|
||||
const name = pkg.category?.trim();
|
||||
return name ? name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* BR-U3-3: chips only when there are at least `threshold` card packages and at least one
|
||||
* category. "Alles" first, then categories in order of first appearance, with counts.
|
||||
*/
|
||||
export function deriveChips(cards: PackageCardData[], threshold: number): Chip[] | null {
|
||||
if (cards.length < threshold) {
|
||||
return null;
|
||||
}
|
||||
const counts = new Map<string, number>();
|
||||
for (const pkg of cards) {
|
||||
const category = categoryOf(pkg);
|
||||
if (category) {
|
||||
counts.set(category, (counts.get(category) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
if (counts.size === 0) {
|
||||
return null;
|
||||
}
|
||||
return [
|
||||
{ id: ALL_CHIP, label: 'Alles', count: cards.length },
|
||||
...[...counts].map(([name, count]) => ({ id: `cat:${name}`, label: name, count })),
|
||||
];
|
||||
}
|
||||
|
||||
export function filterCards(cards: PackageCardData[], activeId: string): PackageCardData[] {
|
||||
if (activeId === ALL_CHIP) {
|
||||
return cards;
|
||||
}
|
||||
return cards.filter((pkg) => `cat:${categoryOf(pkg)}` === activeId);
|
||||
}
|
||||
|
||||
/** BR-U3-4 */
|
||||
export function resultLabel(count: number, hasBanner: boolean): string {
|
||||
const noun = count === 1 ? 'pakket' : 'pakketten';
|
||||
return `${count} ${noun} met vaste prijs${hasBanner ? ', plus maatwerk' : ''}`;
|
||||
}
|
||||
|
||||
/** BR-U3-7: index of the featured card, else the first one. */
|
||||
export function initialIndex(visible: PackageCardData[]): number {
|
||||
const index = visible.findIndex((pkg) => pkg.featured);
|
||||
return index >= 0 ? index : 0;
|
||||
}
|
||||
|
||||
/** Card whose centre is nearest to the centre of the viewport (cards use snap-center). */
|
||||
export function activeIndexFromScroll(
|
||||
scrollLeft: number,
|
||||
viewportWidth: number,
|
||||
items: { offset: number; width: number }[],
|
||||
): number {
|
||||
if (items.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const viewportCenter = scrollLeft + viewportWidth / 2;
|
||||
let best = 0;
|
||||
let bestDistance = Infinity;
|
||||
items.forEach((item, index) => {
|
||||
const distance = Math.abs(item.offset + item.width / 2 - viewportCenter);
|
||||
if (distance < bestDistance) {
|
||||
best = index;
|
||||
bestDistance = distance;
|
||||
}
|
||||
});
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { PackageCardData, PackagesSettings } from '../../features/landing/data/content';
|
||||
import { ALL_CHIP, deriveChips, filterCards, resultLabel, splitPackages } from './packageLogic';
|
||||
|
||||
/** Splits packages into cards and banner, derives the chips and applies the active chip. */
|
||||
export function usePackageFilter(packages: PackageCardData[], settings: PackagesSettings) {
|
||||
const { cards, banners } = useMemo(
|
||||
() => splitPackages(packages, settings.bannerSlugs),
|
||||
[packages, settings.bannerSlugs],
|
||||
);
|
||||
const chips = useMemo(
|
||||
() => deriveChips(cards, settings.chipThreshold),
|
||||
[cards, settings.chipThreshold],
|
||||
);
|
||||
const [chosenId, setActive] = useState(ALL_CHIP);
|
||||
|
||||
// A chip that no longer exists (data changed) falls back to "Alles".
|
||||
const activeId = chips?.some((chip) => chip.id === chosenId) ? chosenId : ALL_CHIP;
|
||||
const visible = useMemo(() => filterCards(cards, activeId), [cards, activeId]);
|
||||
const hasBanner = banners.length > 0 || settings.bannerSlugs.length > 0;
|
||||
|
||||
return {
|
||||
cards,
|
||||
banners,
|
||||
chips,
|
||||
activeId,
|
||||
setActive,
|
||||
visible,
|
||||
hasBanner,
|
||||
label: resultLabel(visible.length, hasBanner),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { usePrefersReducedMotion } from '../hooks/usePrefersReducedMotion';
|
||||
import { activeIndexFromScroll } from './packageLogic';
|
||||
|
||||
function cardMetrics(container: HTMLElement) {
|
||||
return Array.from(container.children).map((child) => ({
|
||||
offset: (child as HTMLElement).offsetLeft,
|
||||
width: (child as HTMLElement).offsetWidth,
|
||||
}));
|
||||
}
|
||||
|
||||
function scrollLeftFor(container: HTMLElement, index: number): number {
|
||||
const item = container.children[index] as HTMLElement | undefined;
|
||||
if (!item) {
|
||||
return 0;
|
||||
}
|
||||
return item.offsetLeft - (container.clientWidth - item.offsetWidth) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for the mobile swipe row (BR-U3-5, 7, 8). Scrolling itself is plain CSS scroll-snap;
|
||||
* this hook only puts the row on `initialIndex` when it (re)appears, tracks the active card for the
|
||||
* dots and scrolls to a card on request (smooth unless the visitor prefers reduced motion).
|
||||
*/
|
||||
export function useSwipeRow(itemCount: number, initialIndex: number, resetKey: string) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(initialIndex);
|
||||
const reducedMotion = usePrefersReducedMotion();
|
||||
|
||||
const scrollToIndex = useCallback(
|
||||
(index: number) => {
|
||||
const container = ref.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
const left = scrollLeftFor(container, index);
|
||||
if (typeof container.scrollTo === 'function') {
|
||||
container.scrollTo({ left, behavior: reducedMotion ? 'auto' : 'smooth' });
|
||||
} else {
|
||||
container.scrollLeft = left;
|
||||
}
|
||||
setActiveIndex(index);
|
||||
},
|
||||
[reducedMotion],
|
||||
);
|
||||
|
||||
// Start position: featured card (or first) whenever the set of cards changes.
|
||||
useEffect(() => {
|
||||
const container = ref.current;
|
||||
if (container) {
|
||||
container.scrollLeft = scrollLeftFor(container, initialIndex);
|
||||
}
|
||||
setActiveIndex(initialIndex);
|
||||
}, [initialIndex, itemCount, resetKey]);
|
||||
|
||||
// Follow the scroll position for the dots (throttled to animation frames).
|
||||
useEffect(() => {
|
||||
const container = ref.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
let frame = 0;
|
||||
const onScroll = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
setActiveIndex(
|
||||
activeIndexFromScroll(
|
||||
container.scrollLeft,
|
||||
container.clientWidth,
|
||||
cardMetrics(container),
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
container.addEventListener('scroll', onScroll, { passive: true });
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
container.removeEventListener('scroll', onScroll);
|
||||
};
|
||||
}, [itemCount]);
|
||||
|
||||
return { ref, activeIndex, scrollToIndex };
|
||||
}
|
||||
Reference in New Issue
Block a user