Connects the contact form to the CMS API through the cms-client package
Copies the headless cms-client package (SlpSoftware 93fa729) and builds the form on useContactForm: availability check when the form is in view (no request while switched off), the readable shoot label as subject, the Friendly Captcha widget as its own lazy chunk, trackEvent for contact-sent and contact-failed. Removes the old reducer, validation and submit stub. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+11
-11
@@ -6,17 +6,17 @@ Order matters: steps 1-2 can start with the current package (without captcha); t
|
||||
|
||||
## Steps
|
||||
|
||||
- [ ] **1. Copy the current package**: `src/cms-client/` (http/, contact/, README, tests, boundary test) copied unchanged from `SlpSoftware/src/cms-client` (read only). Add the ESLint `no-restricted-imports` rule for `src/cms-client/**`. Check: boundary test and the package's own tests pass in this repo.
|
||||
- [ ] **2. Client factory**: `src/contact/contactClient.ts` creating `createContactClient` with same-origin base `/api/v1`; no logging of bodies.
|
||||
- [ ] **3. Subject options by label**: `src/lib/shootOptions.ts` returns `{ value: label, label }` plus the id-to-label map for `?pakket=`; test that every content label is 1-100 characters and that `& ' " < >` survive the payload (PBT-02/03).
|
||||
- [ ] **4. ContactAvailability**: new `src/components/ContactForm/ContactAvailability.tsx` with the state machine of the functional design (no request when disabled; IntersectionObserver with the `useInView` hook; first-focus fallback; `idle/checking/open/closed`; token in memory; `refreshToken`). Tests: no request when disabled, one request when in view, 404/429/5xx/network keep the gate, unsupported provider keeps the gate, first-focus fallback.
|
||||
- [ ] **5. ContactPanel + Gate wiring**: Gate stays the initial render; Panel renders Availability inside Gate when `enabled`; Panel remembers the last preselect as `{ subject: label, key }`; placeholder heights unchanged. Tests: prerendered HTML has no token/widget/address; hydration test stays green.
|
||||
- [ ] **6. ContactForm on `useContactForm`**: replace reducer, validation, 3 s check and submit prop; keep Chakra skin, ids, test ids, thank-you and PrivacyNote; error text outside the label; honeypot from `honeypotProps`; failure message from the package with address assembled after hydration (`useEmailAddress`); events `contact-sent`/`contact-failed` through the analytics wrapper. Tests: component tests incl. axe, field errors, focus after render, 429 text, failure path without address in HTML.
|
||||
- [ ] **7. Remove dead code**: `src/lib/contactFormReducer.ts`, `validateContact.ts`, `toContactPayload.ts`, `isLikelySpam`, `src/contact/submitContactForm.ts` and `types.ts` (as far as unused), plus their tests; update `src/test/arbitraries.ts` (form generators) and references.
|
||||
- [ ] **8. Dev proxy and CSP**: `vite.config.ts` `server.proxy` for `/api` (env-configurable, default off in CI); `config/securityHeaders.ts` additions per the infrastructure design (frame-src decided by Bryan; others only after the real-browser test) with reason comments; extend the `securityHeaders` tests.
|
||||
- [ ] **9. Final package** (after SLS-Main's message): replace `src/cms-client/` by the final version (captcha slot, `initialSubject`); re-run boundary and package tests.
|
||||
- [ ] **10. CaptchaWidget**: new lazy chunk `src/components/ContactForm/CaptchaWidget.tsx` using `@friendlycaptcha/sdk` (`createWidget`, `startMode: focus`, `language: nl`, `apiEndpoint` per Bryan's host choice); complete -> `setCaptchaToken(response)`; expire/error -> `setCaptchaToken(null)` and `reset()`; `destroy()` on unmount; reserved height; add the pinned dependency (check `minimumReleaseAge` rules of pnpm). Tests with a fake SDK: expired token not sent, error resets, unsupported or missing provider keeps the gate, submit blocked with message until solved.
|
||||
- [ ] **11. Preselect with `initialSubject`**: Panel passes the remembered preselect to the form, the form to the hook; test "Boek..." before the form is mounted.
|
||||
- [x] **1. Copy the current package**: `src/cms-client/` (http/, contact/, README, tests, boundary test) copied unchanged from `SlpSoftware/src/cms-client` (read only). Add the ESLint `no-restricted-imports` rule for `src/cms-client/**`. Check: boundary test and the package's own tests pass in this repo.
|
||||
- [x] **2. Client factory**: `src/contact/contactClient.ts` creating `createContactClient` with same-origin base `/api/v1`; no logging of bodies.
|
||||
- [x] **3. Subject options by label**: `src/lib/shootOptions.ts` returns `{ value: label, label }` plus the id-to-label map for `?pakket=`; test that every content label is 1-100 characters and that `& ' " < >` survive the payload (PBT-02/03).
|
||||
- [x] **4. ContactAvailability**: new `src/components/ContactForm/ContactAvailability.tsx` with the state machine of the functional design (no request when disabled; IntersectionObserver with the `useInView` hook; first-focus fallback; `idle/checking/open/closed`; token in memory; `refreshToken`). Tests: no request when disabled, one request when in view, 404/429/5xx/network keep the gate, unsupported provider keeps the gate, first-focus fallback.
|
||||
- [x] **5. ContactPanel + Gate wiring**: Gate stays the initial render; Panel renders Availability inside Gate when `enabled`; Panel remembers the last preselect as `{ subject: label, key }`; placeholder heights unchanged. Tests: prerendered HTML has no token/widget/address; hydration test stays green.
|
||||
- [x] **6. ContactForm on `useContactForm`**: replace reducer, validation, 3 s check and submit prop; keep Chakra skin, ids, test ids, thank-you and PrivacyNote; error text outside the label; honeypot from `honeypotProps`; failure message from the package with address assembled after hydration (`useEmailAddress`); events `contact-sent`/`contact-failed` through the analytics wrapper. Tests: component tests incl. axe, field errors, focus after render, 429 text, failure path without address in HTML.
|
||||
- [x] **7. Remove dead code**: `src/lib/contactFormReducer.ts`, `validateContact.ts`, `toContactPayload.ts`, `isLikelySpam`, `src/contact/submitContactForm.ts` and `types.ts` (as far as unused), plus their tests; update `src/test/arbitraries.ts` (form generators) and references.
|
||||
- [x] **8. Dev proxy and CSP**: `vite.config.ts` `server.proxy` for `/api` (env-configurable, default off in CI); `config/securityHeaders.ts` additions per the infrastructure design (frame-src decided by Bryan; others only after the real-browser test) with reason comments; extend the `securityHeaders` tests.
|
||||
- [x] **9. Final package** (after SLS-Main's message): replace `src/cms-client/` by the final version (captcha slot, `initialSubject`); re-run boundary and package tests.
|
||||
- [x] **10. CaptchaWidget**: new lazy chunk `src/components/ContactForm/CaptchaWidget.tsx` using `@friendlycaptcha/sdk` (`createWidget`, `startMode: focus`, `language: nl`, `apiEndpoint` per Bryan's host choice); complete -> `setCaptchaToken(response)`; expire/error -> `setCaptchaToken(null)` and `reset()`; `destroy()` on unmount; reserved height; add the pinned dependency (check `minimumReleaseAge` rules of pnpm). Tests with a fake SDK: expired token not sent, error resets, unsupported or missing provider keeps the gate, submit blocked with message until solved.
|
||||
- [x] **11. Preselect with `initialSubject`**: Panel passes the remembered preselect to the form, the form to the hook; test "Boek..." before the form is mounted.
|
||||
- [ ] **12. Privacy text**: PrivacyNote and the privacy page name the captcha provider and what the form stores (wording needs Bryan's approval; draft goes to SLS-Main for routing).
|
||||
- [ ] **13. PBT and e2e**: fast-check properties (PBT-02/03/07/08/09) for the label/payload mapping and trim; e2e with a mocked `/api` route: token 200 -> form, 404 -> gate, 202 success, 400 expired -> retry, prerendered HTML check; extend `noJs` e2e (gate and mail button without JS).
|
||||
- [ ] **14. Documentation**: update `LAYOUT.md` if the contact block changes; README note for the copied package (source and sync rule); `aidlc-docs` code summary.
|
||||
|
||||
@@ -11,3 +11,6 @@ pnpm-lock.yaml
|
||||
.junie
|
||||
.tanstack
|
||||
skills-lock.json
|
||||
|
||||
# Copied package (source: SlpSoftware src/cms-client); keeps its own formatting
|
||||
src/cms-client
|
||||
|
||||
@@ -31,6 +31,24 @@ export default tseslint.config(
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
{
|
||||
// The copied cms-client package stays headless: it may only import
|
||||
// react and its own files (also enforced by its boundary test)
|
||||
files: ['src/cms-client/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'no-restricted-imports': [
|
||||
'error',
|
||||
{
|
||||
patterns: [
|
||||
{
|
||||
group: ['@/*'],
|
||||
message: 'cms-client must not import from the app',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['config/**/*.ts', 'e2e/**/*.ts', 'vitest.e2e.config.ts'],
|
||||
languageOptions: {
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@fontsource/jost": "^5.3.0",
|
||||
"@fontsource/marcellus": "^5.3.0",
|
||||
"@friendlycaptcha/sdk": "^1.1.3",
|
||||
"@sentry/react": "^11.8.0",
|
||||
"@tanstack/react-router": "1.170.46",
|
||||
"@tanstack/react-start": "1.169.4",
|
||||
|
||||
Generated
+8
@@ -184,6 +184,9 @@ importers:
|
||||
'@fontsource/marcellus':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@friendlycaptcha/sdk':
|
||||
specifier: ^1.1.3
|
||||
version: 1.1.3
|
||||
'@sentry/react':
|
||||
specifier: ^11.8.0
|
||||
version: 11.8.0(react@19.3.0)
|
||||
@@ -758,6 +761,9 @@ packages:
|
||||
'@formatjs/intl-localematcher@0.6.2':
|
||||
resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==}
|
||||
|
||||
'@friendlycaptcha/sdk@1.1.3':
|
||||
resolution: {integrity: sha512-a2wJ46Ag6MGeZ/b+zyAO3MLT32816fgDN6fwQsVU6bRIUHyuU2/DHAWgQi5EiWAAr7Jj0uMrEdvukWhMPdnh1g==}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
|
||||
engines: {node: '>=18.18.0'}
|
||||
@@ -4730,6 +4736,8 @@ snapshots:
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
|
||||
'@friendlycaptcha/sdk@1.1.3': {}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
dependencies:
|
||||
'@humanfs/types': 0.15.0
|
||||
|
||||
@@ -191,7 +191,7 @@ describe('app', () => {
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
).toHaveValue('Newborn');
|
||||
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
|
||||
expect(router.state.location.pathname).toBe('/contact');
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
@@ -451,7 +451,7 @@ describe('homepage ?pakket=', () => {
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
).toHaveValue('Newborn');
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
scrolls.mock.contexts.some(
|
||||
@@ -468,11 +468,11 @@ describe('homepage ?pakket=', () => {
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
).toHaveValue('Newborn');
|
||||
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
|
||||
expect(router.state.location.hash).toBe('contact');
|
||||
// The form stays once loaded, also now that ?pakket= is gone
|
||||
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('newborn');
|
||||
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('Newborn');
|
||||
// within the section: the footer has a "Contact" heading too
|
||||
expect(
|
||||
within(screen.getByRole('region', { name: 'Contact' })).getByRole(
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# cms-client (draft package)
|
||||
|
||||
Headless client for the SLP CMS API, written inside the SlpSoftware frontend first and meant to move to the SlpModularCms repository as the package `cms-client` (decision of the product owner, 2026-11-09).
|
||||
|
||||
- **Boundary**: nothing in this folder may import from the rest of the app (`features`, `components`, `shared`, `theme`, `utils`, ...); enforced by ESLint (`no-restricted-imports`) and a test. Allowed: `react` and files inside `src/cms-client`.
|
||||
- **Parts** (import only what a site uses): `contact/` (validation, reducer, client, `useContactForm`), `http/` (internal helpers). `offerings/` follows later.
|
||||
- **Contract**: see `aidlc-docs/features/redesign-modern-timetravel/inception/application-design/contact-api-contract.md` and the CMS file `openapi/slpsoftware.v1.json`.
|
||||
- **No markup, no styling**: sites render their own fields from `useContactForm().getFieldProps`.
|
||||
- **Privacy**: nothing here logs form values, tokens or idempotency keys.
|
||||
|
||||
## Captcha slot and initial subject
|
||||
|
||||
- The token response may carry `captcha: { provider, siteKey, apiEndpoint }` (`apiEndpoint` is `global` or `eu`, default `global`). `useContactForm` returns `captcha`, `captchaRequired`, `captchaToken`, `setCaptchaToken(token | null)` and `captchaResetCount`. The package renders no widget: the site mounts the provider widget client-side, calls `setCaptchaToken(response)` when solved and `setCaptchaToken(null)` when it expires or fails, and resets the widget whenever `captchaResetCount` changes (a response can be used once).
|
||||
- With captcha required, submit sends nothing until a response is set and shows `messages.captchaRequired`; the payload then carries `captchaToken`. Without captcha the field is omitted.
|
||||
- `initialSubject` (option of `useContactForm`) applies a subject chosen before the form was mounted, as soon as it exists in `subjectOptions` and unless the visitor already picked one. Unknown values are ignored.
|
||||
- Subject values are the readable labels (they appear in the mail and the CMS message list); a site keeps its own ids only for links/preselect.
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// All source files of the package (tests excluded), as raw text.
|
||||
const sources = import.meta.glob(['../**/*.{ts,tsx}', '!../**/__tests__/**'], {
|
||||
query: '?raw',
|
||||
import: 'default',
|
||||
eager: true,
|
||||
}) as Record<string, string>;
|
||||
|
||||
const files = Object.entries(sources);
|
||||
|
||||
describe('cms-client boundary (movable package)', () => {
|
||||
it('finds the package sources', () => {
|
||||
expect(files.length).toBeGreaterThan(5);
|
||||
});
|
||||
|
||||
it('only imports react and files inside src/cms-client', () => {
|
||||
const offenders: string[] = [];
|
||||
for (const [file, text] of files) {
|
||||
for (const match of text.matchAll(/from\s+['"]([^'"]+)['"]/g)) {
|
||||
const spec = match[1];
|
||||
if (spec === 'react') continue;
|
||||
if (spec.startsWith('./')) continue;
|
||||
if (spec.startsWith('../')) {
|
||||
// Count how far the import climbs out of the package: file path is ../<inside>/x.ts
|
||||
const depthInside = file.replace(/^\.\.\//, '').split('/').length - 1;
|
||||
const climbs = spec.split('/').filter((part) => part === '..').length;
|
||||
if (climbs <= depthInside) continue;
|
||||
}
|
||||
offenders.push(`${file}: ${spec}`);
|
||||
}
|
||||
}
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads configuration only through import.meta.env.VITE_API_BASE_URL', () => {
|
||||
const uses = files.flatMap(([, text]) =>
|
||||
[...text.matchAll(/import\.meta\.env\.(\w+)/g)].map((m) => m[1]),
|
||||
);
|
||||
expect([...new Set(uses)]).toEqual(['VITE_API_BASE_URL']);
|
||||
});
|
||||
|
||||
it('does not log anything', () => {
|
||||
const logging = files.filter(([, text]) => /console\.(log|info|warn|error|debug)/.test(text));
|
||||
expect(logging).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
contactFormReducer,
|
||||
initialContactState,
|
||||
type ContactEvent,
|
||||
type ContactState,
|
||||
} from '../contactFormReducer';
|
||||
import type { ContactField } from '../types';
|
||||
|
||||
function run(events: ContactEvent[], from: ContactState = initialContactState): ContactState {
|
||||
return events.reduce(contactFormReducer, from);
|
||||
}
|
||||
|
||||
const fill: ContactEvent[] = [
|
||||
{ type: 'change', field: 'name', value: 'Jan' },
|
||||
{ type: 'change', field: 'email', value: 'jan@example.nl' },
|
||||
{ type: 'change', field: 'subject', value: 'website' },
|
||||
{ type: 'change', field: 'message', value: 'Hallo' },
|
||||
];
|
||||
|
||||
describe('contactFormReducer (examples)', () => {
|
||||
it('starts empty and editing', () => {
|
||||
expect(initialContactState.status).toBe('editing');
|
||||
expect(initialContactState.values.name).toBe('');
|
||||
});
|
||||
|
||||
it('shows an error only after blur of a touched field, and clears it when valid', () => {
|
||||
let state = run([{ type: 'change', field: 'email', value: 'nope' }]);
|
||||
expect(state.errors.email).toBeUndefined();
|
||||
state = run([{ type: 'blur', field: 'email' }], state);
|
||||
expect(state.errors.email).toBe('invalid');
|
||||
state = run([{ type: 'change', field: 'email', value: 'a@b.nl' }], state);
|
||||
expect(state.errors.email).toBeUndefined();
|
||||
});
|
||||
|
||||
it('shows all errors after a submit attempt and stays editing', () => {
|
||||
const state = run([{ type: 'submit' }]);
|
||||
expect(Object.keys(state.errors).sort()).toEqual(['email', 'message', 'name', 'subject']);
|
||||
expect(state.status).toBe('editing');
|
||||
});
|
||||
|
||||
it('refuses to start sending while invalid', () => {
|
||||
expect(run([{ type: 'sending' }]).status).toBe('editing');
|
||||
});
|
||||
|
||||
it('goes editing -> sending -> sent and ignores edits while sending', () => {
|
||||
let state = run([...fill, { type: 'sending' }]);
|
||||
expect(state.status).toBe('sending');
|
||||
const during = run(
|
||||
[{ type: 'change', field: 'name', value: 'Piet' }, { type: 'submit' }],
|
||||
state,
|
||||
);
|
||||
expect(during).toBe(state);
|
||||
state = run([{ type: 'succeeded' }], state);
|
||||
expect(state.status).toBe('sent');
|
||||
});
|
||||
|
||||
it('keeps all input after a failure and returns to editing on change', () => {
|
||||
let state = run([...fill, { type: 'sending' }, { type: 'failed' }]);
|
||||
expect(state.status).toBe('failed');
|
||||
expect(state.values.message).toBe('Hallo');
|
||||
state = run([{ type: 'change', field: 'message', value: 'Hallo!' }], state);
|
||||
expect(state.status).toBe('editing');
|
||||
});
|
||||
|
||||
it('maps server field errors back to editing with the errors shown', () => {
|
||||
const state = run([
|
||||
...fill,
|
||||
{ type: 'sending' },
|
||||
{ type: 'fieldErrors', errors: { email: 'invalid' } },
|
||||
]);
|
||||
expect(state.status).toBe('editing');
|
||||
expect(state.errors).toEqual({ email: 'invalid' });
|
||||
});
|
||||
|
||||
it('never leaves sent except through reset', () => {
|
||||
const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]);
|
||||
expect(
|
||||
run(
|
||||
[{ type: 'change', field: 'name', value: 'X' }, { type: 'failed' }, { type: 'submit' }],
|
||||
sent,
|
||||
),
|
||||
).toBe(sent);
|
||||
expect(run([{ type: 'reset' }], sent)).toEqual(initialContactState);
|
||||
});
|
||||
|
||||
it('applies a preselect to the subject', () => {
|
||||
expect(run([{ type: 'preselect', subject: 'maatwerk' }]).values.subject).toBe('maatwerk');
|
||||
});
|
||||
});
|
||||
|
||||
describe('contactFormReducer (properties)', () => {
|
||||
const field = fc.constantFrom<ContactField>('name', 'email', 'subject', 'message');
|
||||
const event: fc.Arbitrary<ContactEvent> = fc.oneof(
|
||||
fc.record({ type: fc.constant('change' as const), field, value: fc.string({ maxLength: 40 }) }),
|
||||
fc.record({ type: fc.constant('blur' as const), field }),
|
||||
fc.constant({ type: 'submit' } as ContactEvent),
|
||||
fc.constant({ type: 'sending' } as ContactEvent),
|
||||
fc.constant({ type: 'succeeded' } as ContactEvent),
|
||||
fc.constant({ type: 'failed' } as ContactEvent),
|
||||
fc.record({ type: fc.constant('preselect' as const), subject: fc.string({ maxLength: 10 }) }),
|
||||
);
|
||||
|
||||
it('sent is absorbing except for reset', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(event, { maxLength: 30 }), (rest) => {
|
||||
const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]);
|
||||
expect(run(rest, sent)).toBe(sent);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores edits and submits while sending', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.array(
|
||||
fc.oneof(
|
||||
fc.record({
|
||||
type: fc.constant('change' as const),
|
||||
field,
|
||||
value: fc.string({ maxLength: 10 }),
|
||||
}),
|
||||
fc.constant({ type: 'submit' } as ContactEvent),
|
||||
fc.record({
|
||||
type: fc.constant('preselect' as const),
|
||||
subject: fc.string({ maxLength: 10 }),
|
||||
}),
|
||||
),
|
||||
{ maxLength: 20 },
|
||||
),
|
||||
(edits) => {
|
||||
const sending = run([...fill, { type: 'sending' }]);
|
||||
expect(run(edits, sending)).toBe(sending);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('never loses typed values on failure', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(event, { maxLength: 30 }), (events) => {
|
||||
const before = run([...fill, { type: 'sending' }]);
|
||||
const after = run([{ type: 'failed' }], before);
|
||||
expect(after.values).toEqual(before.values);
|
||||
void events;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('only reaches sending from a valid form', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(event, { maxLength: 40 }), (events) => {
|
||||
const state = run(events);
|
||||
if (state.status === 'sending' || state.status === 'sent') {
|
||||
expect(
|
||||
Object.keys(run([{ type: 'submit' }], { ...state, status: 'editing' }).errors),
|
||||
).toEqual([]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createContactClient } from '../createContactClient';
|
||||
import { parseProblem } from '../../http/problem';
|
||||
import { retryAfterMinutes } from '../messages.nl';
|
||||
import type { ContactPayload } from '../types';
|
||||
|
||||
const payload: ContactPayload = {
|
||||
name: 'Jan',
|
||||
email: 'jan@example.nl',
|
||||
subject: 'website',
|
||||
message: 'Hallo',
|
||||
hpCheck: '',
|
||||
token: 'tok',
|
||||
};
|
||||
|
||||
function client(response: Response | Error) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
if (response instanceof Error) throw response;
|
||||
return response;
|
||||
});
|
||||
return {
|
||||
api: createContactClient({ baseUrl: '', fetch: fetchMock as unknown as typeof fetch }),
|
||||
fetchMock,
|
||||
};
|
||||
}
|
||||
|
||||
function json(body: unknown, status: number, headers: Record<string, string> = {}) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
describe('getToken', () => {
|
||||
it('returns the token on 200 and calls the contract path', async () => {
|
||||
const { api, fetchMock } = client(json({ token: 'abc', minSeconds: 3, captcha: null }, 200));
|
||||
expect(await api.getToken()).toEqual({
|
||||
kind: 'ok',
|
||||
token: { token: 'abc', minSeconds: 3, captcha: null },
|
||||
});
|
||||
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(
|
||||
'/api/v1/contact-messages/token',
|
||||
);
|
||||
});
|
||||
|
||||
it('parses captcha info', async () => {
|
||||
const { api } = client(
|
||||
json({ token: 'abc', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k' } }, 200),
|
||||
);
|
||||
const result = await api.getToken();
|
||||
expect(result.kind === 'ok' && result.token.captcha).toEqual({
|
||||
provider: 'fc',
|
||||
siteKey: 'k',
|
||||
apiEndpoint: 'global',
|
||||
});
|
||||
});
|
||||
|
||||
it('takes the captcha api endpoint from the server and falls back to global', async () => {
|
||||
const eu = client(
|
||||
json(
|
||||
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'eu' } },
|
||||
200,
|
||||
),
|
||||
);
|
||||
const euResult = await eu.api.getToken();
|
||||
expect(euResult.kind === 'ok' && euResult.token.captcha?.apiEndpoint).toBe('eu');
|
||||
|
||||
const odd = client(
|
||||
json(
|
||||
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'x' } },
|
||||
200,
|
||||
),
|
||||
);
|
||||
const oddResult = await odd.api.getToken();
|
||||
expect(oddResult.kind === 'ok' && oddResult.token.captcha?.apiEndpoint).toBe('global');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[404, 'closed'],
|
||||
[429, 'failed'],
|
||||
[500, 'failed'],
|
||||
[503, 'failed'],
|
||||
])('maps status %i to %s', async (status, kind) => {
|
||||
const { api } = client(new Response(null, { status }));
|
||||
expect((await api.getToken()).kind).toBe(kind);
|
||||
});
|
||||
|
||||
it('treats a malformed 200 body and network errors as failed', async () => {
|
||||
expect((await client(json({ nope: true }, 200)).api.getToken()).kind).toBe('failed');
|
||||
expect((await client(new Error('offline')).api.getToken()).kind).toBe('failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('submit', () => {
|
||||
it('posts the contract body with the idempotency key and treats 202 as ok', async () => {
|
||||
const { api, fetchMock } = client(json({ status: 'received' }, 202));
|
||||
expect(await api.submit(payload, { idempotencyKey: 'key-1' })).toEqual({ kind: 'ok' });
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/contact-messages');
|
||||
expect(init.method).toBe('POST');
|
||||
expect((init.headers as Record<string, string>)['Idempotency-Key']).toBe('key-1');
|
||||
expect(JSON.parse(init.body as string)).toEqual(payload);
|
||||
});
|
||||
|
||||
it('maps 400 field errors and ignores unknown fields/codes', async () => {
|
||||
const { api } = client(
|
||||
json(
|
||||
{
|
||||
errors: {
|
||||
email: ['invalid'],
|
||||
message: ['tooLong'],
|
||||
other: ['required'],
|
||||
name: ['weird'],
|
||||
},
|
||||
},
|
||||
400,
|
||||
),
|
||||
);
|
||||
expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({
|
||||
kind: 'invalid',
|
||||
fields: { email: 'invalid', message: 'tooLong' },
|
||||
tokenExpired: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('flags an expired token', async () => {
|
||||
const { api } = client(json({ errors: { token: ['expired'] } }, 400));
|
||||
expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({
|
||||
kind: 'invalid',
|
||||
fields: {},
|
||||
tokenExpired: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a 400 without usable errors (body, idempotencyKey) as failed', async () => {
|
||||
const { api } = client(json({ errors: { body: ['invalid'] } }, 400));
|
||||
expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed');
|
||||
});
|
||||
|
||||
it('maps 413, 404, 429 (with Retry-After) and 5xx', async () => {
|
||||
expect(
|
||||
(
|
||||
await client(new Response(null, { status: 413 })).api.submit(payload, {
|
||||
idempotencyKey: 'k',
|
||||
})
|
||||
).kind,
|
||||
).toBe('tooLarge');
|
||||
expect(
|
||||
(
|
||||
await client(new Response(null, { status: 404 })).api.submit(payload, {
|
||||
idempotencyKey: 'k',
|
||||
})
|
||||
).kind,
|
||||
).toBe('closed');
|
||||
expect(
|
||||
await client(json({}, 429, { 'Retry-After': '120' })).api.submit(payload, {
|
||||
idempotencyKey: 'k',
|
||||
}),
|
||||
).toEqual({ kind: 'rateLimited', retryAfterSeconds: 120 });
|
||||
expect(
|
||||
(
|
||||
await client(new Response(null, { status: 500 })).api.submit(payload, {
|
||||
idempotencyKey: 'k',
|
||||
})
|
||||
).kind,
|
||||
).toBe('failed');
|
||||
});
|
||||
|
||||
it('never throws on network errors', async () => {
|
||||
const { api } = client(new Error('offline'));
|
||||
expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed');
|
||||
});
|
||||
|
||||
it('times out hanging requests', async () => {
|
||||
vi.useFakeTimers();
|
||||
const hanging = vi.fn(
|
||||
(_url: string, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () =>
|
||||
reject(new DOMException('aborted', 'AbortError')),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const api = createContactClient({ baseUrl: '', fetch: hanging as unknown as typeof fetch });
|
||||
const promise = api.submit(payload, { idempotencyKey: 'k' });
|
||||
await vi.advanceTimersByTimeAsync(10_001);
|
||||
expect((await promise).kind).toBe('failed');
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
describe('serialization round trips (properties)', () => {
|
||||
it('payload JSON survives a stringify/parse round trip', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.record({
|
||||
name: fc.string({ maxLength: 100 }),
|
||||
email: fc.string({ maxLength: 254 }),
|
||||
subject: fc.string({ maxLength: 100 }),
|
||||
message: fc.string({ maxLength: 500 }),
|
||||
hpCheck: fc.constant(''),
|
||||
token: fc.string({ minLength: 1, maxLength: 50 }),
|
||||
}),
|
||||
(p) => {
|
||||
expect(JSON.parse(JSON.stringify(p))).toEqual(p);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('parseProblem recovers the error map of a serialized problem', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.dictionary(
|
||||
fc.constantFrom('name', 'email', 'subject', 'message', 'token'),
|
||||
fc.array(fc.constantFrom('required', 'tooLong', 'invalid', 'expired'), {
|
||||
minLength: 1,
|
||||
maxLength: 3,
|
||||
}),
|
||||
),
|
||||
(errors) => {
|
||||
const body = JSON.parse(
|
||||
JSON.stringify({ type: 'about:blank', title: 't', status: 400, errors }),
|
||||
);
|
||||
expect(parseProblem(400, body, null).errors).toEqual(errors);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('parseProblem never throws on arbitrary JSON', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.anything(), (body) => {
|
||||
expect(() => parseProblem(400, body, null)).not.toThrow();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('retryAfterMinutes rounds up and is at least 1', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.integer({ min: -10, max: 100_000 }), (seconds) => {
|
||||
const minutes = retryAfterMinutes(seconds);
|
||||
expect(minutes).toBeGreaterThanOrEqual(1);
|
||||
if (seconds > 0) expect(minutes * 60).toBeGreaterThanOrEqual(seconds);
|
||||
}),
|
||||
);
|
||||
expect(retryAfterMinutes(null)).toBe(1);
|
||||
expect(retryAfterMinutes(61)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { useContactForm } from '../useContactForm';
|
||||
import type { ContactClient, ContactPayload, ContactToken, SubmitResult } from '../types';
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 'Website', label: 'Website' },
|
||||
{ value: 'Overig', label: 'Overig' },
|
||||
];
|
||||
|
||||
const CAPTCHA_TOKEN: ContactToken = {
|
||||
token: 'tok',
|
||||
minSeconds: 3,
|
||||
captcha: { provider: 'friendlycaptcha', siteKey: 'FCMKEY', apiEndpoint: 'global' },
|
||||
};
|
||||
const PLAIN_TOKEN: ContactToken = { token: 'tok', minSeconds: 3, captcha: null };
|
||||
|
||||
function makeClient(results: SubmitResult[] = [{ kind: 'ok' }]) {
|
||||
const payloads: ContactPayload[] = [];
|
||||
const submit = vi.fn(async (payload: ContactPayload) => {
|
||||
payloads.push(payload);
|
||||
return results.shift() ?? ({ kind: 'ok' } as SubmitResult);
|
||||
});
|
||||
const client: ContactClient = {
|
||||
getToken: async () => ({ kind: 'ok', token: PLAIN_TOKEN }),
|
||||
submit,
|
||||
};
|
||||
return { client, payloads, submit };
|
||||
}
|
||||
|
||||
function Harness(props: {
|
||||
token: ContactToken;
|
||||
client: ContactClient;
|
||||
options?: typeof OPTIONS;
|
||||
initialSubject?: string | null;
|
||||
}) {
|
||||
const form = useContactForm({
|
||||
idPrefix: 'c',
|
||||
subjectOptions: props.options ?? OPTIONS,
|
||||
initialSubject: props.initialSubject,
|
||||
client: props.client,
|
||||
token: props.token,
|
||||
refreshToken: async () => ({ kind: 'ok', token: props.token }),
|
||||
fallbackAddress: 'info@example.nl',
|
||||
});
|
||||
const name = form.getFieldProps('name');
|
||||
const email = form.getFieldProps('email');
|
||||
const subject = form.getFieldProps('subject');
|
||||
const message = form.getFieldProps('message');
|
||||
return (
|
||||
<form {...form.formProps}>
|
||||
<input aria-label="naam" {...name.inputProps} />
|
||||
<input aria-label="mail" {...email.inputProps} />
|
||||
<select aria-label="onderwerp" {...subject.inputProps}>
|
||||
<option value="" />
|
||||
{(props.options ?? OPTIONS).map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<textarea aria-label="bericht" {...message.inputProps} />
|
||||
<button type="submit">verstuur</button>
|
||||
<output data-testid="captcha-required">{String(form.captchaRequired)}</output>
|
||||
<output data-testid="captcha-site-key">{form.captcha?.siteKey ?? '-'}</output>
|
||||
<output data-testid="captcha-endpoint">{form.captcha?.apiEndpoint ?? '-'}</output>
|
||||
<output data-testid="reset-count">{form.captchaResetCount}</output>
|
||||
<output data-testid="failure">{form.failureMessage ?? ''}</output>
|
||||
<output data-testid="status">{form.status}</output>
|
||||
<button type="button" onClick={() => form.setCaptchaToken('frc-response')}>
|
||||
solved
|
||||
</button>
|
||||
<button type="button" onClick={() => form.setCaptchaToken(null)}>
|
||||
expired
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function fill() {
|
||||
fireEvent.change(screen.getByLabelText('naam'), { target: { value: 'Jan' } });
|
||||
fireEvent.change(screen.getByLabelText('mail'), { target: { value: 'jan@example.nl' } });
|
||||
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Website' } });
|
||||
fireEvent.change(screen.getByLabelText('bericht'), { target: { value: 'Hallo daar' } });
|
||||
}
|
||||
|
||||
describe('captcha slot', () => {
|
||||
it('exposes the captcha info from the token response', () => {
|
||||
render(<Harness token={CAPTCHA_TOKEN} client={makeClient().client} />);
|
||||
expect(screen.getByTestId('captcha-required')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('captcha-site-key')).toHaveTextContent('FCMKEY');
|
||||
expect(screen.getByTestId('captcha-endpoint')).toHaveTextContent('global');
|
||||
});
|
||||
|
||||
it('reports no captcha when the server asks for none', () => {
|
||||
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} />);
|
||||
expect(screen.getByTestId('captcha-required')).toHaveTextContent('false');
|
||||
});
|
||||
|
||||
it('does not send until the captcha is solved and shows the message', async () => {
|
||||
const { client, submit } = makeClient();
|
||||
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
|
||||
fill();
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('failure')).toHaveTextContent(
|
||||
'Bevestig eerst dat je geen robot bent.',
|
||||
),
|
||||
);
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId('status')).toHaveTextContent('editing');
|
||||
});
|
||||
|
||||
it('sends the captcha response with the payload and asks for a widget reset afterwards', async () => {
|
||||
const { client, payloads } = makeClient();
|
||||
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
|
||||
fill();
|
||||
fireEvent.click(screen.getByText('solved'));
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
|
||||
expect(payloads[0].captchaToken).toBe('frc-response');
|
||||
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
|
||||
});
|
||||
|
||||
it('never sends an expired captcha response', async () => {
|
||||
const { client, submit } = makeClient();
|
||||
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
|
||||
fill();
|
||||
fireEvent.click(screen.getByText('solved'));
|
||||
fireEvent.click(screen.getByText('expired'));
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('needs a new captcha response after a failed attempt', async () => {
|
||||
const { client, submit } = makeClient([{ kind: 'failed' }]);
|
||||
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
|
||||
fill();
|
||||
fireEvent.click(screen.getByText('solved'));
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('failed'));
|
||||
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('omits captchaToken when no captcha is configured', async () => {
|
||||
const { client, payloads } = makeClient();
|
||||
render(<Harness token={PLAIN_TOKEN} client={client} />);
|
||||
fill();
|
||||
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
|
||||
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
|
||||
expect('captchaToken' in payloads[0]).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('initialSubject', () => {
|
||||
it('applies a subject chosen before the form was mounted', async () => {
|
||||
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Website" />);
|
||||
await waitFor(() =>
|
||||
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
|
||||
);
|
||||
});
|
||||
|
||||
it('waits until the option exists and ignores unknown values', async () => {
|
||||
const { rerender } = render(
|
||||
<Harness
|
||||
token={PLAIN_TOKEN}
|
||||
client={makeClient().client}
|
||||
options={[{ value: 'Overig', label: 'Overig' }]}
|
||||
initialSubject="Website"
|
||||
/>,
|
||||
);
|
||||
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
|
||||
await act(async () => {
|
||||
rerender(
|
||||
<Harness
|
||||
token={PLAIN_TOKEN}
|
||||
client={makeClient().client}
|
||||
options={OPTIONS}
|
||||
initialSubject="Website"
|
||||
/>,
|
||||
);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not override a subject the visitor already chose', async () => {
|
||||
const { rerender } = render(
|
||||
<Harness
|
||||
token={PLAIN_TOKEN}
|
||||
client={makeClient().client}
|
||||
options={[{ value: 'Overig', label: 'Overig' }]}
|
||||
initialSubject="Website"
|
||||
/>,
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Overig' } });
|
||||
await act(async () => {
|
||||
rerender(
|
||||
<Harness
|
||||
token={PLAIN_TOKEN}
|
||||
client={makeClient().client}
|
||||
options={OPTIONS}
|
||||
initialSubject="Website"
|
||||
/>,
|
||||
);
|
||||
});
|
||||
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Overig');
|
||||
});
|
||||
|
||||
it('ignores an unknown initial subject', () => {
|
||||
render(
|
||||
<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Bestaat niet" />,
|
||||
);
|
||||
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CONTACT_LIMITS, EMPTY_FIELDS, type ContactFields } from '../types';
|
||||
import { hasErrors, trimFields, validateContact } from '../validateContact';
|
||||
|
||||
const valid: ContactFields = {
|
||||
name: 'Jan Jansen',
|
||||
email: 'jan@example.nl',
|
||||
subject: 'website',
|
||||
message: 'Ik wil graag een offerte.',
|
||||
};
|
||||
|
||||
describe('validateContact (examples)', () => {
|
||||
it('accepts valid values', () => {
|
||||
expect(validateContact(valid)).toEqual({});
|
||||
expect(hasErrors(validateContact(valid))).toBe(false);
|
||||
});
|
||||
|
||||
it('requires every field (after trimming)', () => {
|
||||
expect(validateContact(EMPTY_FIELDS)).toEqual({
|
||||
name: 'required',
|
||||
email: 'required',
|
||||
subject: 'required',
|
||||
message: 'required',
|
||||
});
|
||||
expect(validateContact({ ...valid, name: ' ', message: '\n\t ' })).toEqual({
|
||||
name: 'required',
|
||||
message: 'required',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['plain', false],
|
||||
['a@b', false],
|
||||
['a@b.c', false],
|
||||
['a b@c.nl', false],
|
||||
['a@b.nl', true],
|
||||
['first.last+tag@sub.example.nl', true],
|
||||
])('email %s valid=%s', (email, ok) => {
|
||||
const errors = validateContact({ ...valid, email });
|
||||
expect(errors.email).toBe(ok ? undefined : 'invalid');
|
||||
});
|
||||
|
||||
it('reports the first failing rule per field: required, then length, then format', () => {
|
||||
const tooLongInvalid = 'x'.repeat(CONTACT_LIMITS.email + 1);
|
||||
expect(validateContact({ ...valid, email: tooLongInvalid }).email).toBe('tooLong');
|
||||
expect(validateContact({ ...valid, email: 'nope' }).email).toBe('invalid');
|
||||
});
|
||||
|
||||
it('rejects control characters in name, email and subject, but allows line breaks in the message', () => {
|
||||
expect(validateContact({ ...valid, name: 'Jan\nJansen' }).name).toBe('invalid');
|
||||
expect(validateContact({ ...valid, subject: 'a\u0007b' }).subject).toBe('invalid');
|
||||
expect(validateContact({ ...valid, message: 'regel 1\nregel 2\tmet tab' })).toEqual({});
|
||||
expect(validateContact({ ...valid, message: 'bel\u0007' }).message).toBe('invalid');
|
||||
});
|
||||
|
||||
it('trims before measuring', () => {
|
||||
expect(validateContact({ ...valid, name: ` ${'a'.repeat(100)} ` })).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateContact (properties)', () => {
|
||||
const text = fc.string({ maxLength: 300 });
|
||||
const fields = fc.record({ name: text, email: text, subject: text, message: text });
|
||||
|
||||
it('is invariant under trimming', () => {
|
||||
fc.assert(
|
||||
fc.property(fields, (values) => {
|
||||
expect(validateContact(values)).toEqual(validateContact(trimFields(values)));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('treats the length limits as inclusive for every field', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.constantFrom('name', 'subject', 'message' as const), (field) => {
|
||||
const limit = CONTACT_LIMITS[field];
|
||||
const at = { ...valid, [field]: 'a'.repeat(limit) };
|
||||
const over = { ...valid, [field]: 'a'.repeat(limit + 1) };
|
||||
expect(validateContact(at)[field]).toBeUndefined();
|
||||
expect(validateContact(over)[field]).toBe('tooLong');
|
||||
}),
|
||||
);
|
||||
const localPart = 'a'.repeat(CONTACT_LIMITS.email - '@b.nl'.length);
|
||||
expect(validateContact({ ...valid, email: `${localPart}@b.nl` }).email).toBeUndefined();
|
||||
expect(validateContact({ ...valid, email: `${localPart}a@b.nl` }).email).toBe('tooLong');
|
||||
});
|
||||
|
||||
it('rejects any control character inside name', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string({ minLength: 1, maxLength: 20 }).filter((s) => s.trim().length > 0),
|
||||
fc.integer({ min: 0, max: 0x1f }),
|
||||
(base, code) => {
|
||||
const name = `${base.trim()}${String.fromCharCode(code)}x`;
|
||||
if (name.trim() !== name) return; // trimming would remove edge whitespace controls
|
||||
expect(validateContact({ ...valid, name }).name).toBe('invalid');
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('only ever yields known codes', () => {
|
||||
fc.assert(
|
||||
fc.property(fields, (values) => {
|
||||
for (const code of Object.values(validateContact(values))) {
|
||||
expect(['required', 'tooLong', 'invalid']).toContain(code);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
EMPTY_FIELDS,
|
||||
type ContactField,
|
||||
type ContactFieldErrors,
|
||||
type ContactFields,
|
||||
type ContactStatus,
|
||||
} from './types';
|
||||
import { hasErrors, validateContact } from './validateContact';
|
||||
|
||||
export interface ContactState {
|
||||
status: ContactStatus;
|
||||
values: ContactFields;
|
||||
touched: Partial<Record<ContactField, boolean>>;
|
||||
/** Errors currently shown (touched fields or after a submit attempt, plus server errors). */
|
||||
errors: ContactFieldErrors;
|
||||
/** True after a submit attempt: every field then shows its error. */
|
||||
submitted: boolean;
|
||||
}
|
||||
|
||||
export type ContactEvent =
|
||||
| { type: 'change'; field: ContactField; value: string }
|
||||
| { type: 'blur'; field: ContactField }
|
||||
| { type: 'submit' }
|
||||
| { type: 'sending' }
|
||||
| { type: 'succeeded' }
|
||||
| { type: 'failed' }
|
||||
| { type: 'fieldErrors'; errors: ContactFieldErrors }
|
||||
| { type: 'preselect'; subject: string }
|
||||
| { type: 'reset' };
|
||||
|
||||
export const initialContactState: ContactState = {
|
||||
status: 'editing',
|
||||
values: EMPTY_FIELDS,
|
||||
touched: {},
|
||||
errors: {},
|
||||
submitted: false,
|
||||
};
|
||||
|
||||
function visibleErrors(state: Pick<ContactState, 'values' | 'touched' | 'submitted'>) {
|
||||
const all = validateContact(state.values);
|
||||
const shown: ContactFieldErrors = {};
|
||||
for (const field of Object.keys(all) as ContactField[]) {
|
||||
if (state.submitted || state.touched[field]) {
|
||||
shown[field] = all[field];
|
||||
}
|
||||
}
|
||||
return shown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure reducer of the contact form (BR-U4-4, BR-U4-5). Invariants: `sent` only changes through
|
||||
* `reset`; input is kept on `failed`; edits are ignored while `sending`.
|
||||
*/
|
||||
export function contactFormReducer(state: ContactState, event: ContactEvent): ContactState {
|
||||
if (state.status === 'sent' && event.type !== 'reset') {
|
||||
return state;
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'reset':
|
||||
return initialContactState;
|
||||
|
||||
case 'change': {
|
||||
if (state.status === 'sending') {
|
||||
return state;
|
||||
}
|
||||
const values = { ...state.values, [event.field]: event.value };
|
||||
const next = { ...state, values, status: 'editing' as const };
|
||||
return { ...next, errors: visibleErrors(next) };
|
||||
}
|
||||
|
||||
case 'preselect': {
|
||||
if (state.status === 'sending') {
|
||||
return state;
|
||||
}
|
||||
const values = { ...state.values, subject: event.subject };
|
||||
const next = { ...state, values, status: 'editing' as const };
|
||||
return { ...next, errors: visibleErrors(next) };
|
||||
}
|
||||
|
||||
case 'blur': {
|
||||
const touched = { ...state.touched, [event.field]: true };
|
||||
return { ...state, touched, errors: visibleErrors({ ...state, touched }) };
|
||||
}
|
||||
|
||||
case 'submit': {
|
||||
if (state.status === 'sending') {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state, submitted: true };
|
||||
return { ...next, errors: visibleErrors(next) };
|
||||
}
|
||||
|
||||
case 'sending':
|
||||
return hasErrors(validateContact(state.values)) ? state : { ...state, status: 'sending' };
|
||||
|
||||
case 'succeeded':
|
||||
return state.status === 'sending' ? { ...state, status: 'sent', errors: {} } : state;
|
||||
|
||||
case 'failed':
|
||||
return state.status === 'sending' ? { ...state, status: 'failed' } : state;
|
||||
|
||||
case 'fieldErrors':
|
||||
return state.status === 'sending'
|
||||
? { ...state, status: 'editing', submitted: true, errors: event.errors }
|
||||
: state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { apiUrl } from '../http/apiUrl';
|
||||
import { fetchJson } from '../http/fetchJson';
|
||||
import { parseProblem } from '../http/problem';
|
||||
import type {
|
||||
ContactClient,
|
||||
ContactErrorCode,
|
||||
ContactField,
|
||||
ContactFieldErrors,
|
||||
ContactPayload,
|
||||
ContactToken,
|
||||
SubmitResult,
|
||||
TokenResult,
|
||||
} from './types';
|
||||
|
||||
const TOKEN_PATH = '/api/v1/contact-messages/token';
|
||||
const SUBMIT_PATH = '/api/v1/contact-messages';
|
||||
const FIELDS: ContactField[] = ['name', 'email', 'subject', 'message'];
|
||||
const CODES: ContactErrorCode[] = ['required', 'tooLong', 'invalid', 'expired'];
|
||||
|
||||
function parseToken(body: unknown): ContactToken | null {
|
||||
if (!body || typeof body !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const { token, minSeconds, captcha } = body as Record<string, unknown>;
|
||||
if (typeof token !== 'string' || token.length === 0 || typeof minSeconds !== 'number') {
|
||||
return null;
|
||||
}
|
||||
let parsedCaptcha: ContactToken['captcha'] = null;
|
||||
if (captcha && typeof captcha === 'object') {
|
||||
const { provider, siteKey, apiEndpoint } = captcha as Record<string, unknown>;
|
||||
if (typeof provider !== 'string' || typeof siteKey !== 'string') {
|
||||
return null;
|
||||
}
|
||||
// Additive field: absent or unknown means the default (global) endpoint.
|
||||
parsedCaptcha = { provider, siteKey, apiEndpoint: apiEndpoint === 'eu' ? 'eu' : 'global' };
|
||||
}
|
||||
return { token, minSeconds, captcha: parsedCaptcha };
|
||||
}
|
||||
|
||||
function mapFieldErrors(errors: Record<string, string[]>): ContactFieldErrors {
|
||||
const result: ContactFieldErrors = {};
|
||||
for (const field of FIELDS) {
|
||||
const code = errors[field]?.find((c): c is ContactErrorCode => (CODES as string[]).includes(c));
|
||||
if (code) {
|
||||
result[field] = code;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Client for the contact endpoints of the CMS API (contract v0.3.x). Never throws: every outcome
|
||||
* is a typed result. Request and response bodies are never logged.
|
||||
*/
|
||||
export function createContactClient(
|
||||
options: { baseUrl?: string; fetch?: typeof fetch } = {},
|
||||
): ContactClient {
|
||||
const fetchImpl = options.fetch ?? ((...args) => fetch(...args));
|
||||
|
||||
return {
|
||||
async getToken(): Promise<TokenResult> {
|
||||
try {
|
||||
const response = await fetchJson(fetchImpl, apiUrl(TOKEN_PATH, options.baseUrl), {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (response.status === 200) {
|
||||
const token = parseToken(response.body);
|
||||
return token ? { kind: 'ok', token } : { kind: 'failed' };
|
||||
}
|
||||
return response.status === 404 ? { kind: 'closed' } : { kind: 'failed' };
|
||||
} catch {
|
||||
return { kind: 'failed' };
|
||||
}
|
||||
},
|
||||
|
||||
async submit(payload: ContactPayload, context): Promise<SubmitResult> {
|
||||
try {
|
||||
const response = await fetchJson(fetchImpl, apiUrl(SUBMIT_PATH, options.baseUrl), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'Idempotency-Key': context.idempotencyKey,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
switch (response.status) {
|
||||
case 202:
|
||||
return { kind: 'ok' };
|
||||
case 400: {
|
||||
const problem = parseProblem(400, response.body, response.retryAfter);
|
||||
const fields = mapFieldErrors(problem.errors);
|
||||
const tokenExpired = Boolean(problem.errors.token?.includes('expired'));
|
||||
if (tokenExpired || Object.keys(fields).length > 0) {
|
||||
return { kind: 'invalid', fields, tokenExpired };
|
||||
}
|
||||
return { kind: 'failed' };
|
||||
}
|
||||
case 404:
|
||||
return { kind: 'closed' };
|
||||
case 413:
|
||||
return { kind: 'tooLarge' };
|
||||
case 429:
|
||||
return {
|
||||
kind: 'rateLimited',
|
||||
retryAfterSeconds: parseProblem(429, response.body, response.retryAfter)
|
||||
.retryAfterSeconds,
|
||||
};
|
||||
default:
|
||||
return { kind: 'failed' };
|
||||
}
|
||||
} catch {
|
||||
return { kind: 'failed' };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export { createContactClient } from './createContactClient';
|
||||
export { contactFormReducer, initialContactState } from './contactFormReducer';
|
||||
export type { ContactEvent, ContactState } from './contactFormReducer';
|
||||
export { fieldErrorMessage, messagesNl, retryAfterMinutes } from './messages.nl';
|
||||
export type { ContactMessages } from './messages.nl';
|
||||
export { useContactForm } from './useContactForm';
|
||||
export type { ContactFailure, SubjectOption, UseContactFormOptions } from './useContactForm';
|
||||
export { hasErrors, trimFields, validateContact } from './validateContact';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { ContactErrorCode, ContactField } from './types';
|
||||
|
||||
/** Texts of the contact form; every entry can be overridden per site (default: Dutch). */
|
||||
export interface ContactMessages {
|
||||
fieldErrors: Record<ContactField, Partial<Record<ContactErrorCode, string>>>;
|
||||
fallbackFieldError: string;
|
||||
rateLimited: (minutes: number) => string;
|
||||
tooLarge: string;
|
||||
/** Shown when the captcha has not been solved (or has expired) at submit time. */
|
||||
captchaRequired: string;
|
||||
failed: (address: string) => string;
|
||||
sendingLabel: string;
|
||||
}
|
||||
|
||||
export const messagesNl: ContactMessages = {
|
||||
fieldErrors: {
|
||||
name: {
|
||||
required: 'Vul je naam in.',
|
||||
tooLong: 'De naam is te lang.',
|
||||
invalid: 'Deze naam is ongeldig.',
|
||||
},
|
||||
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.',
|
||||
tooLong: 'Dit onderwerp is te lang.',
|
||||
invalid: 'Kies een onderwerp.',
|
||||
},
|
||||
message: {
|
||||
required: 'Schrijf hier je vraag.',
|
||||
tooLong: 'Het bericht is te lang.',
|
||||
invalid: 'Dit bericht bevat ongeldige tekens.',
|
||||
},
|
||||
},
|
||||
fallbackFieldError: 'Controleer dit veld.',
|
||||
rateLimited: (minutes) =>
|
||||
`Je hebt net al een bericht gestuurd. Probeer het over ${minutes} ${minutes === 1 ? 'minuut' : 'minuten'} opnieuw.`,
|
||||
tooLarge: 'Je bericht is te groot.',
|
||||
captchaRequired: 'Bevestig eerst dat je geen robot bent.',
|
||||
failed: (address) => `Versturen lukte niet. Probeer het later nog eens of mail naar ${address}.`,
|
||||
sendingLabel: 'Versturen…',
|
||||
};
|
||||
|
||||
export function fieldErrorMessage(
|
||||
messages: ContactMessages,
|
||||
field: ContactField,
|
||||
code: ContactErrorCode,
|
||||
): string {
|
||||
return messages.fieldErrors[field][code] ?? messages.fallbackFieldError;
|
||||
}
|
||||
|
||||
/** Retry-After seconds -> whole minutes, rounded up, at least 1. */
|
||||
export function retryAfterMinutes(seconds: number | null): number {
|
||||
if (seconds === null || !Number.isFinite(seconds) || seconds <= 0) {
|
||||
return 1;
|
||||
}
|
||||
return Math.max(1, Math.ceil(seconds / 60));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
export type ContactField = 'name' | 'email' | 'subject' | 'message';
|
||||
export type ContactErrorCode = 'required' | 'tooLong' | 'invalid' | 'expired';
|
||||
export type ContactStatus = 'editing' | 'sending' | 'sent' | 'failed';
|
||||
|
||||
export type ContactFields = Record<ContactField, string>;
|
||||
export type ContactFieldErrors = Partial<Record<ContactField, ContactErrorCode>>;
|
||||
|
||||
/** Limits agreed in the API contract (v0.3.x). */
|
||||
export const CONTACT_LIMITS = { name: 100, email: 254, subject: 100, message: 2000 } as const;
|
||||
|
||||
export const EMPTY_FIELDS: ContactFields = { name: '', email: '', subject: '', message: '' };
|
||||
|
||||
/** Region of the captcha provider API; the site passes it to the widget. */
|
||||
export type CaptchaApiEndpoint = 'global' | 'eu';
|
||||
|
||||
/** Captcha the server asks for; `null` in the token response means no captcha. */
|
||||
export interface CaptchaInfo {
|
||||
provider: string;
|
||||
siteKey: string;
|
||||
apiEndpoint: CaptchaApiEndpoint;
|
||||
}
|
||||
|
||||
export interface ContactToken {
|
||||
token: string;
|
||||
minSeconds: number;
|
||||
captcha: CaptchaInfo | null;
|
||||
}
|
||||
|
||||
/** Body of POST /api/v1/contact-messages. */
|
||||
export interface ContactPayload extends ContactFields {
|
||||
hpCheck: string;
|
||||
token: string;
|
||||
captchaToken?: string | null;
|
||||
}
|
||||
|
||||
export type TokenResult =
|
||||
{ kind: 'ok'; token: ContactToken } | { kind: 'closed' } | { kind: 'failed' };
|
||||
|
||||
export type SubmitResult =
|
||||
| { kind: 'ok' }
|
||||
| { kind: 'invalid'; fields: ContactFieldErrors; tokenExpired: boolean }
|
||||
| { kind: 'tooLarge' }
|
||||
| { kind: 'rateLimited'; retryAfterSeconds: number | null }
|
||||
| { kind: 'closed' }
|
||||
| { kind: 'failed' };
|
||||
|
||||
export interface ContactClient {
|
||||
getToken(): Promise<TokenResult>;
|
||||
submit(payload: ContactPayload, context: { idempotencyKey: string }): Promise<SubmitResult>;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';
|
||||
import type { ChangeEvent, FormEvent } from 'react';
|
||||
import { contactFormReducer, initialContactState } from './contactFormReducer';
|
||||
import {
|
||||
fieldErrorMessage,
|
||||
messagesNl,
|
||||
retryAfterMinutes,
|
||||
type ContactMessages,
|
||||
} from './messages.nl';
|
||||
import type {
|
||||
ContactClient,
|
||||
ContactField,
|
||||
ContactPayload,
|
||||
ContactToken,
|
||||
SubmitResult,
|
||||
TokenResult,
|
||||
} from './types';
|
||||
import { hasErrors, trimFields, validateContact } from './validateContact';
|
||||
|
||||
export interface SubjectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type ContactFailure =
|
||||
| { kind: 'generic' }
|
||||
| { kind: 'tooLarge' }
|
||||
| { kind: 'captchaRequired' }
|
||||
| { kind: 'rateLimited'; minutes: number };
|
||||
|
||||
export interface UseContactFormOptions {
|
||||
/** Prefix of all DOM ids so the form can appear more than once. */
|
||||
idPrefix: string;
|
||||
subjectOptions: SubjectOption[];
|
||||
/** Value + change counter; a new `key` re-applies the subject. Unknown values are ignored. */
|
||||
preselect?: { subject: string | null; key: number };
|
||||
/**
|
||||
* Subject chosen before the form was mounted (e.g. a package link clicked earlier). Applied as
|
||||
* soon as it is among `subjectOptions` (they may arrive later) unless the visitor already
|
||||
* touched the subject field. Unknown values are ignored.
|
||||
*/
|
||||
initialSubject?: string | null;
|
||||
client: ContactClient;
|
||||
/** Server-signed token obtained by the availability check. */
|
||||
token: ContactToken;
|
||||
/** Fetches a fresh token (used once when the API answers `expired`). */
|
||||
refreshToken: () => Promise<TokenResult>;
|
||||
messages?: ContactMessages;
|
||||
/** Address shown in the failure message (assembled by the site, not hard-coded here). */
|
||||
fallbackAddress: string;
|
||||
/** Telemetry hook; receives only the outcome, never any form data. */
|
||||
onEvent?: (event: 'sent' | 'failed') => void;
|
||||
}
|
||||
|
||||
function newIdempotencyKey(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
const bytes = new Uint8Array(16);
|
||||
crypto.getRandomValues(bytes);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
const FIELD_ORDER: ContactField[] = ['name', 'email', 'subject', 'message'];
|
||||
|
||||
/**
|
||||
* Headless contact form: state, validation, submit flow and accessibility wiring, without any
|
||||
* markup or styling (BR-U4-1..16). Sites render their own fields from `getFieldProps`.
|
||||
*/
|
||||
export function useContactForm(options: UseContactFormOptions) {
|
||||
const {
|
||||
idPrefix,
|
||||
subjectOptions,
|
||||
preselect,
|
||||
initialSubject,
|
||||
client,
|
||||
token,
|
||||
refreshToken,
|
||||
fallbackAddress,
|
||||
onEvent,
|
||||
} = options;
|
||||
const messages = options.messages ?? messagesNl;
|
||||
const [state, dispatch] = useReducer(contactFormReducer, initialContactState);
|
||||
const [failure, setFailure] = useState<ContactFailure | null>(null);
|
||||
const [honeypot, setHoneypot] = useState('');
|
||||
const keyRef = useRef<string | null>(null);
|
||||
const tokenRef = useRef(token);
|
||||
const sendingRef = useRef(false);
|
||||
const lastPreselectKey = useRef(preselect?.key ?? 0);
|
||||
const pendingInitialSubject = useRef(initialSubject ?? null);
|
||||
const [captchaToken, setCaptchaTokenState] = useState<string | null>(null);
|
||||
const [captchaResetCount, setCaptchaResetCount] = useState(0);
|
||||
const captchaTokenRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
tokenRef.current = token;
|
||||
}, [token]);
|
||||
|
||||
// BR-U4-9: apply the package choice whenever the change counter moves; ignore unknown values.
|
||||
useEffect(() => {
|
||||
if (!preselect || preselect.key === lastPreselectKey.current) {
|
||||
return;
|
||||
}
|
||||
lastPreselectKey.current = preselect.key;
|
||||
if (preselect.subject && subjectOptions.some((o) => o.value === preselect.subject)) {
|
||||
dispatch({ type: 'preselect', subject: preselect.subject });
|
||||
}
|
||||
}, [preselect, subjectOptions]);
|
||||
|
||||
// Subject chosen before the form existed: apply once, when its option is available.
|
||||
useEffect(() => {
|
||||
const wanted = pendingInitialSubject.current;
|
||||
if (wanted === null || !subjectOptions.some((o) => o.value === wanted)) {
|
||||
return;
|
||||
}
|
||||
pendingInitialSubject.current = null;
|
||||
if (!state.touched.subject && state.values.subject === '') {
|
||||
dispatch({ type: 'preselect', subject: wanted });
|
||||
}
|
||||
}, [subjectOptions, state.touched.subject, state.values.subject]);
|
||||
|
||||
const setCaptchaToken = useCallback((value: string | null) => {
|
||||
captchaTokenRef.current = value;
|
||||
setCaptchaTokenState(value);
|
||||
}, []);
|
||||
|
||||
const fieldId = useCallback((field: ContactField) => `${idPrefix}-${field}`, [idPrefix]);
|
||||
|
||||
// Focus is applied after the render in which the fields are enabled and the errors are shown
|
||||
// (inputs are disabled while sending, and a disabled input cannot take focus).
|
||||
const pendingFocus = useRef<ContactField | null>(null);
|
||||
const focusFirstInvalid = useCallback((errors: Partial<Record<ContactField, unknown>>) => {
|
||||
pendingFocus.current = FIELD_ORDER.find((field) => errors[field]) ?? null;
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pendingFocus.current && state.status !== 'sending') {
|
||||
document.getElementById(fieldId(pendingFocus.current))?.focus();
|
||||
pendingFocus.current = null;
|
||||
}
|
||||
}, [state, fieldId]);
|
||||
|
||||
const attempt = useCallback(
|
||||
async (payload: ContactPayload, key: string): Promise<SubmitResult> => {
|
||||
let current = payload;
|
||||
// At most one automatic token refresh (BR-U4-10): only the first answer may be `expired`.
|
||||
for (let round = 0; round < 2; round++) {
|
||||
const result = await client.submit(current, { idempotencyKey: key });
|
||||
if (!(result.kind === 'invalid' && result.tokenExpired && round === 0)) {
|
||||
return result;
|
||||
}
|
||||
const fresh = await refreshToken();
|
||||
if (fresh.kind !== 'ok') {
|
||||
return { kind: 'failed' };
|
||||
}
|
||||
tokenRef.current = fresh.token;
|
||||
current = { ...current, token: fresh.token.token };
|
||||
}
|
||||
return { kind: 'failed' };
|
||||
},
|
||||
[client, refreshToken],
|
||||
);
|
||||
|
||||
const finishFailure = useCallback(
|
||||
(next: ContactFailure) => {
|
||||
setFailure(next);
|
||||
dispatch({ type: 'failed' });
|
||||
onEvent?.('failed');
|
||||
},
|
||||
[onEvent],
|
||||
);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (sendingRef.current || state.status === 'sending' || state.status === 'sent') {
|
||||
return;
|
||||
}
|
||||
dispatch({ type: 'submit' });
|
||||
const errors = validateContact(state.values);
|
||||
if (hasErrors(errors)) {
|
||||
focusFirstInvalid(errors);
|
||||
return;
|
||||
}
|
||||
|
||||
// The captcha must be solved first; the server would count a missing token as spam while
|
||||
// answering 202, so the visitor has to be told here.
|
||||
if (tokenRef.current.captcha !== null && !captchaTokenRef.current) {
|
||||
setFailure({ kind: 'captchaRequired' });
|
||||
return;
|
||||
}
|
||||
|
||||
sendingRef.current = true;
|
||||
setFailure(null);
|
||||
dispatch({ type: 'sending' });
|
||||
try {
|
||||
// BR-U4-7: a filled honeypot gets a silent success without any request.
|
||||
if (honeypot.length > 0) {
|
||||
dispatch({ type: 'succeeded' });
|
||||
return;
|
||||
}
|
||||
keyRef.current ??= newIdempotencyKey();
|
||||
const payload: ContactPayload = {
|
||||
...trimFields(state.values),
|
||||
hpCheck: '',
|
||||
token: tokenRef.current.token,
|
||||
...(tokenRef.current.captcha !== null ? { captchaToken: captchaTokenRef.current } : {}),
|
||||
};
|
||||
const result = await attempt(payload, keyRef.current);
|
||||
switch (result.kind) {
|
||||
case 'ok':
|
||||
keyRef.current = null;
|
||||
dispatch({ type: 'succeeded' });
|
||||
onEvent?.('sent');
|
||||
break;
|
||||
case 'invalid':
|
||||
if (Object.keys(result.fields).length > 0) {
|
||||
dispatch({ type: 'fieldErrors', errors: result.fields });
|
||||
focusFirstInvalid(result.fields);
|
||||
} else {
|
||||
finishFailure({ kind: 'generic' });
|
||||
}
|
||||
break;
|
||||
case 'tooLarge':
|
||||
finishFailure({ kind: 'tooLarge' });
|
||||
break;
|
||||
case 'rateLimited':
|
||||
finishFailure({
|
||||
kind: 'rateLimited',
|
||||
minutes: retryAfterMinutes(result.retryAfterSeconds),
|
||||
});
|
||||
break;
|
||||
default:
|
||||
finishFailure({ kind: 'generic' });
|
||||
}
|
||||
} finally {
|
||||
sendingRef.current = false;
|
||||
if (tokenRef.current.captcha !== null) {
|
||||
// A captcha response is single-use: the site resets its widget after every attempt.
|
||||
setCaptchaToken(null);
|
||||
setCaptchaResetCount((count) => count + 1);
|
||||
}
|
||||
}
|
||||
}, [
|
||||
attempt,
|
||||
finishFailure,
|
||||
focusFirstInvalid,
|
||||
honeypot,
|
||||
onEvent,
|
||||
setCaptchaToken,
|
||||
state.status,
|
||||
state.values,
|
||||
]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
keyRef.current = null;
|
||||
setFailure(null);
|
||||
setHoneypot('');
|
||||
dispatch({ type: 'reset' });
|
||||
}, []);
|
||||
|
||||
const failureMessage = failure
|
||||
? failure.kind === 'rateLimited'
|
||||
? messages.rateLimited(failure.minutes)
|
||||
: failure.kind === 'tooLarge'
|
||||
? messages.tooLarge
|
||||
: failure.kind === 'captchaRequired'
|
||||
? messages.captchaRequired
|
||||
: messages.failed(fallbackAddress)
|
||||
: null;
|
||||
|
||||
const getFieldProps = (field: ContactField) => {
|
||||
const code = state.errors[field];
|
||||
const errorId = `${fieldId(field)}-error`;
|
||||
return {
|
||||
/** Spread onto the input/select/textarea. */
|
||||
inputProps: {
|
||||
id: fieldId(field),
|
||||
name: field,
|
||||
value: state.values[field],
|
||||
onChange: (
|
||||
event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
|
||||
) => dispatch({ type: 'change', field, value: event.target.value }),
|
||||
onBlur: () => dispatch({ type: 'blur', field }),
|
||||
'aria-invalid': code ? (true as const) : undefined,
|
||||
'aria-describedby': code ? errorId : undefined,
|
||||
required: true,
|
||||
disabled: state.status === 'sending',
|
||||
},
|
||||
errorId,
|
||||
error: code ? fieldErrorMessage(messages, field, code) : null,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
status: state.status,
|
||||
values: state.values,
|
||||
failureMessage,
|
||||
getFieldProps,
|
||||
honeypotProps: {
|
||||
id: `${idPrefix}-hp`,
|
||||
name: `${idPrefix}-hp`,
|
||||
value: honeypot,
|
||||
onChange: (event: ChangeEvent<HTMLInputElement>) => setHoneypot(event.target.value),
|
||||
tabIndex: -1,
|
||||
autoComplete: 'off',
|
||||
'aria-hidden': true as const,
|
||||
},
|
||||
formProps: {
|
||||
noValidate: true as const,
|
||||
onSubmit: (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
},
|
||||
},
|
||||
retry: submit,
|
||||
reset,
|
||||
messages,
|
||||
/** Captcha the server asked for (null = none). The site renders the widget. */
|
||||
captcha: token.captcha,
|
||||
captchaRequired: token.captcha !== null,
|
||||
captchaToken,
|
||||
/** Call with the widget response when solved, and with null when it expires or errors. */
|
||||
setCaptchaToken,
|
||||
/** Increments after every attempt; the site resets its widget when it changes. */
|
||||
captchaResetCount,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
CONTACT_LIMITS,
|
||||
type ContactErrorCode,
|
||||
type ContactField,
|
||||
type ContactFieldErrors,
|
||||
type ContactFields,
|
||||
} from './types';
|
||||
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
// C0 controls and DEL; line breaks and tabs are allowed in the message only.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CONTROL = /[\u0000-\u001f\u007f]/;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CONTROL_EXCEPT_WHITESPACE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
||||
|
||||
export function trimFields(values: ContactFields): ContactFields {
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
email: values.email.trim(),
|
||||
subject: values.subject.trim(),
|
||||
message: values.message.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function check(field: ContactField, value: string): ContactErrorCode | undefined {
|
||||
if (value.length === 0) {
|
||||
return 'required';
|
||||
}
|
||||
if (value.length > CONTACT_LIMITS[field]) {
|
||||
return 'tooLong';
|
||||
}
|
||||
if (field === 'email' && !EMAIL.test(value)) {
|
||||
return 'invalid';
|
||||
}
|
||||
const control = field === 'message' ? CONTROL_EXCEPT_WHITESPACE : CONTROL;
|
||||
if (control.test(value)) {
|
||||
return 'invalid';
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure validation with the same rules as the API: values are trimmed first; per field the first
|
||||
* failing rule wins (required, then length, then format).
|
||||
*/
|
||||
export function validateContact(values: ContactFields): ContactFieldErrors {
|
||||
const trimmed = trimFields(values);
|
||||
const errors: ContactFieldErrors = {};
|
||||
for (const field of ['name', 'email', 'subject', 'message'] as const) {
|
||||
const code = check(field, trimmed[field]);
|
||||
if (code) {
|
||||
errors[field] = code;
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function hasErrors(errors: ContactFieldErrors): boolean {
|
||||
return Object.keys(errors).length > 0;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Builds an API URL. `VITE_API_BASE_URL` is a local-development override only; on test and
|
||||
* production the path stays relative so it resolves against the origin that served the app.
|
||||
*/
|
||||
export function apiUrl(path: string, baseUrl?: string): string {
|
||||
const base = baseUrl ?? import.meta.env.VITE_API_BASE_URL ?? '';
|
||||
return `${base}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { TransportError } from './problem';
|
||||
|
||||
export interface JsonResponse {
|
||||
status: number;
|
||||
/** Parsed JSON body, or `null` when empty or not JSON. */
|
||||
body: unknown;
|
||||
retryAfter: string | null;
|
||||
}
|
||||
|
||||
export const REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* `fetch` with a timeout. Resolves with any HTTP answer (also 4xx/5xx); rejects with a
|
||||
* `TransportError` only when there is no answer at all. Request and response bodies are never
|
||||
* logged.
|
||||
*/
|
||||
export async function fetchJson(
|
||||
fetchImpl: typeof fetch,
|
||||
url: string,
|
||||
init: RequestInit = {},
|
||||
timeoutMs: number = REQUEST_TIMEOUT_MS,
|
||||
): Promise<JsonResponse> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetchImpl(url, { ...init, signal: controller.signal });
|
||||
let body: unknown = null;
|
||||
try {
|
||||
const text = await response.text();
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
return { status: response.status, body, retryAfter: response.headers.get('Retry-After') };
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
throw new TransportError('timeout');
|
||||
}
|
||||
void error;
|
||||
throw new TransportError('network');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/** Parsed `application/problem+json` answer of the CMS API (errors = field -> codes). */
|
||||
export interface ApiProblem {
|
||||
status: number;
|
||||
errors: Record<string, string[]>;
|
||||
/** Value of the Retry-After header in seconds, if present and numeric. */
|
||||
retryAfterSeconds: number | null;
|
||||
}
|
||||
|
||||
export type TransportFailure = 'network' | 'timeout';
|
||||
|
||||
/** Thrown by `fetchJson` when no HTTP answer was received. */
|
||||
export class TransportError extends Error {
|
||||
readonly kind: TransportFailure;
|
||||
|
||||
constructor(kind: TransportFailure) {
|
||||
super(kind);
|
||||
this.kind = kind;
|
||||
this.name = 'TransportError';
|
||||
}
|
||||
}
|
||||
|
||||
function toErrors(value: unknown): Record<string, string[]> {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return {};
|
||||
}
|
||||
const result: Record<string, string[]> = {};
|
||||
for (const [field, codes] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (Array.isArray(codes)) {
|
||||
result[field] = codes.filter((code): code is string => typeof code === 'string');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function parseRetryAfter(header: string | null): number | null {
|
||||
if (header === null) {
|
||||
return null;
|
||||
}
|
||||
const seconds = Number(header);
|
||||
return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
|
||||
}
|
||||
|
||||
/** Never throws: anything that is not the expected shape yields an empty `errors` map. */
|
||||
export function parseProblem(status: number, body: unknown, retryAfter: string | null): ApiProblem {
|
||||
const errors =
|
||||
body && typeof body === 'object' ? toErrors((body as { errors?: unknown }).errors) : {};
|
||||
return { status, errors, retryAfterSeconds: parseRetryAfter(retryAfter) };
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Box } from '@chakra-ui/react';
|
||||
import type { WidgetHandle } from '@friendlycaptcha/sdk';
|
||||
import type { CaptchaInfo } from '@/cms-client/contact';
|
||||
|
||||
// Room kept for the widget, so nothing below it jumps when it appears
|
||||
export const CAPTCHA_HEIGHT = '76px';
|
||||
|
||||
type CaptchaWidgetProps = {
|
||||
captcha: CaptchaInfo;
|
||||
// Goes up after every send attempt: a response can be used only once, so
|
||||
// the widget starts over
|
||||
resetCount: number;
|
||||
// The response when solved, null when it expired or failed
|
||||
onToken: (token: string | null) => void;
|
||||
};
|
||||
|
||||
// The Friendly Captcha v2 widget (the bundled @friendlycaptcha/sdk). Client
|
||||
// only: it is a separate chunk that loads when the form is open and needs a
|
||||
// captcha, never part of the prerendered page. The visitor starts it by
|
||||
// focusing the form (startMode "focus"). The API region comes from the
|
||||
// server (token response), not from the site.
|
||||
export default function CaptchaWidget({
|
||||
captcha,
|
||||
resetCount,
|
||||
onToken,
|
||||
}: CaptchaWidgetProps) {
|
||||
const element = useRef<HTMLDivElement>(null);
|
||||
const widget = useRef<WidgetHandle | null>(null);
|
||||
const latestOnToken = useRef(onToken);
|
||||
useEffect(() => {
|
||||
latestOnToken.current = onToken;
|
||||
}, [onToken]);
|
||||
|
||||
const { siteKey, apiEndpoint } = captcha;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let handle: WidgetHandle | null = null;
|
||||
import('@friendlycaptcha/sdk').then(({ FriendlyCaptchaSDK }) => {
|
||||
if (cancelled || !element.current) return;
|
||||
const sdk = new FriendlyCaptchaSDK({ apiEndpoint });
|
||||
handle = sdk.createWidget({
|
||||
element: element.current,
|
||||
sitekey: siteKey,
|
||||
language: 'nl',
|
||||
theme: 'light',
|
||||
startMode: 'focus',
|
||||
});
|
||||
widget.current = handle;
|
||||
handle.addEventListener('frc:widget.complete', (event) =>
|
||||
latestOnToken.current(event.detail.response),
|
||||
);
|
||||
handle.addEventListener('frc:widget.expire', () =>
|
||||
latestOnToken.current(null),
|
||||
);
|
||||
handle.addEventListener('frc:widget.error', () =>
|
||||
latestOnToken.current(null),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
handle?.destroy();
|
||||
widget.current = null;
|
||||
};
|
||||
}, [siteKey, apiEndpoint]);
|
||||
|
||||
// A used response is gone: start the widget over after each attempt
|
||||
useEffect(() => {
|
||||
if (resetCount === 0) return;
|
||||
widget.current?.reset();
|
||||
latestOnToken.current(null);
|
||||
}, [resetCount]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
ref={element}
|
||||
minH={CAPTCHA_HEIGHT}
|
||||
data-testid="contact-form-captcha"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,89 @@
|
||||
import { useState } from 'react';
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type {
|
||||
CaptchaInfo,
|
||||
ContactClient,
|
||||
ContactToken,
|
||||
SubmitResult,
|
||||
} from '@/cms-client/contact';
|
||||
import packages from '@/content/packages';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import { shootOptions } from '@/lib/shootOptions';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import ContactForm from './ContactForm';
|
||||
import ContactForm, { type FormAvailability } from './ContactForm';
|
||||
|
||||
// A stand-in for the Friendly Captcha SDK: widgets the test can solve,
|
||||
// expire and watch
|
||||
const sdk = vi.hoisted(() => {
|
||||
type Listener = (event: { detail: { response: string } }) => void;
|
||||
class FakeWidget {
|
||||
listeners = new Map<string, Listener>();
|
||||
reset = vi.fn();
|
||||
destroy = vi.fn();
|
||||
options: Record<string, unknown>;
|
||||
constructor(options: Record<string, unknown>) {
|
||||
this.options = options;
|
||||
}
|
||||
addEventListener(type: string, listener: Listener) {
|
||||
this.listeners.set(type, listener);
|
||||
}
|
||||
emit(type: string, response = '') {
|
||||
this.listeners.get(type)?.({ detail: { response } });
|
||||
}
|
||||
}
|
||||
const state = {
|
||||
widgets: [] as FakeWidget[],
|
||||
sdkOptions: [] as unknown[],
|
||||
};
|
||||
class FriendlyCaptchaSDK {
|
||||
constructor(options: unknown) {
|
||||
state.sdkOptions.push(options);
|
||||
}
|
||||
createWidget(options: Record<string, unknown>) {
|
||||
const widget = new FakeWidget(options);
|
||||
state.widgets.push(widget);
|
||||
return widget;
|
||||
}
|
||||
}
|
||||
return { state, FriendlyCaptchaSDK };
|
||||
});
|
||||
vi.mock('@friendlycaptcha/sdk', () => ({
|
||||
FriendlyCaptchaSDK: sdk.FriendlyCaptchaSDK,
|
||||
}));
|
||||
|
||||
const options = shootOptions(packages);
|
||||
const CAPTCHA: CaptchaInfo = {
|
||||
provider: 'friendlycaptcha',
|
||||
siteKey: 'FCMTEST',
|
||||
apiEndpoint: 'global',
|
||||
};
|
||||
|
||||
// The time check needs over 3 s between showing and sending (BR-SPAM-01)
|
||||
let now = 0;
|
||||
const tokenWith = (captcha: CaptchaInfo | null): ContactToken => ({
|
||||
token: 'signed-token',
|
||||
minSeconds: 3,
|
||||
captcha,
|
||||
});
|
||||
|
||||
let submit: ReturnType<typeof vi.fn>;
|
||||
let refreshToken: ReturnType<typeof vi.fn>;
|
||||
let client: ContactClient;
|
||||
beforeEach(() => {
|
||||
now = 0;
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
sdk.state.widgets.length = 0;
|
||||
sdk.state.sdkOptions.length = 0;
|
||||
submit = vi.fn().mockResolvedValue({ kind: 'ok' } satisfies SubmitResult);
|
||||
refreshToken = vi.fn().mockResolvedValue({ kind: 'failed' });
|
||||
client = {
|
||||
getToken: vi.fn(),
|
||||
submit: submit as unknown as ContactClient['submit'],
|
||||
};
|
||||
});
|
||||
|
||||
const open = (captcha: CaptchaInfo | null = null): FormAvailability => ({
|
||||
token: tokenWith(captcha),
|
||||
refreshToken: refreshToken as unknown as FormAvailability['refreshToken'],
|
||||
});
|
||||
|
||||
const renderForm = (
|
||||
@@ -25,10 +93,10 @@ const renderForm = (
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
submit={vi.fn().mockResolvedValue(undefined)}
|
||||
availability={open()}
|
||||
client={client}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
@@ -39,13 +107,10 @@ const type = (name: string, value: string) =>
|
||||
const fillIn = () => {
|
||||
type('naam', 'Demi');
|
||||
type('email', 'demi@example.nl');
|
||||
type('shoot', 'newborn');
|
||||
type('shoot', 'Newborn');
|
||||
type('bericht', 'Wanneer heb je plek?');
|
||||
};
|
||||
const send = () => {
|
||||
now = 10_000;
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
};
|
||||
const send = () => fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
|
||||
describe('ContactForm', () => {
|
||||
it('shows the four labelled fields and the button', async () => {
|
||||
@@ -65,67 +130,59 @@ describe('ContactForm', () => {
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
it('shows nothing when tabbing through an untouched field', async () => {
|
||||
it('offers the package names and Overig as shoots, the label being the value', async () => {
|
||||
await renderForm();
|
||||
fireEvent.blur(field('naam'));
|
||||
expect(screen.queryByText('Vul je naam in.')).toBeNull();
|
||||
});
|
||||
|
||||
it('checks a field on leaving once typed in, and clears it once fine', async () => {
|
||||
await renderForm();
|
||||
type('email', 'demi@');
|
||||
fireEvent.blur(field('email'));
|
||||
expect(
|
||||
screen.getByText('Dit e-mailadres is ongeldig.'),
|
||||
).toBeInTheDocument();
|
||||
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
|
||||
|
||||
type('email', 'demi@example.nl');
|
||||
expect(screen.queryByText('Dit e-mailadres is ongeldig.')).toBeNull();
|
||||
const values = [...field('shoot').querySelectorAll('option')].map(
|
||||
(option) => option.getAttribute('value'),
|
||||
);
|
||||
expect(values).toEqual([
|
||||
'',
|
||||
...packages.map((pkg) => pkg.name),
|
||||
'Overig',
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops an incomplete submit and focuses the first invalid field', async () => {
|
||||
const submit = vi.fn();
|
||||
await renderForm({ submit });
|
||||
await renderForm();
|
||||
type('naam', 'Demi');
|
||||
send();
|
||||
expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Kies een soort shoot.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Kies een onderwerp.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument();
|
||||
expect(field('email')).toHaveFocus();
|
||||
await waitFor(() => expect(field('email')).toHaveFocus());
|
||||
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends the trimmed form and shows the thank-you with focus', async () => {
|
||||
const submit = vi.fn().mockResolvedValue(undefined);
|
||||
await renderForm({ submit });
|
||||
it('sends the trimmed form with the token and the label as subject', async () => {
|
||||
await renderForm();
|
||||
fillIn();
|
||||
type('naam', ' Demi ');
|
||||
send();
|
||||
expect(screen.getByTestId('contact-form-submit')).toHaveTextContent(
|
||||
'Versturen…',
|
||||
);
|
||||
expect(submit).toHaveBeenCalledWith({
|
||||
naam: 'Demi',
|
||||
await screen.findByTestId('contact-form-sent');
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
const [payload, context] = submit.mock.calls[0];
|
||||
expect(payload).toEqual({
|
||||
name: 'Demi',
|
||||
email: 'demi@example.nl',
|
||||
shoot: 'newborn',
|
||||
bericht: 'Wanneer heb je plek?',
|
||||
subject: 'Newborn',
|
||||
message: 'Wanneer heb je plek?',
|
||||
hpCheck: '',
|
||||
token: 'signed-token',
|
||||
});
|
||||
const thanks = await screen.findByTestId('contact-form-sent');
|
||||
expect(thanks).toHaveTextContent(
|
||||
'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.',
|
||||
);
|
||||
await waitFor(() => expect(thanks).toHaveFocus());
|
||||
expect(screen.queryByTestId('contact-form')).toBeNull();
|
||||
expect(context.idempotencyKey).toMatch(/^[0-9a-f-]{36}$/);
|
||||
});
|
||||
|
||||
it('takes the reply time for the thank-you from the content', async () => {
|
||||
it('shows the thank-you with focus and takes the reply time from the content', async () => {
|
||||
await renderForm({ replyTime: '3 werkdagen' });
|
||||
fillIn();
|
||||
send();
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-sent'),
|
||||
).toHaveTextContent('Ik reageer binnen 3 werkdagen.');
|
||||
const thanks = await screen.findByTestId('contact-form-sent');
|
||||
expect(thanks).toHaveTextContent(
|
||||
'Bedankt voor je bericht! Ik reageer binnen 3 werkdagen.',
|
||||
);
|
||||
await waitFor(() => expect(thanks).toHaveFocus());
|
||||
expect(screen.queryByTestId('contact-form')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the privacy line under the submit button', async () => {
|
||||
@@ -137,65 +194,62 @@ describe('ContactForm', () => {
|
||||
).toHaveAttribute('href', '/privacyverklaring');
|
||||
});
|
||||
|
||||
it('keeps the input and offers the mail link when sending fails', async () => {
|
||||
await renderForm({ submit: vi.fn().mockRejectedValue(new Error('x')) });
|
||||
it('keeps the input and names the address when sending fails', async () => {
|
||||
submit.mockResolvedValue({ kind: 'failed' });
|
||||
await renderForm();
|
||||
fillIn();
|
||||
send();
|
||||
const status = await screen.findByRole('alert');
|
||||
expect(status).toHaveTextContent(
|
||||
'Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl',
|
||||
);
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'info@andreaslop.nl' }),
|
||||
).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
);
|
||||
expect(field('naam')).toHaveValue('Demi');
|
||||
expect(screen.getByTestId('contact-form-submit')).not.toBeDisabled();
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByTestId('contact-form-submit'),
|
||||
).not.toBeDisabled(),
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the text of the package for a rate limit (minutes from Retry-After)', async () => {
|
||||
submit.mockResolvedValue({
|
||||
kind: 'rateLimited',
|
||||
retryAfterSeconds: 120,
|
||||
});
|
||||
await renderForm();
|
||||
fillIn();
|
||||
send();
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Je hebt net al een bericht gestuurd. Probeer het over 2 minuten opnieuw.',
|
||||
);
|
||||
});
|
||||
|
||||
it('treats a filled honeypot as spam: thank-you, nothing sent', async () => {
|
||||
const submit = vi.fn();
|
||||
const { container } = await renderForm({ submit });
|
||||
const { container } = await renderForm();
|
||||
fillIn();
|
||||
fireEvent.change(
|
||||
container.querySelector('input[name="website"]') as Element,
|
||||
{ target: { value: 'https://spam.example' } },
|
||||
);
|
||||
fireEvent.change(container.querySelector('input[name="test-hp"]')!, {
|
||||
target: { value: 'https://spam.example' },
|
||||
});
|
||||
send();
|
||||
expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument();
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-sent'),
|
||||
).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats a submit within 3 seconds as spam', async () => {
|
||||
const submit = vi.fn();
|
||||
await renderForm({ submit });
|
||||
fillIn();
|
||||
now = 1_000;
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
it('keeps the honeypot away from people and assistive technology', async () => {
|
||||
const { container } = await renderForm();
|
||||
const honeypot = container.querySelector('input[name="test-hp"]');
|
||||
expect(honeypot).toHaveAttribute('tabindex', '-1');
|
||||
expect(honeypot).toHaveAttribute('autocomplete', 'off');
|
||||
expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('ignores a second submit while sending', async () => {
|
||||
let finish = () => {};
|
||||
const submit = vi.fn(
|
||||
() => new Promise<void>((resolve) => (finish = resolve)),
|
||||
);
|
||||
await renderForm({ submit });
|
||||
fillIn();
|
||||
send();
|
||||
fireEvent.click(screen.getByTestId('contact-form-submit'));
|
||||
expect(submit).toHaveBeenCalledTimes(1);
|
||||
await act(async () => finish());
|
||||
});
|
||||
|
||||
it('takes over a preselected package, also again after a change', async () => {
|
||||
it('applies a choice made before the form existed, and later clicks too', async () => {
|
||||
// A second "Boek" click for the same package raises the key
|
||||
function Harness() {
|
||||
const [preselect, setPreselect] = useState({
|
||||
shoot: 'newborn',
|
||||
subject: 'Newborn',
|
||||
key: 1,
|
||||
});
|
||||
return (
|
||||
@@ -212,44 +266,142 @@ describe('ContactForm', () => {
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
preselect={preselect}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
availability={open()}
|
||||
client={client}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
await renderWithProviders(<Harness />);
|
||||
expect(field('shoot')).toHaveValue('newborn');
|
||||
type('shoot', 'gezin');
|
||||
expect(field('shoot')).toHaveValue('gezin');
|
||||
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
|
||||
type('shoot', 'Gezin');
|
||||
expect(field('shoot')).toHaveValue('Gezin');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'nog eens' }));
|
||||
expect(field('shoot')).toHaveValue('newborn');
|
||||
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
|
||||
});
|
||||
|
||||
it('keeps the honeypot away from people and assistive technology', async () => {
|
||||
const { container } = await renderForm();
|
||||
const honeypot = container.querySelector('input[name="website"]');
|
||||
expect(honeypot).toHaveAttribute('tabindex', '-1');
|
||||
expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-robot-check]')).not.toBeNull();
|
||||
it('sends a label with special characters unchanged', async () => {
|
||||
const special = `Zwanger & "mooi" <b>'s`;
|
||||
await renderForm({
|
||||
options: [{ value: special, label: special }],
|
||||
});
|
||||
type('naam', 'Demi');
|
||||
type('email', 'demi@example.nl');
|
||||
type('shoot', special);
|
||||
type('bericht', 'Hoi');
|
||||
send();
|
||||
await screen.findByTestId('contact-form-sent');
|
||||
expect(submit.mock.calls[0][0].subject).toBe(special);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm with a captcha', () => {
|
||||
const lastWidget = () => sdk.state.widgets[sdk.state.widgets.length - 1];
|
||||
const widget = async () => {
|
||||
await waitFor(() => expect(sdk.state.widgets).toHaveLength(1));
|
||||
return lastWidget();
|
||||
};
|
||||
|
||||
it('mounts the widget with the key and region from the server', async () => {
|
||||
await renderForm({
|
||||
availability: open({ ...CAPTCHA, apiEndpoint: 'eu' }),
|
||||
});
|
||||
const created = await widget();
|
||||
expect(created.options).toMatchObject({
|
||||
sitekey: 'FCMTEST',
|
||||
language: 'nl',
|
||||
startMode: 'focus',
|
||||
});
|
||||
expect(sdk.state.sdkOptions[0]).toEqual({ apiEndpoint: 'eu' });
|
||||
expect(screen.getByTestId('contact-form-captcha')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sends nothing and says so until the captcha is solved', async () => {
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
await widget();
|
||||
fillIn();
|
||||
send();
|
||||
expect(
|
||||
await screen.findByText('Bevestig eerst dat je geen robot bent.'),
|
||||
).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends the solved response with the form', async () => {
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
fillIn();
|
||||
act(() => created.emit('frc:widget.complete', 'solved-response'));
|
||||
send();
|
||||
await screen.findByTestId('contact-form-sent');
|
||||
expect(submit.mock.calls[0][0].captchaToken).toBe('solved-response');
|
||||
});
|
||||
|
||||
it('never sends an expired response', async () => {
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
fillIn();
|
||||
act(() => created.emit('frc:widget.complete', 'old-response'));
|
||||
act(() => created.emit('frc:widget.expire', '.EXPIRED'));
|
||||
send();
|
||||
expect(
|
||||
await screen.findByText('Bevestig eerst dat je geen robot bent.'),
|
||||
).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never sends a response of a failed widget', async () => {
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
fillIn();
|
||||
act(() => created.emit('frc:widget.complete', 'a-response'));
|
||||
act(() => created.emit('frc:widget.error', '.ERROR'));
|
||||
send();
|
||||
await screen.findByText('Bevestig eerst dat je geen robot bent.');
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resets the widget after a send attempt (a response is single-use)', async () => {
|
||||
submit.mockResolvedValue({ kind: 'failed' });
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
fillIn();
|
||||
act(() => created.emit('frc:widget.complete', 'r1'));
|
||||
send();
|
||||
await screen.findByRole('alert');
|
||||
await waitFor(() => expect(created.reset).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('destroys the widget when the form goes away', async () => {
|
||||
const { unmount } = await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
unmount();
|
||||
expect(created.destroy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows no widget without a captcha', async () => {
|
||||
await renderForm();
|
||||
expect(screen.queryByTestId('contact-form-captcha')).toBeNull();
|
||||
expect(sdk.state.widgets).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm in the prerendered HTML', () => {
|
||||
it('does not hold the address (BR-MAIL-06)', async () => {
|
||||
it('does not hold the address, a token or a widget (BR-MAIL-06)', async () => {
|
||||
const html = await serverHtml(
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
submit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('contact-form-submit');
|
||||
expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
|
||||
expect(html).not.toContain('mailto:');
|
||||
expect(html).not.toContain('signed-token');
|
||||
expect(html).not.toContain('contact-form-captcha');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useEffect, useRef, useState, useReducer } from 'react';
|
||||
import { lazy, Suspense, useEffect, useRef } from 'react';
|
||||
import {
|
||||
Box,
|
||||
chakra,
|
||||
Field,
|
||||
Input,
|
||||
Link,
|
||||
NativeSelect,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
@@ -13,89 +12,107 @@ import {
|
||||
useRecipe,
|
||||
} from '@chakra-ui/react';
|
||||
import PrivacyNote from '@/components/PrivacyNote/PrivacyNote';
|
||||
import { submitContactForm } from '@/contact/submitContactForm';
|
||||
import {
|
||||
CONTACT_LIMITS,
|
||||
useContactForm,
|
||||
type ContactClient,
|
||||
type ContactField,
|
||||
type ContactPayload,
|
||||
type ShootOption,
|
||||
} from '@/contact/types';
|
||||
type ContactToken,
|
||||
type SubjectOption,
|
||||
type TokenResult,
|
||||
} from '@/cms-client/contact';
|
||||
import { contactClient } from '@/contact/contactClient';
|
||||
import type { EmailAddress } from '@/content/types';
|
||||
import {
|
||||
contactFormReducer,
|
||||
INITIAL_CONTACT_STATE,
|
||||
type ContactFormEvent,
|
||||
} from '@/lib/contactFormReducer';
|
||||
import useEmailAddress from '@/hooks/useEmailAddress';
|
||||
import { mailtoLink } from '@/lib/mailLink';
|
||||
import { toContactPayload } from '@/lib/toContactPayload';
|
||||
import { CONTACT_FIELDS } from '@/lib/validateContact';
|
||||
import { trackContactEvent } from '@/lib/trackEvent';
|
||||
import { CAPTCHA_HEIGHT } from './CaptchaWidget';
|
||||
|
||||
// What the form needs once the server said it is open
|
||||
export type FormAvailability = {
|
||||
token: ContactToken;
|
||||
refreshToken: () => Promise<TokenResult>;
|
||||
};
|
||||
|
||||
// Behind the gate the form is only a dimmed picture (inert), so it needs no
|
||||
// real token and never sends anything
|
||||
// The widget is its own chunk (SDK included), loaded only when needed
|
||||
const CaptchaWidget = lazy(() => import('./CaptchaWidget'));
|
||||
|
||||
const PREVIEW_AVAILABILITY: FormAvailability = {
|
||||
token: { token: '', minSeconds: 0, captcha: null },
|
||||
refreshToken: async () => ({ kind: 'failed' }),
|
||||
};
|
||||
|
||||
type ContactFormProps = {
|
||||
// Prefix for the field ids, so the form can appear on more than one page
|
||||
idPrefix: string;
|
||||
options: ShootOption[];
|
||||
// A package chosen via "Boek ..."; key changes on every click, so the
|
||||
// same package can be applied again after the visitor changed it
|
||||
preselect?: { shoot: string; key: number };
|
||||
mailSubject: string;
|
||||
// Value and label are the same text: the label is what is sent as subject
|
||||
options: SubjectOption[];
|
||||
// A package chosen via "Boek ..." (its label); key changes on every
|
||||
// click, so the same package can be applied again after a change
|
||||
preselect?: { subject: string; key: number };
|
||||
email: EmailAddress;
|
||||
// How soon Andrea answers, e.g. '1-2 werkdagen' (siteContent)
|
||||
replyTime: string;
|
||||
submit?: (payload: ContactPayload) => Promise<void>;
|
||||
// Null while the form is only shown behind the gate
|
||||
availability?: FormAvailability | null;
|
||||
client?: ContactClient;
|
||||
};
|
||||
|
||||
// The test ids keep the Dutch field names of the page; the package fields
|
||||
// are English
|
||||
const FIELD_TEST_ID: Record<ContactField, string> = {
|
||||
name: 'naam',
|
||||
email: 'email',
|
||||
subject: 'shoot',
|
||||
message: 'bericht',
|
||||
};
|
||||
|
||||
// The contact form (design .form): name and e-mail, the shoot, the question,
|
||||
// and the browser-side anti-spam. Its behaviour is the pure
|
||||
// contactFormReducer; this component wires it to the fields.
|
||||
// and the browser-side honeypot. Its behaviour (validation, sending, token
|
||||
// refresh) is the headless useContactForm of the cms-client package; this
|
||||
// component is only the skin.
|
||||
export default function ContactForm({
|
||||
idPrefix,
|
||||
options,
|
||||
preselect,
|
||||
mailSubject,
|
||||
email,
|
||||
replyTime,
|
||||
submit = submitContactForm,
|
||||
availability = null,
|
||||
client = contactClient,
|
||||
}: ContactFormProps) {
|
||||
const reduce = (
|
||||
state: typeof INITIAL_CONTACT_STATE,
|
||||
event: ContactFormEvent,
|
||||
) => contactFormReducer(state, event, options);
|
||||
const [state, dispatch] = useReducer(reduce, INITIAL_CONTACT_STATE);
|
||||
const formControl = useRecipe({ key: 'formControl' });
|
||||
const linkButton = useRecipe({ key: 'linkButton' });
|
||||
|
||||
// When the form became usable, for the time check (BR-SPAM-01)
|
||||
const [shownAt] = useState(() => Date.now());
|
||||
const honeypot = useRef<HTMLInputElement>(null);
|
||||
const { address } = useEmailAddress(email);
|
||||
const sentMessage = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Apply a new "Boek ..." choice while rendering (React's pattern for
|
||||
// reacting to a changed prop), so it never shows a stale value first
|
||||
const [seenPreselect, setSeenPreselect] = useState(0);
|
||||
if (preselect && preselect.key !== seenPreselect) {
|
||||
setSeenPreselect(preselect.key);
|
||||
dispatch({ type: 'preselect', shoot: preselect.shoot });
|
||||
}
|
||||
|
||||
// After a stopped submit, focus the first field with an error
|
||||
useEffect(() => {
|
||||
if (state.invalidSubmits === 0) return;
|
||||
const first = CONTACT_FIELDS.find((field) => state.errors[field]);
|
||||
if (first) document.getElementById(`${idPrefix}-${first}`)?.focus();
|
||||
// Only on a new stopped submit, not on every error change
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state.invalidSubmits]);
|
||||
const { token, refreshToken } = availability ?? PREVIEW_AVAILABILITY;
|
||||
const form = useContactForm({
|
||||
idPrefix,
|
||||
subjectOptions: options,
|
||||
// A choice made before the form existed is applied at the start,
|
||||
// later clicks through the changing key
|
||||
preselect,
|
||||
initialSubject: preselect?.subject ?? null,
|
||||
client,
|
||||
token,
|
||||
refreshToken,
|
||||
fallbackAddress: address ?? '',
|
||||
onEvent: (event) =>
|
||||
trackContactEvent(
|
||||
event === 'sent' ? 'contact-sent' : 'contact-failed',
|
||||
),
|
||||
});
|
||||
|
||||
// The thank-you replaces the form; move focus there (BR-SEND-02)
|
||||
const { status } = form;
|
||||
useEffect(() => {
|
||||
if (state.status === 'sent') sentMessage.current?.focus();
|
||||
}, [state.status]);
|
||||
if (status === 'sent') sentMessage.current?.focus();
|
||||
}, [status]);
|
||||
|
||||
const { address } = useEmailAddress(email);
|
||||
const disabled = state.status === 'sending';
|
||||
const disabled = status === 'sending';
|
||||
|
||||
if (state.status === 'sent') {
|
||||
if (status === 'sent') {
|
||||
return (
|
||||
<Box
|
||||
ref={sentMessage}
|
||||
@@ -112,39 +129,14 @@ export default function ContactForm({
|
||||
);
|
||||
}
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const submitEvent: ContactFormEvent = {
|
||||
type: 'submit',
|
||||
honeypot: honeypot.current?.value ?? '',
|
||||
shownAt,
|
||||
now: Date.now(),
|
||||
};
|
||||
// Sending starts here, not in an effect, so it happens exactly once
|
||||
const next = reduce(state, submitEvent);
|
||||
dispatch(submitEvent);
|
||||
if (next.status === 'sending') {
|
||||
submit(toContactPayload(state.values)).then(
|
||||
() => dispatch({ type: 'resolved' }),
|
||||
() => dispatch({ type: 'rejected' }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// The control's id comes from Field.Root's id (Ark uses it for the
|
||||
// control and the label's htmlFor), so label and error stay linked
|
||||
const fieldProps = (field: ContactField) => ({
|
||||
name: field,
|
||||
value: state.values[field],
|
||||
onChange: (
|
||||
event: React.ChangeEvent<
|
||||
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
|
||||
>,
|
||||
) => dispatch({ type: 'edit', field, value: event.target.value }),
|
||||
onBlur: () => dispatch({ type: 'blur', field }),
|
||||
// The control's id comes from the hook (the same id Field.Root gets), so
|
||||
// label, input and error stay linked
|
||||
const control = (field: ContactField) => ({
|
||||
...form.getFieldProps(field).inputProps,
|
||||
css: formControl(),
|
||||
'data-testid': `contact-form-${field}`,
|
||||
'data-testid': `contact-form-${FIELD_TEST_ID[field]}`,
|
||||
});
|
||||
const fieldId = (field: ContactField) => `${idPrefix}-${field}`;
|
||||
|
||||
const label = (text: string) => (
|
||||
// ink.soft instead of the design's muted grey: meets 4.5:1
|
||||
@@ -152,44 +144,49 @@ export default function ContactForm({
|
||||
{text}
|
||||
</Field.Label>
|
||||
);
|
||||
const error = (field: ContactField) => (
|
||||
<Field.ErrorText color="error" fontSize="sm">
|
||||
{state.errors[field]}
|
||||
</Field.ErrorText>
|
||||
);
|
||||
// Outside the label, so the accessible name of the field stays clean
|
||||
const error = (field: ContactField) => {
|
||||
const { error: message, errorId } = form.getFieldProps(field);
|
||||
return (
|
||||
<Field.ErrorText id={errorId} color="error" fontSize="sm">
|
||||
{message}
|
||||
</Field.ErrorText>
|
||||
);
|
||||
};
|
||||
const invalid = (field: ContactField) =>
|
||||
Boolean(form.getFieldProps(field).error);
|
||||
|
||||
return (
|
||||
<chakra.form
|
||||
noValidate
|
||||
onSubmit={onSubmit}
|
||||
{...form.formProps}
|
||||
data-testid="contact-form"
|
||||
position="relative"
|
||||
>
|
||||
<Stack gap={6}>
|
||||
<SimpleGrid columns={{ base: 1, sm: 2 }} gap={6}>
|
||||
<Field.Root
|
||||
invalid={Boolean(state.errors.naam)}
|
||||
invalid={invalid('name')}
|
||||
required
|
||||
id={`${idPrefix}-naam`}
|
||||
id={fieldId('name')}
|
||||
>
|
||||
{label('Naam')}
|
||||
<Input
|
||||
{...fieldProps('naam')}
|
||||
{...control('name')}
|
||||
type="text"
|
||||
autoComplete="name"
|
||||
maxLength={CONTACT_LIMITS.naam}
|
||||
maxLength={CONTACT_LIMITS.name}
|
||||
placeholder="Jouw naam"
|
||||
/>
|
||||
{error('naam')}
|
||||
{error('name')}
|
||||
</Field.Root>
|
||||
<Field.Root
|
||||
invalid={Boolean(state.errors.email)}
|
||||
invalid={invalid('email')}
|
||||
required
|
||||
id={`${idPrefix}-email`}
|
||||
id={fieldId('email')}
|
||||
>
|
||||
{label('E-mail')}
|
||||
<Input
|
||||
{...fieldProps('email')}
|
||||
{...control('email')}
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
maxLength={CONTACT_LIMITS.email}
|
||||
@@ -200,13 +197,13 @@ export default function ContactForm({
|
||||
</SimpleGrid>
|
||||
|
||||
<Field.Root
|
||||
invalid={Boolean(state.errors.shoot)}
|
||||
invalid={invalid('subject')}
|
||||
required
|
||||
id={`${idPrefix}-shoot`}
|
||||
id={fieldId('subject')}
|
||||
>
|
||||
{label('In welke shoot heb je interesse?')}
|
||||
<NativeSelect.Root>
|
||||
<NativeSelect.Field {...fieldProps('shoot')}>
|
||||
<NativeSelect.Field {...control('subject')}>
|
||||
<option value="">Kies een optie...</option>
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
@@ -216,27 +213,27 @@ export default function ContactForm({
|
||||
</NativeSelect.Field>
|
||||
<NativeSelect.Indicator />
|
||||
</NativeSelect.Root>
|
||||
{error('shoot')}
|
||||
{error('subject')}
|
||||
</Field.Root>
|
||||
|
||||
<Field.Root
|
||||
invalid={Boolean(state.errors.bericht)}
|
||||
invalid={invalid('message')}
|
||||
required
|
||||
id={`${idPrefix}-bericht`}
|
||||
id={fieldId('message')}
|
||||
>
|
||||
{label('Stel hier je vraag')}
|
||||
<Textarea
|
||||
{...fieldProps('bericht')}
|
||||
maxLength={CONTACT_LIMITS.bericht}
|
||||
{...control('message')}
|
||||
maxLength={CONTACT_LIMITS.message}
|
||||
placeholder="Vul hier je bericht in"
|
||||
minH="170px"
|
||||
resize="vertical"
|
||||
/>
|
||||
{error('bericht')}
|
||||
{error('message')}
|
||||
</Field.Root>
|
||||
|
||||
{/* Honeypot: off-screen and hidden from assistive
|
||||
technology; only bots fill it in (BR-SPAM-01) */}
|
||||
technology; only bots fill it in */}
|
||||
<Box
|
||||
aria-hidden="true"
|
||||
position="absolute"
|
||||
@@ -245,22 +242,22 @@ export default function ContactForm({
|
||||
h="1px"
|
||||
overflow="hidden"
|
||||
>
|
||||
<label htmlFor={`${idPrefix}-website`}>Website</label>
|
||||
<input
|
||||
ref={honeypot}
|
||||
id={`${idPrefix}-website`}
|
||||
name="website"
|
||||
type="text"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<input {...form.honeypotProps} type="text" />
|
||||
</Box>
|
||||
|
||||
{/* Place for the robot check (Friendly Captcha), added with
|
||||
the API (FR-HP-09) */}
|
||||
<div data-robot-check />
|
||||
{/* The robot check (Friendly Captcha) when the server asks
|
||||
for it; its room is kept while the widget loads */}
|
||||
{form.captcha && (
|
||||
<Suspense fallback={<Box minH={CAPTCHA_HEIGHT} />}>
|
||||
<CaptchaWidget
|
||||
captcha={form.captcha}
|
||||
resetCount={form.captchaResetCount}
|
||||
onToken={form.setCaptchaToken}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{state.status === 'failed' && (
|
||||
{form.failureMessage && (
|
||||
<Box
|
||||
role="alert"
|
||||
data-testid="contact-form-status"
|
||||
@@ -270,22 +267,7 @@ export default function ContactForm({
|
||||
bg="paper.alt"
|
||||
fontSize="sm"
|
||||
>
|
||||
<Text>
|
||||
Versturen lukte niet. Probeer het later nog eens
|
||||
{address ? (
|
||||
<>
|
||||
{' of mail naar '}
|
||||
<Link
|
||||
variant="underline"
|
||||
href={mailtoLink(address, mailSubject)}
|
||||
>
|
||||
{address}
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
'.'
|
||||
)}
|
||||
</Text>
|
||||
<Text>{form.failureMessage}</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -297,7 +279,9 @@ export default function ContactForm({
|
||||
cursor={disabled ? 'progress' : 'pointer'}
|
||||
data-testid="contact-form-submit"
|
||||
>
|
||||
{disabled ? 'Versturen…' : '(Aan)vraag versturen'}
|
||||
{disabled
|
||||
? form.messages.sendingLabel
|
||||
: '(Aan)vraag versturen'}
|
||||
</chakra.button>
|
||||
{/* Under the submit button, aligned with it */}
|
||||
<PrivacyNote textAlign="end" />
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
import { useState } from 'react';
|
||||
import { act, fireEvent, screen } from '@testing-library/react';
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import packages from '@/content/packages';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import type { ContactClient, TokenResult } from '@/cms-client/contact';
|
||||
import ContactPanel from './ContactPanel';
|
||||
|
||||
// A fake CMS contact client; the token answer decides whether the form opens
|
||||
const clientWith = (answer: TokenResult) => ({
|
||||
getToken: vi.fn().mockResolvedValue(answer),
|
||||
submit: vi.fn(),
|
||||
});
|
||||
const OPEN: TokenResult = {
|
||||
kind: 'ok',
|
||||
token: { token: 'signed-token', minSeconds: 3, captcha: null },
|
||||
};
|
||||
const asClient = (client: ReturnType<typeof clientWith>) =>
|
||||
client as unknown as ContactClient;
|
||||
|
||||
type Props = Partial<React.ComponentProps<typeof ContactPanel>>;
|
||||
|
||||
const panel = (props: Props = {}) => (
|
||||
@@ -42,7 +55,9 @@ describe('ContactPanel', () => {
|
||||
});
|
||||
|
||||
it('offers the shown packages and Overig as shoots', async () => {
|
||||
await renderWithProviders(panel({ enabled: true }));
|
||||
await renderWithProviders(
|
||||
panel({ enabled: true, client: asClient(clientWith(OPEN)) }),
|
||||
);
|
||||
const options = [...(await shoot()).querySelectorAll('option')].map(
|
||||
(option) => option.textContent,
|
||||
);
|
||||
@@ -73,12 +88,12 @@ describe('ContactPanel', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
|
||||
FakeIntersectionObserver.reset();
|
||||
await renderWithProviders(panel({ load: 'lazy', pakket: 'newborn' }));
|
||||
expect(await shoot()).toHaveValue('newborn');
|
||||
expect(await shoot()).toHaveValue('Newborn');
|
||||
});
|
||||
|
||||
it('preselects a known package and puts it in the mail subject', async () => {
|
||||
await renderWithProviders(panel({ pakket: ' NEWBORN ' }));
|
||||
expect(await shoot()).toHaveValue('newborn');
|
||||
expect(await shoot()).toHaveValue('Newborn');
|
||||
expect(mailButton()).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Aanvraag%20fotoshoot%3A%20Newborn',
|
||||
@@ -97,28 +112,120 @@ describe('ContactPanel', () => {
|
||||
it('applies the same package again after the visitor changed it', async () => {
|
||||
// The page clears ?pakket= after taking it over; a second "Boek"
|
||||
// click on the same package brings it back
|
||||
const client = asClient(clientWith(OPEN));
|
||||
function Harness() {
|
||||
const [pakket, setPakket] = useState<string | undefined>('newborn');
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setPakket(undefined)}>wis</button>
|
||||
<button onClick={() => setPakket('newborn')}>boek</button>
|
||||
{panel({ enabled: true, pakket })}
|
||||
{panel({
|
||||
enabled: true,
|
||||
pakket,
|
||||
client,
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
await renderWithProviders(<Harness />);
|
||||
fireEvent.change(await shoot(), { target: { value: 'gezin' } });
|
||||
// The form is only usable once the server said it is open
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('contact-gate-notice')).toBeNull(),
|
||||
);
|
||||
fireEvent.change(await shoot(), { target: { value: 'Gezin' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'wis' }));
|
||||
expect(await shoot()).toHaveValue('gezin');
|
||||
expect(await shoot()).toHaveValue('Gezin');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'boek' }));
|
||||
expect(await shoot()).toHaveValue('newborn');
|
||||
expect(await shoot()).toHaveValue('Newborn');
|
||||
});
|
||||
|
||||
it('shows just the form when switched on', async () => {
|
||||
await renderWithProviders(panel({ enabled: true }));
|
||||
await renderWithProviders(
|
||||
panel({ enabled: true, client: asClient(clientWith(OPEN)) }),
|
||||
);
|
||||
await shoot();
|
||||
expect(screen.queryByTestId('contact-gate-notice')).toBeNull();
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('contact-gate-notice')).toBeNull(),
|
||||
);
|
||||
expect(screen.getByTestId('privacy-note')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('availability', () => {
|
||||
const noticeGone = () =>
|
||||
waitFor(() =>
|
||||
expect(screen.queryByTestId('contact-gate-notice')).toBeNull(),
|
||||
);
|
||||
|
||||
it('asks the server nothing while switched off', async () => {
|
||||
const client = clientWith(OPEN);
|
||||
await renderWithProviders(
|
||||
panel({ enabled: false, client: asClient(client) }),
|
||||
);
|
||||
await shoot();
|
||||
expect(client.getToken).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.getByTestId('contact-gate-notice'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('asks the server once when switched on and opens the form on a 200', async () => {
|
||||
const client = clientWith(OPEN);
|
||||
await renderWithProviders(
|
||||
panel({ enabled: true, client: asClient(client) }),
|
||||
);
|
||||
await noticeGone();
|
||||
expect(client.getToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('waits with the request until the form is near the screen when lazy', async () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
|
||||
FakeIntersectionObserver.reset();
|
||||
const client = clientWith(OPEN);
|
||||
await renderWithProviders(
|
||||
panel({
|
||||
enabled: true,
|
||||
load: 'lazy',
|
||||
client: asClient(client),
|
||||
}),
|
||||
);
|
||||
expect(client.getToken).not.toHaveBeenCalled();
|
||||
act(() =>
|
||||
FakeIntersectionObserver.instances.forEach((observer) =>
|
||||
observer.trigger(true),
|
||||
),
|
||||
);
|
||||
await noticeGone();
|
||||
expect(client.getToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the form is closed (404)', { kind: 'closed' } as TokenResult],
|
||||
['the server fails', { kind: 'failed' } as TokenResult],
|
||||
[
|
||||
'the server asks for an unknown captcha',
|
||||
{
|
||||
kind: 'ok',
|
||||
token: {
|
||||
token: 't',
|
||||
minSeconds: 3,
|
||||
captcha: {
|
||||
provider: 'somethingelse',
|
||||
siteKey: 'k',
|
||||
apiEndpoint: 'global',
|
||||
},
|
||||
},
|
||||
} as TokenResult,
|
||||
],
|
||||
])('keeps the gate when %s', async (_name, answer) => {
|
||||
const client = clientWith(answer);
|
||||
await renderWithProviders(
|
||||
panel({ enabled: true, client: asClient(client) }),
|
||||
);
|
||||
await waitFor(() => expect(client.getToken).toHaveBeenCalled());
|
||||
await shoot();
|
||||
expect(
|
||||
screen.getByTestId('contact-gate-notice'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,10 @@ import { lazy, Suspense, useMemo, useState } from 'react';
|
||||
import { Box } from '@chakra-ui/react';
|
||||
import { DEFERRED_LOAD_MARGIN } from '@/components/DeferredImage/DeferredImage';
|
||||
import ContactFormGate from '@/components/ContactForm/ContactFormGate';
|
||||
import type { ContactClient } from '@/cms-client/contact';
|
||||
import { contactClient } from '@/contact/contactClient';
|
||||
import type { EmailAddress, PricingPackage } from '@/content/types';
|
||||
import useContactAvailability from '@/hooks/useContactAvailability';
|
||||
import useInView from '@/hooks/useInView';
|
||||
import { mailSubject } from '@/lib/mailLink';
|
||||
import { packageFromSearch } from '@/lib/packageFromSearch';
|
||||
@@ -31,6 +34,8 @@ type ContactPanelProps = {
|
||||
// lazy: load the form when it comes near the screen or a package is
|
||||
// chosen (homepage); eager: start loading it with the page (contact page)
|
||||
load: 'lazy' | 'eager';
|
||||
// The CMS contact client; tests pass a fake
|
||||
client?: ContactClient;
|
||||
};
|
||||
|
||||
// The contact form, ready to place on a page: the coming-soon gate, the
|
||||
@@ -45,6 +50,7 @@ export default function ContactPanel({
|
||||
replyTime,
|
||||
pakket,
|
||||
load,
|
||||
client = contactClient,
|
||||
}: ContactPanelProps) {
|
||||
const shown = useMemo(() => visiblePackages(packages), [packages]);
|
||||
const options = useMemo(() => shootOptions(packages), [packages]);
|
||||
@@ -52,8 +58,9 @@ export default function ContactPanel({
|
||||
// Take over a new ?pakket= while rendering (React's pattern for a
|
||||
// changed prop); the last "Boek" click wins (BR-PARAM-03)
|
||||
const [seenPakket, setSeenPakket] = useState<string | undefined>();
|
||||
// The label of the package: that text is what the form sends as subject
|
||||
const [preselect, setPreselect] = useState<{
|
||||
shoot: string;
|
||||
subject: string;
|
||||
key: number;
|
||||
}>();
|
||||
const [chosenName, setChosenName] = useState<string>();
|
||||
@@ -61,9 +68,10 @@ export default function ContactPanel({
|
||||
setSeenPakket(pakket);
|
||||
const id =
|
||||
pakket === undefined ? undefined : packageFromSearch(pakket, shown);
|
||||
if (id) {
|
||||
setPreselect({ shoot: id, key: (preselect?.key ?? 0) + 1 });
|
||||
setChosenName(shown.find((pkg) => pkg.id === id)?.name);
|
||||
const name = shown.find((pkg) => pkg.id === id)?.name;
|
||||
if (id && name) {
|
||||
setPreselect({ subject: name, key: (preselect?.key ?? 0) + 1 });
|
||||
setChosenName(name);
|
||||
}
|
||||
}
|
||||
const subject = mailSubject(chosenName);
|
||||
@@ -77,8 +85,18 @@ export default function ContactPanel({
|
||||
if (!formLoaded && (inView || pakket !== undefined)) setFormLoaded(true);
|
||||
const placeholder = <Box minH={FORM_PLACEHOLDER_HEIGHT} />;
|
||||
|
||||
// Only when the form is switched on and near the screen the server is
|
||||
// asked whether it is open (no request at all otherwise, BR-CF-01); the
|
||||
// gate stays until the answer is yes
|
||||
const availability = useContactAvailability(enabled, formLoaded, client);
|
||||
const open = availability.status === 'open';
|
||||
|
||||
return (
|
||||
<ContactFormGate enabled={enabled} email={email} subject={subject}>
|
||||
<ContactFormGate
|
||||
enabled={enabled && open}
|
||||
email={email}
|
||||
subject={subject}
|
||||
>
|
||||
<Box ref={ref}>
|
||||
{formLoaded ? (
|
||||
<Suspense fallback={placeholder}>
|
||||
@@ -86,9 +104,10 @@ export default function ContactPanel({
|
||||
idPrefix={idPrefix}
|
||||
options={options}
|
||||
preselect={preselect}
|
||||
mailSubject={subject}
|
||||
email={email}
|
||||
replyTime={replyTime}
|
||||
availability={open ? availability : null}
|
||||
client={client}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('ContactSection', () => {
|
||||
'newborn',
|
||||
'/?pakket=newborn#contact',
|
||||
);
|
||||
expect(await shoot()).toHaveValue('newborn');
|
||||
expect(await shoot()).toHaveValue('Newborn');
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'Stuur een e-mail' }),
|
||||
).toHaveAttribute(
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createContactClient } from '@/cms-client/contact';
|
||||
|
||||
// The one client for the CMS contact endpoints. Same-origin /api/v1 paths
|
||||
// (production), or the dev proxy when API_PROXY_TARGET is set.
|
||||
export const contactClient = createContactClient();
|
||||
@@ -1,15 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { submitContactForm } from './submitContactForm';
|
||||
|
||||
describe('submitContactForm', () => {
|
||||
it('fails until the API exists', async () => {
|
||||
await expect(
|
||||
submitContactForm({
|
||||
naam: 'Demi',
|
||||
email: 'demi@example.nl',
|
||||
shoot: 'newborn',
|
||||
bericht: 'Hoi!',
|
||||
}),
|
||||
).rejects.toThrow('not available');
|
||||
});
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { ContactPayload } from './types';
|
||||
|
||||
// The one place where the contact form is sent. There is no back-end yet, so
|
||||
// this always fails; the form is switched off (siteContent.contactForm) until
|
||||
// it works. In the API feature this becomes:
|
||||
//
|
||||
// const response = await fetch('/api/contact', {
|
||||
// method: 'POST',
|
||||
// headers: { 'Content-Type': 'application/json' },
|
||||
// body: JSON.stringify({ ...payload, captcha: token }),
|
||||
// });
|
||||
// if (!response.ok) throw new Error(`Contact form: ${response.status}`);
|
||||
//
|
||||
// plus the Friendly Captcha token and the CSP entries it needs (FR-HP-09).
|
||||
// Visitors never see this error's text, only the generic failure message.
|
||||
export async function submitContactForm(
|
||||
payload: ContactPayload,
|
||||
): Promise<void> {
|
||||
void payload;
|
||||
throw new Error('Contact form is not available yet');
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// What the contact form works with. The payload is what POST /api/contact
|
||||
// will receive (plus the robot-check token, added in the API feature).
|
||||
|
||||
export type ContactField = 'naam' | 'email' | 'shoot' | 'bericht';
|
||||
|
||||
// What the visitor typed
|
||||
export type ContactValues = Record<ContactField, string>;
|
||||
|
||||
// At most one message per field
|
||||
export type ContactErrors = Partial<Record<ContactField, string>>;
|
||||
|
||||
// Trimmed values; shoot is a package id or 'overig'
|
||||
export type ContactPayload = Record<ContactField, string>;
|
||||
|
||||
export interface ShootOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
// Maximum lengths; also set as maxLength on the fields (BR-FORM-06)
|
||||
export const CONTACT_LIMITS = {
|
||||
naam: 100,
|
||||
email: 254,
|
||||
bericht: 2000,
|
||||
} as const;
|
||||
|
||||
export const EMPTY_CONTACT: ContactValues = {
|
||||
naam: '',
|
||||
email: '',
|
||||
shoot: '',
|
||||
bericht: '',
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { contactClient } from '@/contact/contactClient';
|
||||
import type {
|
||||
ContactClient,
|
||||
ContactToken,
|
||||
TokenResult,
|
||||
} from '@/cms-client/contact';
|
||||
|
||||
// Captcha providers this site can show. Anything else keeps the gate
|
||||
// (FR-CF-04).
|
||||
export const SUPPORTED_CAPTCHA_PROVIDERS: readonly string[] = [
|
||||
'friendlycaptcha',
|
||||
];
|
||||
|
||||
export type ContactAvailability =
|
||||
| { status: 'idle' | 'checking' | 'closed' }
|
||||
| {
|
||||
status: 'open';
|
||||
token: ContactToken;
|
||||
refreshToken: () => Promise<TokenResult>;
|
||||
};
|
||||
|
||||
const isUsable = (token: ContactToken) =>
|
||||
token.captcha === null ||
|
||||
SUPPORTED_CAPTCHA_PROVIDERS.includes(token.captcha.provider);
|
||||
|
||||
// Asks the server whether the form is open, once, when `active` becomes true
|
||||
// (the form area is near the screen). Without `enabled` nothing is requested
|
||||
// at all (BR-CF-01). The token lives in memory only.
|
||||
export default function useContactAvailability(
|
||||
enabled: boolean,
|
||||
active: boolean,
|
||||
client: ContactClient = contactClient,
|
||||
): ContactAvailability {
|
||||
const [state, setState] = useState<
|
||||
| { status: 'idle' | 'checking' | 'closed' }
|
||||
| {
|
||||
status: 'open';
|
||||
token: ContactToken;
|
||||
}
|
||||
>({ status: 'idle' });
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || started.current) return;
|
||||
started.current = true;
|
||||
let cancelled = false;
|
||||
setState({ status: 'checking' });
|
||||
client.getToken().then((result) => {
|
||||
if (cancelled) return;
|
||||
setState(
|
||||
result.kind === 'ok' && isUsable(result.token)
|
||||
? { status: 'open', token: result.token }
|
||||
: { status: 'closed' },
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
started.current = false;
|
||||
};
|
||||
}, [enabled, active, client]);
|
||||
|
||||
const refreshToken = useCallback(async () => {
|
||||
const result = await client.getToken();
|
||||
if (result.kind === 'ok' && isUsable(result.token)) {
|
||||
setState({ status: 'open', token: result.token });
|
||||
}
|
||||
return result;
|
||||
}, [client]);
|
||||
|
||||
return state.status === 'open'
|
||||
? { status: 'open', token: state.token, refreshToken }
|
||||
: { status: state.status };
|
||||
}
|
||||
@@ -55,7 +55,7 @@ describe('contact ?pakket= on a direct load', () => {
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
).toHaveValue('Newborn');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -67,7 +67,7 @@ describe('homepage ?pakket= on a direct load', () => {
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
).toHaveValue('Newborn');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import packages from '../content/packages';
|
||||
import { contactEvent } from '../test/arbitraries';
|
||||
import {
|
||||
contactFormReducer,
|
||||
INITIAL_CONTACT_STATE,
|
||||
type ContactFormEvent,
|
||||
type ContactFormState,
|
||||
type ContactStatus,
|
||||
} from './contactFormReducer';
|
||||
import { isLikelySpam } from './isLikelySpam';
|
||||
import { shootOptions } from './shootOptions';
|
||||
import { validateContact } from './validateContact';
|
||||
|
||||
const options = shootOptions(packages);
|
||||
const reduce = (state: ContactFormState, event: ContactFormEvent) =>
|
||||
contactFormReducer(state, event, options);
|
||||
const run = (events: ContactFormEvent[]) =>
|
||||
events.reduce(reduce, INITIAL_CONTACT_STATE);
|
||||
|
||||
const fill: ContactFormEvent[] = [
|
||||
{ type: 'edit', field: 'naam', value: 'Demi' },
|
||||
{ type: 'edit', field: 'email', value: 'demi@example.nl' },
|
||||
{ type: 'edit', field: 'shoot', value: 'newborn' },
|
||||
{ type: 'edit', field: 'bericht', value: 'Hoi!' },
|
||||
];
|
||||
const submit: ContactFormEvent = {
|
||||
type: 'submit',
|
||||
honeypot: '',
|
||||
shownAt: 0,
|
||||
now: 10_000,
|
||||
};
|
||||
|
||||
// Which status may follow which, per the state machine in the design
|
||||
const allowed: Record<ContactStatus, ContactStatus[]> = {
|
||||
editing: ['editing', 'sending', 'sent'],
|
||||
sending: ['sending', 'sent', 'failed'],
|
||||
failed: ['failed', 'editing', 'sending', 'sent'],
|
||||
sent: ['sent'],
|
||||
};
|
||||
|
||||
describe('contactFormReducer', () => {
|
||||
it('shows nothing when leaving an untouched field', () => {
|
||||
const state = run([{ type: 'blur', field: 'naam' }]);
|
||||
expect(state.errors).toEqual({});
|
||||
});
|
||||
|
||||
it('checks a field on leaving once it was typed in', () => {
|
||||
const state = run([
|
||||
{ type: 'edit', field: 'email', value: 'demi@' },
|
||||
{ type: 'blur', field: 'email' },
|
||||
]);
|
||||
expect(state.errors).toEqual({
|
||||
email: 'Dit e-mailadres is ongeldig.',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears an error while typing as soon as the field is fine', () => {
|
||||
const state = run([
|
||||
{ type: 'edit', field: 'email', value: 'demi@' },
|
||||
{ type: 'blur', field: 'email' },
|
||||
{ type: 'edit', field: 'email', value: 'demi@example.nl' },
|
||||
]);
|
||||
expect(state.errors).toEqual({});
|
||||
});
|
||||
|
||||
it('stops an invalid submit with all errors and counts it', () => {
|
||||
const state = run([submit]);
|
||||
expect(state.status).toBe('editing');
|
||||
expect(Object.keys(state.errors)).toEqual([
|
||||
'naam',
|
||||
'email',
|
||||
'shoot',
|
||||
'bericht',
|
||||
]);
|
||||
expect(state.invalidSubmits).toBe(1);
|
||||
});
|
||||
|
||||
it('sends a valid form and ends in sent or failed', () => {
|
||||
const sending = run([...fill, submit]);
|
||||
expect(sending.status).toBe('sending');
|
||||
expect(reduce(sending, { type: 'resolved' }).status).toBe('sent');
|
||||
const failed = reduce(sending, { type: 'rejected' });
|
||||
expect(failed.status).toBe('failed');
|
||||
expect(failed.values).toEqual(sending.values);
|
||||
expect(reduce(failed, submit).status).toBe('sending');
|
||||
});
|
||||
|
||||
it('treats spam as sent without sending', () => {
|
||||
expect(run([...fill, { ...submit, honeypot: 'x' }]).status).toBe(
|
||||
'sent',
|
||||
);
|
||||
expect(run([...fill, { ...submit, now: 1000 }]).status).toBe('sent');
|
||||
});
|
||||
|
||||
it('ignores a second submit and edits while sending', () => {
|
||||
const sending = run([...fill, submit]);
|
||||
expect(reduce(sending, submit)).toBe(sending);
|
||||
expect(
|
||||
reduce(sending, { type: 'edit', field: 'naam', value: 'X' }),
|
||||
).toBe(sending);
|
||||
});
|
||||
|
||||
it('changes nothing once sent', () => {
|
||||
const sent = reduce(run([...fill, submit]), { type: 'resolved' });
|
||||
expect(sent.status).toBe('sent');
|
||||
for (const event of [
|
||||
submit,
|
||||
{ type: 'edit', field: 'naam', value: 'X' },
|
||||
{ type: 'rejected' },
|
||||
] as ContactFormEvent[]) {
|
||||
expect(reduce(sent, event)).toBe(sent);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the shoot error when preselecting an unknown value', () => {
|
||||
const state = run([submit, { type: 'preselect', shoot: 'bruiloft' }]);
|
||||
expect(state.values.shoot).toBe('bruiloft');
|
||||
expect(state.errors.shoot).toBe('Kies een soort shoot.');
|
||||
});
|
||||
|
||||
it('preselects a package and clears its error', () => {
|
||||
const state = run([submit, { type: 'preselect', shoot: 'gezin' }]);
|
||||
expect(state.values.shoot).toBe('gezin');
|
||||
expect(state.errors.shoot).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps to the state machine for any sequence of events (stateful)', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(contactEvent, { maxLength: 40 }), (events) => {
|
||||
let state = INITIAL_CONTACT_STATE;
|
||||
let submitted = false;
|
||||
for (const event of events) {
|
||||
const next = reduce(state, event);
|
||||
|
||||
// Status only moves along the allowed transitions
|
||||
expect(allowed[state.status]).toContain(next.status);
|
||||
|
||||
// Sending only after a valid, non-spam submit
|
||||
if (
|
||||
next.status === 'sending' &&
|
||||
state.status !== 'sending'
|
||||
) {
|
||||
expect(event.type).toBe('submit');
|
||||
expect(validateContact(state.values, options)).toEqual(
|
||||
{},
|
||||
);
|
||||
if (event.type === 'submit') {
|
||||
expect(isLikelySpam(event)).toBe(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing changes while sending (except its result) or
|
||||
// after sent
|
||||
if (state.status === 'sent') expect(next).toBe(state);
|
||||
if (state.status === 'sending') {
|
||||
expect(next.values).toBe(state.values);
|
||||
}
|
||||
|
||||
if (event.type === 'submit') submitted = true;
|
||||
|
||||
// An error only for a field typed in, or after a submit
|
||||
for (const field of Object.keys(next.errors)) {
|
||||
expect(
|
||||
submitted || next.touched.includes(field as never),
|
||||
).toBe(true);
|
||||
}
|
||||
state = next;
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
import {
|
||||
EMPTY_CONTACT,
|
||||
type ContactErrors,
|
||||
type ContactField,
|
||||
type ContactValues,
|
||||
type ShootOption,
|
||||
} from '../contact/types.ts';
|
||||
import { isLikelySpam } from './isLikelySpam.ts';
|
||||
import {
|
||||
CONTACT_FIELDS,
|
||||
validateContact,
|
||||
validateField,
|
||||
} from './validateContact.ts';
|
||||
|
||||
export type ContactStatus = 'editing' | 'sending' | 'sent' | 'failed';
|
||||
|
||||
export interface ContactFormState {
|
||||
status: ContactStatus;
|
||||
values: ContactValues;
|
||||
// Fields the visitor has typed in; only those are checked on leaving
|
||||
touched: ContactField[];
|
||||
errors: ContactErrors;
|
||||
// Counts submits stopped by errors, so the form can move focus to the
|
||||
// first invalid field each time
|
||||
invalidSubmits: number;
|
||||
}
|
||||
|
||||
export type ContactFormEvent =
|
||||
| { type: 'edit'; field: ContactField; value: string }
|
||||
| { type: 'blur'; field: ContactField }
|
||||
| { type: 'preselect'; shoot: string }
|
||||
| { type: 'submit'; honeypot: string; shownAt: number; now: number }
|
||||
| { type: 'resolved' }
|
||||
| { type: 'rejected' };
|
||||
|
||||
export const INITIAL_CONTACT_STATE: ContactFormState = {
|
||||
status: 'editing',
|
||||
values: EMPTY_CONTACT,
|
||||
touched: [],
|
||||
errors: {},
|
||||
invalidSubmits: 0,
|
||||
};
|
||||
|
||||
const withoutError = (errors: ContactErrors, field: ContactField) => {
|
||||
const next = { ...errors };
|
||||
delete next[field];
|
||||
return next;
|
||||
};
|
||||
|
||||
// The contact form's behaviour as a pure state machine (business logic
|
||||
// model): editing -> sending -> sent | failed, and failed -> sending on a
|
||||
// new valid submit. Nothing changes while sending, except its result, and
|
||||
// nothing at all after sent.
|
||||
export function contactFormReducer(
|
||||
state: ContactFormState,
|
||||
event: ContactFormEvent,
|
||||
options: readonly ShootOption[],
|
||||
): ContactFormState {
|
||||
if (state.status === 'sent') return state;
|
||||
|
||||
if (state.status === 'sending') {
|
||||
if (event.type === 'resolved') return { ...state, status: 'sent' };
|
||||
if (event.type === 'rejected') return { ...state, status: 'failed' };
|
||||
// A second submit or edits while sending are ignored (BR-SEND-04)
|
||||
return state;
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'edit': {
|
||||
const values = { ...state.values, [event.field]: event.value };
|
||||
const touched = state.touched.includes(event.field)
|
||||
? state.touched
|
||||
: [...state.touched, event.field];
|
||||
// A shown error disappears as soon as the field is fine; new
|
||||
// errors only appear on leaving or submitting (BR-FORM-12)
|
||||
const errors =
|
||||
state.errors[event.field] &&
|
||||
!validateField(event.field, values, options)
|
||||
? withoutError(state.errors, event.field)
|
||||
: state.errors;
|
||||
return { ...state, values, touched, errors };
|
||||
}
|
||||
case 'blur': {
|
||||
// Leaving an untouched field shows nothing (BR-FORM-10)
|
||||
if (!state.touched.includes(event.field)) return state;
|
||||
const message = validateField(event.field, state.values, options);
|
||||
const errors = message
|
||||
? { ...state.errors, [event.field]: message }
|
||||
: withoutError(state.errors, event.field);
|
||||
return { ...state, errors };
|
||||
}
|
||||
case 'preselect': {
|
||||
const values = { ...state.values, shoot: event.shoot };
|
||||
const errors = validateField('shoot', values, options)
|
||||
? state.errors
|
||||
: withoutError(state.errors, 'shoot');
|
||||
return { ...state, values, errors };
|
||||
}
|
||||
case 'submit': {
|
||||
const errors = validateContact(state.values, options);
|
||||
if (Object.keys(errors).length > 0) {
|
||||
return {
|
||||
...state,
|
||||
status: 'editing',
|
||||
touched: [...CONTACT_FIELDS],
|
||||
errors,
|
||||
invalidSubmits: state.invalidSubmits + 1,
|
||||
};
|
||||
}
|
||||
// Spam gets the normal thank-you, but nothing is sent (BR-SPAM-02)
|
||||
const status = isLikelySpam(event) ? 'sent' : 'sending';
|
||||
return { ...state, status, errors: {} };
|
||||
}
|
||||
default:
|
||||
// resolved or rejected without a pending send
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isLikelySpam, MIN_FILL_MS } from './isLikelySpam';
|
||||
|
||||
describe('isLikelySpam', () => {
|
||||
it('lets a person through and stops a filled honeypot or a hurry', () => {
|
||||
expect(isLikelySpam({ honeypot: '', shownAt: 0, now: 10_000 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
isLikelySpam({ honeypot: 'https://x.nl', shownAt: 0, now: 10_000 }),
|
||||
).toBe(true);
|
||||
expect(isLikelySpam({ honeypot: '', shownAt: 0, now: 1_000 })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('is spam exactly when the honeypot is filled or under 3 s (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.oneof(fc.constant(''), fc.string()),
|
||||
fc.integer({ min: 0, max: 1e9 }),
|
||||
fc.integer({ min: 0, max: 20_000 }),
|
||||
(honeypot, shownAt, elapsed) => {
|
||||
expect(
|
||||
isLikelySpam({
|
||||
honeypot,
|
||||
shownAt,
|
||||
now: shownAt + elapsed,
|
||||
}),
|
||||
).toBe(honeypot !== '' || elapsed < MIN_FILL_MS);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
// A person needs more than this to fill in the form (BR-SPAM-01)
|
||||
export const MIN_FILL_MS = 3000;
|
||||
|
||||
interface SpamSignals {
|
||||
// Value of the hidden "website" field; only bots fill it in
|
||||
honeypot: string;
|
||||
// When the form became usable, and when it was submitted (ms)
|
||||
shownAt: number;
|
||||
now: number;
|
||||
}
|
||||
|
||||
// Whether a submission looks automated. Browser side only: the API repeats
|
||||
// its own checks (SECURITY-11).
|
||||
export function isLikelySpam({ honeypot, shownAt, now }: SpamSignals): boolean {
|
||||
return honeypot !== '' || now - shownAt < MIN_FILL_MS;
|
||||
}
|
||||
@@ -8,10 +8,10 @@ import { visiblePackages } from './visiblePackages';
|
||||
describe('shootOptions', () => {
|
||||
it('lists the live packages, then Overig', () => {
|
||||
expect(shootOptions(packages)).toEqual([
|
||||
{ value: 'zwangerschap', label: 'Zwangerschap' },
|
||||
{ value: 'newborn', label: 'Newborn' },
|
||||
{ value: 'gezin', label: 'Gezin' },
|
||||
{ value: 'overig', label: 'Overig' },
|
||||
{ value: 'Zwangerschap', label: 'Zwangerschap' },
|
||||
{ value: 'Newborn', label: 'Newborn' },
|
||||
{ value: 'Gezin', label: 'Gezin' },
|
||||
{ value: 'Overig', label: 'Overig' },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('shootOptions', () => {
|
||||
expect(options.at(-1)).toEqual(OTHER_SHOOT);
|
||||
expect(options.slice(0, -1)).toEqual(
|
||||
visiblePackages(input).map((pkg) => ({
|
||||
value: pkg.id,
|
||||
value: pkg.name,
|
||||
label: pkg.name,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import type { ShootOption } from '../contact/types.ts';
|
||||
import type { SubjectOption } from '../cms-client/contact/index.ts';
|
||||
import type { PricingPackage } from '../content/types.ts';
|
||||
import { visiblePackages } from './visiblePackages.ts';
|
||||
|
||||
export const OTHER_SHOOT: ShootOption = { value: 'overig', label: 'Overig' };
|
||||
// What is sent as the message subject is the readable label, so mails and
|
||||
// the CMS message list are readable (decision Bryan, 2026-11-10). The label
|
||||
// of "other" is fixed per site.
|
||||
export const OTHER_SHOOT: SubjectOption = { value: 'Overig', label: 'Overig' };
|
||||
|
||||
// The choices of "In welke shoot heb je interesse?": the shown packages in
|
||||
// their order, then Overig. Same source as the price cards, so the two never
|
||||
// drift apart.
|
||||
// drift apart. The value is the label itself; the package id stays local
|
||||
// (?pakket=, see ContactPanel).
|
||||
export function shootOptions(
|
||||
packages: readonly PricingPackage[],
|
||||
): ShootOption[] {
|
||||
): SubjectOption[] {
|
||||
return [
|
||||
...visiblePackages(packages).map((pkg) => ({
|
||||
value: pkg.id,
|
||||
value: pkg.name,
|
||||
label: pkg.name,
|
||||
})),
|
||||
OTHER_SHOOT,
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { anyContactValues } from '../test/arbitraries';
|
||||
import { toContactPayload } from './toContactPayload';
|
||||
|
||||
describe('toContactPayload', () => {
|
||||
it('trims every field', () => {
|
||||
expect(
|
||||
toContactPayload({
|
||||
naam: ' Demi ',
|
||||
email: ' demi@example.nl',
|
||||
shoot: 'newborn ',
|
||||
bericht: '\nHoi!\n',
|
||||
}),
|
||||
).toEqual({
|
||||
naam: 'Demi',
|
||||
email: 'demi@example.nl',
|
||||
shoot: 'newborn',
|
||||
bericht: 'Hoi!',
|
||||
});
|
||||
});
|
||||
|
||||
it('is idempotent and leaves no outer whitespace', () => {
|
||||
fc.assert(
|
||||
fc.property(anyContactValues, (values) => {
|
||||
const payload = toContactPayload(values);
|
||||
expect(toContactPayload(payload)).toEqual(payload);
|
||||
for (const value of Object.values(payload)) {
|
||||
expect(value).toBe(value.trim());
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import type { ContactPayload, ContactValues } from '../contact/types.ts';
|
||||
|
||||
// What is sent: the values without surrounding whitespace
|
||||
export function toContactPayload(values: ContactValues): ContactPayload {
|
||||
return {
|
||||
naam: values.naam.trim(),
|
||||
email: values.email.trim(),
|
||||
shoot: values.shoot.trim(),
|
||||
bericht: values.bericht.trim(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// The only analytics events the contact form sends. Names only: never a
|
||||
// field value, token or key (FR-CF-10).
|
||||
export type ContactEvent = 'contact-sent' | 'contact-failed';
|
||||
|
||||
type UmamiWindow = Window & { umami?: { track?: (name: string) => void } };
|
||||
|
||||
export function trackContactEvent(name: ContactEvent): void {
|
||||
try {
|
||||
(window as UmamiWindow).umami?.track?.(name);
|
||||
} catch {
|
||||
// Statistics must never get in the way of the form
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CONTACT_LIMITS, type ContactField } from '../contact/types';
|
||||
import packages from '../content/packages';
|
||||
import { anyContactValues, contactValues } from '../test/arbitraries';
|
||||
import { shootOptions } from './shootOptions';
|
||||
import {
|
||||
CONTACT_FIELDS,
|
||||
CONTACT_MESSAGES as M,
|
||||
validateContact,
|
||||
validateField,
|
||||
} from './validateContact';
|
||||
|
||||
const options = shootOptions(packages);
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
|
||||
const valid = {
|
||||
naam: 'Demi',
|
||||
email: 'demi@example.nl',
|
||||
shoot: 'newborn',
|
||||
bericht: 'Wanneer heb je plek?',
|
||||
};
|
||||
|
||||
const requiredMessage: Record<ContactField, string> = {
|
||||
naam: M.naamRequired,
|
||||
email: M.emailRequired,
|
||||
shoot: M.shootRequired,
|
||||
bericht: M.berichtRequired,
|
||||
};
|
||||
|
||||
describe('validateContact', () => {
|
||||
it('accepts a complete form', () => {
|
||||
expect(validateContact(valid, options)).toEqual({});
|
||||
});
|
||||
|
||||
it('gives the agreed message per rule', () => {
|
||||
const empty = { naam: ' ', email: '', shoot: '', bericht: '' };
|
||||
expect(validateContact(empty, options)).toEqual({
|
||||
naam: 'Vul je naam in.',
|
||||
email: 'Vul je e-mailadres in.',
|
||||
shoot: 'Kies een soort shoot.',
|
||||
bericht: 'Schrijf hier je vraag.',
|
||||
});
|
||||
expect(
|
||||
validateField('email', { ...valid, email: 'demi@' }, options),
|
||||
).toBe('Dit e-mailadres is ongeldig.');
|
||||
expect(
|
||||
validateField('shoot', { ...valid, shoot: 'bruiloft' }, options),
|
||||
).toBe('Kies een soort shoot.');
|
||||
expect(
|
||||
validateField('naam', { ...valid, naam: 'x'.repeat(101) }, options),
|
||||
).toBe('De naam is te lang.');
|
||||
expect(
|
||||
validateField(
|
||||
'email',
|
||||
{ ...valid, email: `${'x'.repeat(250)}@a.nl` },
|
||||
options,
|
||||
),
|
||||
).toBe('Het e-mailadres is te lang.');
|
||||
expect(
|
||||
validateField(
|
||||
'bericht',
|
||||
{ ...valid, bericht: 'x'.repeat(2001) },
|
||||
options,
|
||||
),
|
||||
).toBe('Het bericht is te lang.');
|
||||
});
|
||||
|
||||
it('finds no errors in valid values (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(contactValues, (values) => {
|
||||
expect(validateContact(values, options)).toEqual({});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reports exactly the emptied required field (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
contactValues,
|
||||
fc.constantFrom(...CONTACT_FIELDS),
|
||||
fc.constantFrom('', ' '),
|
||||
(values, field, blank) => {
|
||||
expect(
|
||||
validateContact({ ...values, [field]: blank }, options),
|
||||
).toEqual({ [field]: requiredMessage[field] });
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('reports a field over its limit as too long (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
contactValues,
|
||||
fc.constantFrom('naam' as const, 'bericht' as const),
|
||||
fc.integer({ min: 1, max: 50 }),
|
||||
(values, field, extra) => {
|
||||
const long = 'x'.repeat(CONTACT_LIMITS[field] + extra);
|
||||
expect(
|
||||
validateContact({ ...values, [field]: long }, options),
|
||||
).toEqual({
|
||||
[field]:
|
||||
field === 'naam' ? M.naamTooLong : M.berichtTooLong,
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('flags an e-mail exactly when it fails the format (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
contactValues,
|
||||
fc.string({ minLength: 1, maxLength: 40 }),
|
||||
(values, email) => {
|
||||
fc.pre(email.trim() !== '');
|
||||
const message = validateField(
|
||||
'email',
|
||||
{ ...values, email },
|
||||
options,
|
||||
);
|
||||
expect(message === M.emailInvalid).toBe(
|
||||
!EMAIL.test(email.trim()),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('only ever uses the agreed messages, one per field (invariant)', () => {
|
||||
const messages = new Set<string>(Object.values(M));
|
||||
fc.assert(
|
||||
fc.property(anyContactValues, (values) => {
|
||||
const errors = validateContact(values, options);
|
||||
for (const [field, message] of Object.entries(errors)) {
|
||||
expect(CONTACT_FIELDS).toContain(field);
|
||||
expect(messages.has(message)).toBe(true);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import {
|
||||
CONTACT_LIMITS,
|
||||
type ContactErrors,
|
||||
type ContactField,
|
||||
type ContactValues,
|
||||
type ShootOption,
|
||||
} from '../contact/types.ts';
|
||||
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
|
||||
// The messages of BR-FORM-01…06
|
||||
export const CONTACT_MESSAGES = {
|
||||
naamRequired: 'Vul je naam in.',
|
||||
naamTooLong: 'De naam is te lang.',
|
||||
emailRequired: 'Vul je e-mailadres in.',
|
||||
emailTooLong: 'Het e-mailadres is te lang.',
|
||||
emailInvalid: 'Dit e-mailadres is ongeldig.',
|
||||
shootRequired: 'Kies een soort shoot.',
|
||||
berichtRequired: 'Schrijf hier je vraag.',
|
||||
berichtTooLong: 'Het bericht is te lang.',
|
||||
} as const;
|
||||
|
||||
export const CONTACT_FIELDS: readonly ContactField[] = [
|
||||
'naam',
|
||||
'email',
|
||||
'shoot',
|
||||
'bericht',
|
||||
];
|
||||
|
||||
// The message for one field, or undefined when it is fine. Per field the
|
||||
// first failing rule wins: required, then length, then format (BR-FORM-07).
|
||||
export function validateField(
|
||||
field: ContactField,
|
||||
values: ContactValues,
|
||||
options: readonly ShootOption[],
|
||||
): string | undefined {
|
||||
const value = values[field].trim();
|
||||
switch (field) {
|
||||
case 'naam':
|
||||
if (value === '') return CONTACT_MESSAGES.naamRequired;
|
||||
if (value.length > CONTACT_LIMITS.naam) {
|
||||
return CONTACT_MESSAGES.naamTooLong;
|
||||
}
|
||||
return undefined;
|
||||
case 'email':
|
||||
if (value === '') return CONTACT_MESSAGES.emailRequired;
|
||||
if (value.length > CONTACT_LIMITS.email) {
|
||||
return CONTACT_MESSAGES.emailTooLong;
|
||||
}
|
||||
if (!EMAIL.test(value)) return CONTACT_MESSAGES.emailInvalid;
|
||||
return undefined;
|
||||
case 'shoot':
|
||||
return options.some((option) => option.value === values.shoot)
|
||||
? undefined
|
||||
: CONTACT_MESSAGES.shootRequired;
|
||||
case 'bericht':
|
||||
if (value === '') return CONTACT_MESSAGES.berichtRequired;
|
||||
if (value.length > CONTACT_LIMITS.bericht) {
|
||||
return CONTACT_MESSAGES.berichtTooLong;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Messages for every field that fails; empty when the form can be sent
|
||||
export function validateContact(
|
||||
values: ContactValues,
|
||||
options: readonly ShootOption[],
|
||||
): ContactErrors {
|
||||
const errors: ContactErrors = {};
|
||||
for (const field of CONTACT_FIELDS) {
|
||||
const message = validateField(field, values, options);
|
||||
if (message) errors[field] = message;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
import fc from 'fast-check';
|
||||
import type { ContactField, ContactValues } from '../contact/types';
|
||||
import type { ContactFormEvent } from '../lib/contactFormReducer';
|
||||
import type { LightboxEvent } from '../lib/lightboxReducer';
|
||||
import { shootPageView, type ShootPageView } from '../lib/shootPageView';
|
||||
import type { Point } from '../lib/swipeDirection';
|
||||
@@ -339,77 +337,6 @@ export const anyTestimonial: fc.Arbitrary<Testimonial> = fc.oneof(
|
||||
),
|
||||
);
|
||||
|
||||
// Shoot values as the form offers them for the live packages
|
||||
const shootValue = fc.constantFrom(
|
||||
'zwangerschap',
|
||||
'newborn',
|
||||
'gezin',
|
||||
'overig',
|
||||
);
|
||||
|
||||
// Values that pass every rule: realistic text within the limits
|
||||
export const contactValues: fc.Arbitrary<ContactValues> = fc.record({
|
||||
naam: nonBlank,
|
||||
email: validEmail.map(({ user, domain }) => `${user}@${domain}`),
|
||||
shoot: shootValue,
|
||||
bericht: fc
|
||||
.string({ minLength: 1, maxLength: 300 })
|
||||
.filter((text) => text.trim() !== ''),
|
||||
});
|
||||
|
||||
// Valid and broken values mixed: empty, whitespace, too long, bad e-mail
|
||||
export const anyContactValues: fc.Arbitrary<ContactValues> = fc.oneof(
|
||||
contactValues,
|
||||
fc.record({
|
||||
naam: fc.oneof(nonBlank, fc.constantFrom('', ' ', 'x'.repeat(101))),
|
||||
email: fc.oneof(
|
||||
validEmail.map(({ user, domain }) => `${user}@${domain}`),
|
||||
fc.constantFrom(
|
||||
'',
|
||||
'geen-adres',
|
||||
'a@b',
|
||||
'a b@c.nl',
|
||||
'x'.repeat(255),
|
||||
),
|
||||
fc.string({ maxLength: 20 }),
|
||||
),
|
||||
shoot: fc.oneof(shootValue, fc.constantFrom('', 'bruiloft')),
|
||||
bericht: fc.oneof(
|
||||
nonBlank,
|
||||
fc.constantFrom('', ' ', 'x'.repeat(2001)),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const contactField = fc.constantFrom<ContactField>(
|
||||
'naam',
|
||||
'email',
|
||||
'shoot',
|
||||
'bericht',
|
||||
);
|
||||
|
||||
// Anything that can happen to the form, for the state machine test
|
||||
export const contactEvent: fc.Arbitrary<ContactFormEvent> = fc.oneof(
|
||||
fc.record({
|
||||
type: fc.constant('edit' as const),
|
||||
field: contactField,
|
||||
value: fc.oneof(
|
||||
nonBlank,
|
||||
fc.constantFrom('', 'a@b.nl', 'newborn', 'overig'),
|
||||
),
|
||||
}),
|
||||
fc.record({ type: fc.constant('blur' as const), field: contactField }),
|
||||
fc.record({ type: fc.constant('preselect' as const), shoot: shootValue }),
|
||||
fc.record({
|
||||
type: fc.constant('submit' as const),
|
||||
honeypot: fc.constantFrom('', '', '', 'http://spam.example'),
|
||||
shownAt: fc.constant(0),
|
||||
now: fc.constantFrom(500, 5000, 10000),
|
||||
}),
|
||||
fc.constant({ type: 'resolved' as const }),
|
||||
fc.constant({ type: 'rejected' as const }),
|
||||
);
|
||||
|
||||
// --- Gallery (portfolio) ---
|
||||
|
||||
// A touch position on a screen, in CSS pixels
|
||||
|
||||
Reference in New Issue
Block a user