Contactformulier: cms-client (validatie, reducer, client, hook), formulier in stijl B en beschikbaarheid

Headless pakket src/cms-client met importgrens, formulier dat pas verschijnt als de API antwoordt
(anders blijft de mailto-knop), honeypot, idempotentie, token-vernieuwing en property-based tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:13:24 +01:00
co-authored by Claude Sonnet 5.5
parent 9661b64635
commit aa843a5675
45 changed files with 2609 additions and 22 deletions
@@ -0,0 +1,43 @@
# Business Logic Model — contact-form (U4)
## Module layout (movable package)
`src/cms-client/` is self-contained (an ESLint `no-restricted-imports` rule forbids imports from outside it):
- `http/` — `apiUrl`, `parseProblem`, `ApiError`.
- `contact/` — `validateContact`, `contactFormReducer` + types, `messages.nl`, `createContactClient` (`getToken`, `submit`), `useContactForm`.
- `index.ts` per subpath (`@/cms-client/contact`, later `/offerings`) so a site imports only what it uses.
## Submission sequence
```mermaid
sequenceDiagram
box rgba(99,179,237,0.4) Browser
participant V as Visitor
participant H as useContactForm
participant C as contact client
end
box rgba(154,230,180,0.4) CMS API
participant A as contact-messages
end
H->>C: get token when section nears viewport
C->>A: GET token
A-->>C: 200 token and minSeconds
V->>H: fill fields and submit
H->>H: validate and honeypot check
H->>C: submit with token and idempotency key
C->>A: POST contact-messages
A-->>C: 202 received
C-->>H: ok
H-->>V: success state
```
Text alternative: the hook obtains a token via the client, validates on submit, posts with the token and an idempotency key and shows the success state after a 202.
## Pure units (unit- and property-tested)
- `validateContact(values) -> errors`: trimming, boundaries 100/254/100/2000 inclusive, control characters, email regex.
- `contactFormReducer(state, event)`: events `change`, `blur`, `submit`, `sending`, `succeeded`, `failed`, `fieldErrors`, `reset`, `preselect`; invariants: `sent` never reverts except `reset`; input kept on `failed`; edits ignored while `sending`.
- `mapApiErrors(problem) -> { fields, token, generic }` and `retryAfterMinutes(headerValue)`.
- Request/response serialization round trips (payload shape, problem+json parsing) — property-based (PBT partial per the extension decision).
## Integration of the pieces
- `ContactSection` (U2 frame) renders `ContactPanel`: availability `unknown/closed` → mailto panel; `open` → `ContactFormView` (B skin) using `useContactForm`.
- Subject options come from `usePackagesQuery` + "Overig"; `useContactPreselect` (U3) drives `preselect`.
- Umami events via the existing analytics component's API (no data), Sentry untouched except documented non-logging.
@@ -0,0 +1,66 @@
# Business Rules — contact-form (U4)
| Id | Rule |
|---|---|
| BR-U4-1 | **Fixed fields**: name, email, subject, message, all required (no builder, no phone, no "aanvraag/vraag" switch). |
| BR-U4-2 | **Progressive enhancement**: the contact panel starts as the mailto call-to-action (as in U2). When the contact section comes near the viewport the client fetches the token (`GET /api/v1/contact-messages/token`). `200` and no captcha → the panel switches to the form; `404`, any other status, network error, or `captcha != null` (no widget implemented in this repo) → the mailto panel stays. There is no build-time flag: the server (host switch + CMS switch) decides. |
| BR-U4-3 | **Token**: one token per page view, fetched once when the section nears the viewport (IntersectionObserver with fallback to the first focus where unavailable); not on page load, not in static HTML. On `errors.token = ["expired"]` one fresh token is fetched and the submit is repeated once automatically; a second failure shows the generic failure message. |
| BR-U4-4 | **Validation** is the same pure function on the client and (by contract) on the server: first failing rule per field wins (required, then length, then format). Errors appear on blur of a touched field or on submit and disappear as soon as the field is valid; on a stopped submit the focus moves to the first invalid field. The form uses `noValidate` and shows its own messages. |
| BR-U4-5 | **States**: `editing → sending → sent | failed`. While `sending`, edits and a second submit are ignored. `sent` never reverts (except an explicit "Nog een bericht sturen" reset). `failed` keeps all input and offers retry; the failure message includes the mail address (assembled after mount, see BR-U4-10). |
| BR-U4-6 | **Idempotency**: one UUID per attempt series, reused when the visitor retries after `failed` until success, renewed after success/reset. Sent as `Idempotency-Key`. |
| BR-U4-7 | **Honeypot**: a visually hidden field (off-screen, `aria-hidden`, `tabindex=-1`, `autocomplete=off`, implausible DOM name) sent as `hpCheck`. If it is filled the client does not call the API but shows the normal success state (silent drop); the server repeats the check. The server-signed token replaces any client time check (no `Date.now` needed). |
| BR-U4-8 | **Responses**: `202` → success state. `400` with `errors` → map codes to messages per field (and `token` as above); unknown codes → generic failure. `413` → "Je bericht is te groot." `429` → message with the minutes from `Retry-After` (rounded up, min 1). `404/5xx/network` → generic failure with the mailto fallback address. No automatic retry other than the token case. |
| BR-U4-9 | **Preselect**: when the contact preselect `key` changes (package CTA from U3), the subject is set to its `subject` if that value exists in the subject options; unknown values are ignored. A later manual choice stays until the next click (key change). |
| BR-U4-10 | **Mailto fallback**: the address is assembled in the browser after mount from `contactInfo` parts, not as a literal in prerendered HTML (the site is a SPA, so this is defence in depth); the existing mailto button and the visible address of the section stay. |
| BR-U4-11 | **Subject options**: the packages from the offerings query (value = `slug`, label = `title`, in API order, banner packages included) plus "Overig" (`other`); first option is a disabled placeholder "Kies een onderwerp". While offerings load or fail, only "Overig" is available. |
| BR-U4-12 | **Privacy**: below the submit button the sentence "Je gegevens gebruik ik alleen om op je bericht te reageren; ik bewaar ze maximaal 12 maanden." (no checkbox, no link). |
| BR-U4-13 | **Success**: the form is replaced by "Bedankt!" with "Je bericht is verstuurd. Je hoort binnen één werkdag van me." (role=status, focus moves to it) and a button "Nog een bericht sturen" that resets to an empty form with a new idempotency key. |
| BR-U4-14 | **Privacy of telemetry**: no field values or the API token/idempotency key are logged, sent to Sentry (breadcrumbs, extra context) or Umami; the only analytics events are `contact-sent` and `contact-failed` without data. Errors reported to Sentry carry no request/response bodies. |
| BR-U4-15 | **Accessibility**: real `<label>`s, errors linked with `aria-describedby` and `aria-invalid`, `role=alert` on the failure message, `role=status` + focus on success, visible focus, touch targets ≥ 44px, no animation dependency, honeypot invisible to assistive technology. |
| BR-U4-16 | **Headless boundary**: all logic (reducer, validation, hook, client) lives in `src/cms-client/` without imports from the app; the B skin (markup/classes) lives in the landing feature. Texts are injectable with Dutch defaults. |
## Decision flow: availability
```mermaid
graph TD
S([Contact section near viewport]) --> T[GET token]
T --> R{Status 200}
R -->|"no"| M[Keep mailto panel]
R -->|"yes"| C{Captcha required}
C -->|"yes"| M
C -->|"no"| F[Show form]
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 R,C decision;
class T,M,F step;
```
Text alternative: when the section nears the viewport the token is requested; only a 200 without captcha shows the form, otherwise the mailto panel stays.
## Decision flow: submit
```mermaid
graph TD
A([Submit]) --> B{Sending already}
B -->|"yes"| X[Ignore]
B -->|"no"| V{Valid}
V -->|"no"| E[Show errors and focus first]
V -->|"yes"| H{Honeypot filled}
H -->|"yes"| OK[Show success without call]
H -->|"no"| P[POST with idempotency key]
P --> S{Result}
S -->|"202"| OK
S -->|"token expired"| T[Fetch token and repeat once]
S -->|"400 fields"| E
S -->|"429 or other"| FL[Failed with message and mailto]
classDef start fill:#CE93D8,stroke:#6A1B9A,color:#000;
classDef decision fill:#FFF59D,stroke:#F57F17,color:#000;
classDef step fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef bad fill:#ffab91,stroke:#bf360c,color:#000;
class A start;
class B,V,H,S decision;
class X,E,P,T,OK step;
class FL bad;
```
Text alternative: a submit is ignored while sending, validated, dropped silently if the honeypot is filled, otherwise posted; success, an expired token (one retry), field errors or a failure result.
@@ -0,0 +1,46 @@
# Domain Entities — contact-form (U4)
```mermaid
graph TD
CF[ContactFields] -->|"validated by"| VAL[validateContact]
VAL -->|"produces"| ERR[FieldErrors code per field]
CF -->|"sent with"| TOK[ContactToken]
CF -->|"sent with"| IDK[Idempotency key]
TOK -->|"from"| API1[GET token]
CF -->|"posted to"| API2[POST contact-messages]
ST[FormState] -->|"holds"| CF
ST -->|"holds"| ERR
ST -->|"status"| STA[editing sending sent failed]
PRE[ContactPreselect] -->|"subject"| CF
AV[Availability] -->|"open closed"| ST
classDef data fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef logic fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef ext fill:#f6e05e,stroke:#c05621,color:#000;
class CF,ERR,ST,STA,PRE,AV data;
class VAL logic;
class TOK,IDK,API1,API2 ext;
```
Text alternative: the fields are validated into per-field error codes; submission needs a server token and an idempotency key and posts to the API; the form state holds fields, errors and status; the package preselect fills the subject; availability decides whether the form is shown at all.
## ContactFields
| Field | Type | Rules (same as the API) |
|---|---|---|
| `name` | string | trimmed, 1–100, no control characters |
| `email` | string | trimmed, 1–254, `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`, no control characters |
| `subject` | string | opaque value from the site's options (package slug or `other`), 1–100 |
| `message` | string | trimmed, 1–2000, control characters rejected except line breaks and tabs |
Payload to the API: the four fields (trimmed) + `hpCheck` (always `""` unless a bot filled the honeypot) + `token` + optional `captchaToken`.
## Error codes and messages
Codes `required | tooLong | invalid | expired`. Messages per field and code (Dutch, equal to the ASF texts where they exist): name required "Vul je naam in.", tooLong "De naam is te lang."; email required "Vul je e-mailadres in.", tooLong "Het e-mailadres is te lang.", invalid "Dit e-mailadres is ongeldig."; subject required "Kies een onderwerp."; message required "Schrijf hier je vraag.", tooLong "Het bericht is te lang.". Other texts: rate limit "Je hebt net al een bericht gestuurd. Probeer het over {minuten} minuten opnieuw.", too large "Je bericht is te groot.", server/network "Versturen lukte niet. Probeer het later nog eens of mail naar {adres}.", token expired is retried silently once.
## FormState
`status: 'editing' | 'sending' | 'sent' | 'failed'`; `values`; `touched` (per field); `errors` (shown); `attemptKey` (Idempotency-Key, one UUID per attempt series; kept on retry, renewed after success or reset).
## Availability
`unknown` (default, shows the mailto panel) → `open` (token received) | `closed` (404 on the token route, network error, captcha required or any other non-200) → mailto panel stays.
## ContactToken
`{ token, minSeconds, captcha: null | { provider, siteKey } }`; fetched lazily as described in BR-U4-3.
@@ -0,0 +1,58 @@
# Frontend Components — contact-form (U4)
## Component hierarchy
```mermaid
graph TD
cs[ContactSection] --> cp[ContactPanel]
cp --> ma[MailtoPanel]
cp --> fv[ContactFormView]
fv --> fld[Field components]
fv --> hp[Honeypot]
fv --> pn[PrivacyNote]
fv --> sm[StatusMessages]
cp -.uses.-> av[useContactAvailability]
fv -.uses.-> uf[useContactForm]
uf -.uses.-> cl[createContactClient]
cp -.uses.-> pre[useContactPreselect]
cp -.uses.-> pq[usePackagesQuery]
cl --> api[(contact-messages API)]
classDef page fill:#2196F3,stroke:#0d47a1,color:#000;
classDef ui fill:#4CAF50,stroke:#2e7d32,color:#000;
classDef hook fill:#9C27B0,stroke:#4a148c,color:#000;
classDef ext fill:#F44336,stroke:#b71c1c,color:#000;
class cs page;
class cp,ma,fv,fld,hp,pn,sm ui;
class av,uf,cl,pre,pq hook;
class api ext;
```
Text alternative: the contact section shows a panel that is either the mailto panel or the form; the form uses the headless hook and client, the preselect context and the offerings for subject options.
## Components and hooks
| Unit | Props / state |
|---|---|
| `ContactPanel` | decides between `MailtoPanel` and `ContactFormView` from `useContactAvailability`; keeps `data-testid="contact-panel"` |
| `MailtoPanel` | the U2 content (mailto button) with address assembled after mount |
| `ContactFormView` | `subjectOptions`, `preselect`, `token source`; renders fields, honeypot, privacy sentence, submit button "Verstuur", status messages; B skin (panel colours, underline inputs on `bg-field`, brand submit button) |
| `useContactAvailability(sectionRef)` | `'unknown' \| 'open' \| 'closed'` plus the token; IntersectionObserver trigger; never fetches during server/test render without observer support (falls back to first focus) |
| `useContactForm(options)` (headless) | per `component-methods.md`: values, errors, status, `getFieldProps`, `honeypot`, `formProps`, `retry`, `reset`, `focusFirstError`; options `idPrefix`, `subjectOptions`, `preselect`, `getToken`, `submit`, `messages`, `fallbackAddress` |
| `createContactClient` | `getToken()`, `submit(payload, ctx)`; injectable `fetch`; uses `apiUrl()` |
## User interaction flows
- Section scrolls near → token → form appears (or stays mailto). Fill → blur errors → submit → success or failure (with retry and mailto address).
- Package CTA → preselect → subject set, scroll to contact.
## Form validation rules
BR-U4-4 (same codes and limits as the API).
## API integration points
`GET /api/v1/contact-messages/token`, `POST /api/v1/contact-messages` (headers `Idempotency-Key`), offerings query for subject options.
## Acceptance tests
1. Validation table and property tests; reducer invariants; serialization round trips (PBT).
2. Availability: 200 → form; 404/500/network/captcha → mailto panel; no fetch before the section nears the viewport.
3. Submit success (202), honeypot silent success without call, 400 field errors mapped, token expired → one refetch and repeat, 413, 429 with minutes, 5xx/network failure keeps input, retry reuses the idempotency key, reset renews it.
4. Preselect fills the subject; unknown value ignored; second click with the same package re-applies.
5. Accessibility: labels, `aria-invalid`/`aria-describedby`, focus on first error, `role=alert`, `role=status` + focus on success, honeypot hidden from AT, 44px targets.
6. No PII in console/Sentry/Umami calls (spy) during a full flow.
7. Boundary: lint rule forbids imports from `src/cms-client` to the app (rule test).