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:
2026-11-10 23:21:02 +01:00
co-authored by Claude Sonnet 5.5
parent 4da314c0ba
commit e09459423f
46 changed files with 2402 additions and 1038 deletions
-174
View File
@@ -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;
}
}),
);
});
});
-118
View File
@@ -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;
}
}
-36
View File
@@ -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);
},
),
);
});
});
-16
View File
@@ -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;
}
+5 -5
View File
@@ -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,
})),
);
+9 -5
View File
@@ -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,
-34
View File
@@ -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());
}
}),
);
});
});
-11
View File
@@ -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(),
};
}
+13
View File
@@ -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
}
}
-143
View File
@@ -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);
}
}),
);
});
});
-76
View File
@@ -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;
}