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

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

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:13:24 +01:00
co-authored by Claude Sonnet 5.5
parent 9661b64635
commit aa843a5675
45 changed files with 2609 additions and 22 deletions
+9
View File
@@ -0,0 +1,9 @@
# 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.
+47
View File
@@ -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,225 @@
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' });
});
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,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,117 @@
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 } = captcha as Record<string, unknown>;
if (typeof provider !== 'string' || typeof siteKey !== 'string') {
return null;
}
parsedCaptcha = { provider, siteKey };
}
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' };
}
},
};
}
+9
View File
@@ -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';
+58
View File
@@ -0,0 +1,58 @@
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;
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.',
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));
}
+40
View File
@@ -0,0 +1,40 @@
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: '' };
export interface ContactToken {
token: string;
minSeconds: number;
captcha: { provider: string; siteKey: string } | 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>;
}
+260
View File
@@ -0,0 +1,260 @@
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: '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 };
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,
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);
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]);
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, canRefresh: boolean): Promise<SubmitResult> => {
const result = await client.submit(payload, { idempotencyKey: key });
if (result.kind === 'invalid' && result.tokenExpired && canRefresh) {
const fresh = await refreshToken();
if (fresh.kind === 'ok') {
tokenRef.current = fresh.token;
return attempt({ ...payload, token: fresh.token.token }, key, false);
}
return { kind: 'failed' };
}
return result;
},
[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;
}
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,
};
const result = await attempt(payload, keyRef.current, true);
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;
}
}, [attempt, finishFailure, focusFirstInvalid, honeypot, onEvent, 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
: 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,
};
}
+60
View File
@@ -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;
}
+8
View File
@@ -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}`;
}
+44
View File
@@ -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);
}
}
+45
View File
@@ -0,0 +1,45 @@
/** 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 {
constructor(public readonly kind: TransportFailure) {
super(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,453 @@
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ContactSection } from '../components/ContactSection';
import { contactForm, packages } from '../data/content';
import { ContactPreselectProvider } from '../../../shared/contact/ContactPreselectProvider';
import { useContactPreselect } from '../../../shared/contact/useContactPreselect';
class FakeIntersectionObserver {
static instances: FakeIntersectionObserver[] = [];
constructor(private readonly callback: IntersectionObserverCallback) {
FakeIntersectionObserver.instances.push(this);
}
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
trigger() {
this.callback(
[{ isIntersecting: true } as IntersectionObserverEntry],
this as unknown as IntersectionObserver,
);
}
}
interface Call {
url: string;
init?: RequestInit;
}
type Responder = (call: Call) => Response | Promise<Response>;
const TOKEN = { token: 'tok-1', minSeconds: 3, captcha: null };
const jsonResponse = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json', ...headers },
});
function setup(routes: { token?: Responder; submit?: Responder } = {}) {
const calls: Call[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
const call = { url, init };
calls.push(call);
if (url.endsWith('/api/v1/offerings')) return jsonResponse(packages);
if (url.endsWith('/contact-messages/token')) {
return (routes.token ?? (() => jsonResponse(TOKEN)))(call);
}
if (url.endsWith('/contact-messages')) {
return (routes.submit ?? (() => jsonResponse({ status: 'received' }, 202)))(call);
}
return new Response(null, { status: 404 });
});
vi.stubGlobal('fetch', fetchMock);
function PreselectButton() {
const { select } = useContactPreselect();
return (
<button type="button" onClick={() => select('website')}>
kies website
</button>
);
}
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={queryClient}>
<ContactPreselectProvider>
<PreselectButton />
<ContactSection />
</ContactPreselectProvider>
</QueryClientProvider>,
);
const tokenCalls = () => calls.filter((c) => c.url.endsWith('/contact-messages/token'));
const submitCalls = () =>
calls.filter((c) => c.url.endsWith('/contact-messages') && c.init?.method === 'POST');
const intersect = async () => {
await act(async () => {
FakeIntersectionObserver.instances.forEach((o) => o.trigger());
});
};
return { calls, tokenCalls, submitCalls, intersect };
}
async function openForm(s: ReturnType<typeof setup>) {
await s.intersect();
await screen.findByTestId('contact-form');
// wait for the offerings so the subject options are complete
await waitFor(() => expect(screen.getByRole('option', { name: 'Website' })).toBeInTheDocument());
}
function fillValid() {
fireEvent.change(screen.getByLabelText('Naam'), { target: { value: 'Jan Jansen' } });
fireEvent.change(screen.getByLabelText('E-mail'), { target: { value: 'jan@example.nl' } });
fireEvent.change(screen.getByLabelText('Onderwerp'), { target: { value: 'website' } });
fireEvent.change(screen.getByLabelText('Bericht'), {
target: { value: 'Ik wil graag een offerte.' },
});
}
describe('contact panel availability (BR-U4-2, BR-U4-3)', () => {
beforeEach(() => {
FakeIntersectionObserver.instances = [];
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
vi.stubEnv('VITE_API_BASE_URL', '');
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
it('shows the mailto panel and does not touch the API before the section nears the viewport', () => {
const s = setup();
expect(screen.getByTestId('mailto-panel')).toBeInTheDocument();
expect(screen.getByTestId('contact-mailto-button')).toBeInTheDocument();
expect(s.tokenCalls()).toHaveLength(0);
});
it('upgrades to the form once the token request answers 200', async () => {
const s = setup();
await s.intersect();
expect(await screen.findByTestId('contact-form')).toBeInTheDocument();
expect(screen.getByTestId('contact-panel')).toHaveAttribute('data-availability', 'open');
expect(s.tokenCalls()).toHaveLength(1);
expect(screen.queryByTestId('mailto-panel')).not.toBeInTheDocument();
});
it.each([
['404 (form closed)', () => new Response(null, { status: 404 })],
['500', () => new Response(null, { status: 500 })],
['429', () => new Response(null, { status: 429 })],
[
'a captcha requirement',
() => jsonResponse({ ...TOKEN, captcha: { provider: 'fc', siteKey: 'k' } }),
],
['a malformed body', () => jsonResponse({ nope: 1 })],
])('keeps the mailto panel on %s', async (_name, token) => {
const s = setup({ token });
await s.intersect();
await waitFor(() =>
expect(screen.getByTestId('contact-panel')).toHaveAttribute('data-availability', 'closed'),
);
expect(screen.getByTestId('mailto-panel')).toBeInTheDocument();
expect(screen.queryByTestId('contact-form')).not.toBeInTheDocument();
});
it('keeps the mailto panel on a network error', async () => {
const s = setup({
token: () => {
throw new TypeError('offline');
},
});
await s.intersect();
await waitFor(() =>
expect(screen.getByTestId('contact-panel')).toHaveAttribute('data-availability', 'closed'),
);
});
it('asks for the token only once', async () => {
const s = setup();
await s.intersect();
await s.intersect();
await screen.findByTestId('contact-form');
expect(s.tokenCalls()).toHaveLength(1);
});
it('falls back to the first focus when IntersectionObserver is unavailable', async () => {
vi.stubGlobal('IntersectionObserver', undefined);
const s = setup();
expect(s.tokenCalls()).toHaveLength(0);
fireEvent.focusIn(screen.getByTestId('contact-panel'));
expect(await screen.findByTestId('contact-form')).toBeInTheDocument();
});
});
describe('contact form (BR-U4-4 .. BR-U4-15)', () => {
beforeEach(() => {
FakeIntersectionObserver.instances = [];
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
vi.stubEnv('VITE_API_BASE_URL', '');
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it('submits valid input with token and idempotency key and shows the thank-you state', async () => {
const track = vi.fn();
vi.stubGlobal('umami', { track });
const s = setup();
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
const success = await screen.findByTestId('contact-success');
expect(success).toHaveAttribute('role', 'status');
expect(success).toHaveTextContent('Bedankt!');
expect(success).toHaveTextContent(contactForm.successText);
await waitFor(() => expect(document.activeElement).toBe(success));
const [call] = s.submitCalls();
const headers = call.init?.headers as Record<string, string>;
expect(headers['Idempotency-Key']).toMatch(/^[0-9a-f-]{36}$/);
expect(JSON.parse(call.init?.body as string)).toEqual({
name: 'Jan Jansen',
email: 'jan@example.nl',
subject: 'website',
message: 'Ik wil graag een offerte.',
hpCheck: '',
token: 'tok-1',
});
expect(track).toHaveBeenCalledTimes(1);
expect(track).toHaveBeenCalledWith('contact-sent');
});
it('shows the privacy sentence and offers the packages plus Overig as subjects', async () => {
const s = setup();
await openForm(s);
expect(screen.getByText(contactForm.privacyNote)).toBeInTheDocument();
const options = within(screen.getByLabelText('Onderwerp'))
.getAllByRole('option')
.map((o) => o.textContent);
expect(options).toEqual(['Kies een onderwerp', ...packages.map((p) => p.title), 'Overig']);
expect(screen.getByRole('option', { name: 'Kies een onderwerp' })).toBeDisabled();
});
it('shows validation errors on submit, focuses the first invalid field and sends nothing', async () => {
const s = setup();
await openForm(s);
fireEvent.click(screen.getByTestId('contact-submit'));
expect(screen.getAllByTestId('field-error').map((e) => e.textContent)).toEqual([
'Vul je naam in.',
'Vul je e-mailadres in.',
'Kies een onderwerp.',
'Schrijf hier je vraag.',
]);
const name = screen.getByLabelText('Naam');
expect(name).toHaveAttribute('aria-invalid', 'true');
expect(name).toHaveAttribute('aria-describedby', 'contact-name-error');
expect(document.getElementById('contact-name-error')).toHaveTextContent('Vul je naam in.');
expect(document.activeElement).toBe(name);
expect(s.submitCalls()).toHaveLength(0);
});
it('shows a field error on blur and removes it when the value becomes valid', async () => {
const s = setup();
await openForm(s);
const email = screen.getByLabelText('E-mail');
fireEvent.change(email, { target: { value: 'nope' } });
expect(screen.queryByTestId('field-error')).not.toBeInTheDocument();
fireEvent.blur(email);
expect(screen.getByTestId('field-error')).toHaveTextContent('Dit e-mailadres is ongeldig.');
fireEvent.change(email, { target: { value: 'jan@example.nl' } });
expect(screen.queryByTestId('field-error')).not.toBeInTheDocument();
});
it('drops a filled honeypot silently: success state without any request', async () => {
const s = setup();
await openForm(s);
fillValid();
const honeypot = document.getElementById('contact-hp') as HTMLInputElement;
expect(honeypot.closest('[aria-hidden="true"]')).not.toBeNull();
expect(honeypot).toHaveAttribute('tabindex', '-1');
expect(honeypot).toHaveAttribute('autocomplete', 'off');
fireEvent.change(honeypot, { target: { value: 'http://spam.example' } });
fireEvent.click(screen.getByTestId('contact-submit'));
expect(await screen.findByTestId('contact-success')).toBeInTheDocument();
expect(s.submitCalls()).toHaveLength(0);
});
it('maps server field errors back to the fields and focuses the first one', async () => {
const s = setup({
submit: () => jsonResponse({ errors: { email: ['invalid'], message: ['tooLong'] } }, 400),
});
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
await waitFor(() => expect(screen.getAllByTestId('field-error')).toHaveLength(2));
expect(screen.getAllByTestId('field-error').map((e) => e.textContent)).toEqual([
'Dit e-mailadres is ongeldig.',
'Het bericht is te lang.',
]);
expect(document.activeElement).toBe(screen.getByLabelText('E-mail'));
expect(screen.getByLabelText('Naam')).toHaveValue('Jan Jansen');
});
it('refreshes an expired token once and repeats the submit with the same idempotency key', async () => {
let tokenRequests = 0;
let submits = 0;
const s = setup({
token: () => jsonResponse({ ...TOKEN, token: `tok-${++tokenRequests}` }),
submit: () =>
++submits === 1
? jsonResponse({ errors: { token: ['expired'] } }, 400)
: jsonResponse({ status: 'received' }, 202),
});
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
expect(await screen.findByTestId('contact-success')).toBeInTheDocument();
expect(s.tokenCalls()).toHaveLength(2);
const [first, second] = s.submitCalls();
expect(JSON.parse(first.init?.body as string).token).toBe('tok-1');
expect(JSON.parse(second.init?.body as string).token).toBe('tok-2');
expect((first.init?.headers as Record<string, string>)['Idempotency-Key']).toBe(
(second.init?.headers as Record<string, string>)['Idempotency-Key'],
);
});
it('shows a generic failure when the token is still expired after the single refresh', async () => {
const s = setup({ submit: () => jsonResponse({ errors: { token: ['expired'] } }, 400) });
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
expect(await screen.findByTestId('contact-failure')).toBeInTheDocument();
expect(s.submitCalls()).toHaveLength(2);
});
it.each([
[413, {}, 'Je bericht is te groot.'],
[429, { 'Retry-After': '120' }, 'Probeer het over 2 minuten opnieuw.'],
[429, { 'Retry-After': '30' }, 'Probeer het over 1 minuut opnieuw.'],
])('explains %i answers', async (status, headers, text) => {
const s = setup({ submit: () => jsonResponse({}, status, headers as Record<string, string>) });
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent(text);
});
it('keeps the input after a server failure, shows the mail address and retries with the same key', async () => {
const track = vi.fn();
vi.stubGlobal('umami', { track });
let submits = 0;
const s = setup({
submit: () =>
++submits === 1
? new Response(null, { status: 500 })
: jsonResponse({ status: 'received' }, 202),
});
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Versturen lukte niet.');
expect(alert).toHaveTextContent('info@slpsoftware.nl');
expect(screen.getByLabelText('Naam')).toHaveValue('Jan Jansen');
expect(screen.getByLabelText('Bericht')).toHaveValue('Ik wil graag een offerte.');
expect(screen.getByTestId('contact-submit')).toHaveTextContent('Opnieuw proberen');
expect(track).toHaveBeenCalledWith('contact-failed');
fireEvent.click(screen.getByTestId('contact-submit'));
expect(await screen.findByTestId('contact-success')).toBeInTheDocument();
const [a, b] = s.submitCalls();
expect((a.init?.headers as Record<string, string>)['Idempotency-Key']).toBe(
(b.init?.headers as Record<string, string>)['Idempotency-Key'],
);
});
it('ignores a second submit while sending', async () => {
let release: (r: Response) => void = () => {};
const s = setup({
submit: () => new Promise<Response>((resolve) => (release = resolve)),
});
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
await waitFor(() => expect(screen.getByTestId('contact-submit')).toBeDisabled());
expect(screen.getByTestId('contact-submit')).toHaveTextContent('Versturen');
fireEvent.submit(screen.getByTestId('contact-form'));
expect(s.submitCalls()).toHaveLength(1);
await act(async () => release(jsonResponse({ status: 'received' }, 202)));
expect(await screen.findByTestId('contact-success')).toBeInTheDocument();
});
it('resets to an empty form with a new idempotency key after "Nog een bericht sturen"', async () => {
const s = setup();
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
await screen.findByTestId('contact-success');
fireEvent.click(screen.getByTestId('contact-reset'));
expect(await screen.findByTestId('contact-form')).toBeInTheDocument();
expect(screen.getByLabelText('Naam')).toHaveValue('');
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
await screen.findByTestId('contact-success');
const [a, b] = s.submitCalls();
expect((a.init?.headers as Record<string, string>)['Idempotency-Key']).not.toBe(
(b.init?.headers as Record<string, string>)['Idempotency-Key'],
);
});
it('applies the package choice to the subject, re-applies it after a manual change, ignores unknown values', async () => {
const s = setup();
await openForm(s);
const subject = screen.getByLabelText('Onderwerp') as HTMLSelectElement;
fireEvent.click(screen.getByText('kies website'));
await waitFor(() => expect(subject.value).toBe('website'));
fireEvent.change(subject, { target: { value: 'other' } });
expect(subject.value).toBe('other');
fireEvent.click(screen.getByText('kies website'));
await waitFor(() => expect(subject.value).toBe('website'));
});
it('never writes form data to the console, Sentry-style globals or analytics events', async () => {
const consoleSpies = (['log', 'info', 'warn', 'error', 'debug'] as const).map((m) =>
vi.spyOn(console, m).mockImplementation(() => {}),
);
const track = vi.fn();
vi.stubGlobal('umami', { track });
let submits = 0;
const s = setup({
submit: () =>
++submits === 1
? new Response(null, { status: 500 })
: jsonResponse({ status: 'received' }, 202),
});
await openForm(s);
fillValid();
fireEvent.click(screen.getByTestId('contact-submit'));
await screen.findByRole('alert');
fireEvent.click(screen.getByTestId('contact-submit'));
await screen.findByTestId('contact-success');
const logged = JSON.stringify(consoleSpies.flatMap((spy) => spy.mock.calls));
for (const secret of ['Jan Jansen', 'jan@example.nl', 'offerte', 'tok-1']) {
expect(logged).not.toContain(secret);
}
for (const [event, ...rest] of track.mock.calls) {
expect(['contact-sent', 'contact-failed']).toContain(event);
expect(rest).toHaveLength(0);
}
});
it('has labelled controls with a 44px submit target and no autocompletion hints missing', async () => {
const s = setup();
await openForm(s);
expect(screen.getByLabelText('Naam')).toHaveAttribute('autocomplete', 'name');
expect(screen.getByLabelText('E-mail')).toHaveAttribute('autocomplete', 'email');
expect(screen.getByLabelText('E-mail')).toHaveAttribute('type', 'email');
expect(screen.getByTestId('contact-form')).toHaveAttribute('novalidate');
expect(screen.getByTestId('contact-submit')).toHaveClass('min-h-[44px]');
});
});
@@ -0,0 +1,164 @@
import { useEffect, useMemo, useRef } from 'react';
import type { ReactNode } from 'react';
import {
useContactForm,
type ContactClient,
type ContactToken,
type SubjectOption,
type TokenResult,
} from '../../../cms-client/contact';
import { trackEvent } from '../../../shared/analytics/trackEvent';
import { useContactPreselect } from '../../../shared/contact/useContactPreselect';
import { contactForm, contactInfo } from '../data/content';
import { usePackagesQuery } from '../hooks/usePackagesQuery';
const INPUT =
'w-full rounded-none border-0 border-b-2 border-text bg-field px-3.5 py-[13px] text-[17px] font-normal text-text focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:opacity-70';
interface ContactFormViewProps {
client: ContactClient;
token: ContactToken;
refreshToken: () => Promise<TokenResult>;
}
function Field({
label,
children,
error,
errorId,
}: {
label: string;
children: ReactNode;
error: string | null;
errorId: string;
}) {
return (
<div className="flex flex-col gap-1.5">
<label className="flex flex-col gap-1.5 text-sm font-bold">
{label}
{children}
</label>
{error ? (
<span id={errorId} className="text-sm font-medium text-danger" data-testid="field-error">
{error}
</span>
) : null}
</div>
);
}
/** The contact form of design B (panel colours, underline inputs, brand submit button). */
export function ContactFormView({ client, token, refreshToken }: ContactFormViewProps) {
const { data: packages } = usePackagesQuery();
const preselect = useContactPreselect();
const subjectOptions = useMemo<SubjectOption[]>(
() => [
...(packages ?? []).map((pkg) => ({ value: pkg.slug, label: pkg.title })),
{ value: 'other', label: contactForm.otherSubjectLabel },
],
[packages],
);
const form = useContactForm({
idPrefix: 'contact',
subjectOptions,
preselect: { subject: preselect.subject, key: preselect.key },
client,
token,
refreshToken,
fallbackAddress: contactInfo.email,
onEvent: (event) => trackEvent(event === 'sent' ? 'contact-sent' : 'contact-failed'),
});
const successRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (form.status === 'sent') {
successRef.current?.focus();
}
}, [form.status]);
if (form.status === 'sent') {
return (
<div
ref={successRef}
tabIndex={-1}
role="status"
className="py-6 outline-none"
data-testid="contact-success"
>
<p className="mb-3 text-[clamp(30px,3.4vw,44px)] font-extrabold leading-none tracking-[-0.02em] [font-stretch:112%]">
Bedankt!
</p>
<p className="mb-7 text-body">{contactForm.successText}</p>
<button
type="button"
onClick={form.reset}
className="min-h-[44px] bg-text px-[22px] py-[15px] text-[15px] font-bold text-panel"
data-testid="contact-reset"
>
Nog een bericht sturen
</button>
</div>
);
}
const name = form.getFieldProps('name');
const email = form.getFieldProps('email');
const subject = form.getFieldProps('subject');
const message = form.getFieldProps('message');
const { id: hpId, ...hpProps } = form.honeypotProps;
return (
<form {...form.formProps} className="flex flex-col gap-6" data-testid="contact-form">
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
<Field label="Naam" error={name.error} errorId={name.errorId}>
<input type="text" autoComplete="name" className={INPUT} {...name.inputProps} />
</Field>
<Field label="E-mail" error={email.error} errorId={email.errorId}>
<input type="email" autoComplete="email" className={INPUT} {...email.inputProps} />
</Field>
</div>
<Field label="Onderwerp" error={subject.error} errorId={subject.errorId}>
<select className={INPUT} {...subject.inputProps}>
<option value="" disabled>
Kies een onderwerp
</option>
{subjectOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
<Field label="Bericht" error={message.error} errorId={message.errorId}>
<textarea rows={5} className={`${INPUT} resize-y`} {...message.inputProps} />
</Field>
{/* Honeypot: invisible to people and assistive technology; bots fill it (BR-U4-7). */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<label htmlFor={hpId}>Laat dit veld leeg</label>
<input type="text" id={hpId} {...hpProps} />
</div>
{form.failureMessage ? (
<p role="alert" className="font-medium text-danger" data-testid="contact-failure">
{form.failureMessage}
</p>
) : null}
<button
type="submit"
disabled={form.status === 'sending'}
className="min-h-[44px] rounded-none bg-brand px-6 py-[18px] text-[17px] font-bold text-on-brand disabled:opacity-70"
data-testid="contact-submit"
>
{form.status === 'sending'
? form.messages.sendingLabel
: form.status === 'failed'
? 'Opnieuw proberen'
: 'Verstuur'}
</button>
<p className="-mt-2 text-[13px] text-muted">{contactForm.privacyNote}</p>
</form>
);
}
@@ -0,0 +1,31 @@
import { useMemo, useRef } from 'react';
import { createContactClient } from '../../../cms-client/contact';
import { useContactAvailability } from '../hooks/useContactAvailability';
import { ContactFormView } from './ContactFormView';
import { MailtoPanel } from './MailtoPanel';
/**
* Panel inside the contact block: the mailto call-to-action by default (and whenever the API is
* closed, failing or needs a captcha), the form once the API answers (BR-U4-2). The panel keeps a
* minimum height so the page does not jump when it is upgraded.
*/
export function ContactPanel() {
const ref = useRef<HTMLDivElement>(null);
const client = useMemo(() => createContactClient(), []);
const { availability, refreshToken } = useContactAvailability(ref, client);
return (
<div
ref={ref}
className="min-h-[280px] min-w-0 flex-[1.4_1_520px] bg-panel p-[clamp(24px,4vw,48px)] text-text"
data-testid="contact-panel"
data-availability={availability.status}
>
{availability.status === 'open' ? (
<ContactFormView client={client} token={availability.token} refreshToken={refreshToken} />
) : (
<MailtoPanel />
)}
</div>
);
}
@@ -1,12 +1,11 @@
import { contactInfo } from '../data/content';
import { ContactPanel } from './ContactPanel';
/**
* Contact block of design B: brand-red section with the display heading, intro, mail link and a
* panel on the right. Until the contact form (unit U4) the panel holds the mailto call-to-action.
* panel on the right (mailto call-to-action or the contact form, see ContactPanel).
*/
export function ContactSection() {
const mailtoHref = `mailto:${contactInfo.email}?subject=${encodeURIComponent(contactInfo.mailSubject)}`;
return (
<section id="contact" aria-labelledby="contact-heading" className="bg-brand text-on-brand">
<div className="mx-auto max-w-[1280px] px-6 pb-24 pt-20 sm:px-8 md:pb-[152px] md:pt-36">
@@ -33,24 +32,7 @@ export function ContactSection() {
{contactInfo.email}
</a>
</div>
<div
className="min-w-0 flex-[1.4_1_520px] bg-panel p-[clamp(24px,4vw,48px)] text-text"
data-testid="contact-panel"
>
<p className="mb-3 text-[clamp(28px,3vw,40px)] font-extrabold leading-none tracking-[-0.02em] [font-stretch:112%]">
Vertel wat je voor ogen hebt
</p>
<p className="mb-7 max-w-[44ch] text-body">
Stuur een bericht met je idee of vraag. Je krijgt binnen één werkdag reactie.
</p>
<a
href={mailtoHref}
className="inline-block bg-brand px-6 py-[18px] text-[17px] font-bold text-on-brand no-underline hover:opacity-90"
data-testid="contact-mailto-button"
>
Stuur een bericht
</a>
</div>
<ContactPanel />
</div>
</div>
</section>
@@ -0,0 +1,24 @@
import { contactInfo } from '../data/content';
/** Default state of the contact panel (and fallback): the mailto call-to-action. */
export function MailtoPanel() {
const mailtoHref = `mailto:${contactInfo.email}?subject=${encodeURIComponent(contactInfo.mailSubject)}`;
return (
<div data-testid="mailto-panel">
<p className="mb-3 text-[clamp(28px,3vw,40px)] font-extrabold leading-none tracking-[-0.02em] [font-stretch:112%]">
Vertel wat je voor ogen hebt
</p>
<p className="mb-7 max-w-[44ch] text-body">
Stuur een bericht met je idee of vraag. Je krijgt binnen één werkdag reactie.
</p>
<a
href={mailtoHref}
className="inline-block bg-brand px-6 py-[18px] text-[17px] font-bold text-on-brand no-underline hover:opacity-90"
data-testid="contact-mailto-button"
>
Stuur een bericht
</a>
</div>
);
}
+8
View File
@@ -194,6 +194,14 @@ export const aboutFacts: AboutFact[] = [
{ title: 'Vaste prijs', text: 'per pakket, vooraf bekend' },
];
/** Texts of the contact form (design B). */
export const contactForm = {
otherSubjectLabel: 'Overig',
successText: 'Je bericht is verstuurd. Je hoort binnen één werkdag van me.',
privacyNote:
'Je gegevens gebruik ik alleen om op je bericht te reageren; ik bewaar ze maximaal 12 maanden.',
};
export const contactInfo: ContactInfo = {
heading: 'Klaar om te bouwen?',
displayHeading: ['Klaar om', 'te bouwen?'],
@@ -0,0 +1,63 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { RefObject } from 'react';
import type { ContactClient, ContactToken, TokenResult } from '../../../cms-client/contact';
export type ContactAvailability =
{ status: 'unknown' } | { status: 'closed' } | { status: 'open'; token: ContactToken };
/**
* BR-U4-2/3: fetches the contact token once, when the contact section nears the viewport (or,
* without IntersectionObserver, on the first focus inside it). Only a 200 without captcha opens
* the form; every other outcome keeps the mailto panel.
*/
export function useContactAvailability(ref: RefObject<HTMLElement | null>, client: ContactClient) {
const [availability, setAvailability] = useState<ContactAvailability>({ status: 'unknown' });
const started = useRef(false);
const check = useCallback(async () => {
if (started.current) {
return;
}
started.current = true;
const result = await client.getToken();
if (result.kind === 'ok' && result.token.captcha === null) {
setAvailability({ status: 'open', token: result.token });
} else {
setAvailability({ status: 'closed' });
}
}, [client]);
useEffect(() => {
const element = ref.current;
if (!element) {
return;
}
if (typeof IntersectionObserver === 'function') {
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
observer.disconnect();
void check();
}
},
{ rootMargin: '300px 0px' },
);
observer.observe(element);
return () => observer.disconnect();
}
const onFocus = () => void check();
element.addEventListener('focusin', onFocus, { once: true });
return () => element.removeEventListener('focusin', onFocus);
}, [ref, check]);
/** Fetches a fresh token for the single refresh after `expired` (BR-U4-3). */
const refreshToken = useCallback(async (): Promise<TokenResult> => {
const result = await client.getToken();
if (result.kind === 'ok') {
setAvailability({ status: 'open', token: result.token });
}
return result;
}, [client]);
return { availability, refreshToken };
}
+4
View File
@@ -31,6 +31,7 @@ html[data-variant='b'][data-mode='light'] {
--color-panel: #ffffff;
--color-field: #f1efec;
--color-prog: #7a1414;
--color-danger: #b3261e;
}
html[data-variant='b'][data-mode='dark'] {
@@ -53,6 +54,7 @@ html[data-variant='b'][data-mode='dark'] {
--color-panel: #1c1918;
--color-field: #0f0e0e;
--color-prog: #e5524a;
--color-danger: #ff8a80;
}
html[data-variant='e'][data-mode='light'] {
@@ -75,6 +77,7 @@ html[data-variant='e'][data-mode='light'] {
--color-panel: #ffffff;
--color-field: #f3f3f3;
--color-prog: #ac0000;
--color-danger: #b3261e;
}
html[data-variant='e'][data-mode='dark'] {
@@ -97,6 +100,7 @@ html[data-variant='e'][data-mode='dark'] {
--color-panel: #232326;
--color-field: #1b1b1d;
--color-prog: #ff6b5e;
--color-danger: #ff8a80;
}
html {
+15
View File
@@ -0,0 +1,15 @@
interface UmamiGlobal {
track?: (event: string) => void;
}
/**
* Sends a named Umami event without any data (BR-U4-14). Does nothing when analytics is not
* loaded (local development, missing configuration, blocked script).
*/
export function trackEvent(name: string): void {
try {
(window as unknown as { umami?: UmamiGlobal }).umami?.track?.(name);
} catch {
// Analytics must never break the page.
}
}
+3
View File
@@ -54,6 +54,7 @@ describe('token contrast (NFR-1, WCAG AA)', () => {
'panel',
'field',
'prog',
'danger',
]) {
expect(t[name], name).toBeDefined();
}
@@ -71,6 +72,8 @@ describe('token contrast (NFR-1, WCAG AA)', () => {
['text', 'panel'],
['muted', 'panel'],
['text', 'field'],
['danger', 'panel'],
['danger', 'field'],
])('%s on %s has at least 4.5:1', (fg, bg) => {
expect(contrast(t[fg], t[bg]), `${fg} ${t[fg]} on ${bg} ${t[bg]}`).toBeGreaterThanOrEqual(
4.5,