Adds the Contact section to the homepage
Adds the contact form with the live fields, validation and browser-side anti-spam, behind a coming-soon notice with a mail button until the API exists. A "Boek" link on a price card selects its package, tidies the URL and moves focus to the form. The form loads only when it comes near the screen, so the hero does not wait for it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
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;
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mailSubject, mailtoLink } from './mailLink';
|
||||
|
||||
describe('mailSubject', () => {
|
||||
it('names the package when there is one', () => {
|
||||
expect(mailSubject('Newborn')).toBe('Aanvraag fotoshoot: Newborn');
|
||||
expect(mailSubject()).toBe('Vraag via andreaslop.nl');
|
||||
});
|
||||
|
||||
it('contains the package name whenever one is given (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.string({ minLength: 1 }), (name) => {
|
||||
expect(mailSubject(name)).toContain(name);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mailtoLink', () => {
|
||||
it('builds a mail link with an encoded subject', () => {
|
||||
expect(mailtoLink('a@b.nl', 'Aanvraag fotoshoot: Gezin')).toBe(
|
||||
'mailto:a@b.nl?subject=Aanvraag%20fotoshoot%3A%20Gezin',
|
||||
);
|
||||
});
|
||||
|
||||
it('gives back the subject when decoded (round-trip)', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.string(), (subject) => {
|
||||
const link = mailtoLink('a@b.nl', subject);
|
||||
expect(link.startsWith('mailto:a@b.nl?subject=')).toBe(true);
|
||||
const encoded = link.slice('mailto:a@b.nl?subject='.length);
|
||||
expect(decodeURIComponent(encoded)).toBe(subject);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// Subject of a mail from the site: the package when the visitor came via a
|
||||
// "Boek ..." link, otherwise a general one (BR-MAIL-01)
|
||||
export function mailSubject(packageName?: string): string {
|
||||
return packageName
|
||||
? `Aanvraag fotoshoot: ${packageName}`
|
||||
: 'Vraag via andreaslop.nl';
|
||||
}
|
||||
|
||||
export function mailtoLink(address: string, subject: string): string {
|
||||
return `mailto:${address}?subject=${encodeURIComponent(subject)}`;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import packages from '../content/packages';
|
||||
import { anyPackage } from '../test/arbitraries';
|
||||
import { OTHER_SHOOT, shootOptions } from './shootOptions';
|
||||
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' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('is the shown packages in order followed by Overig (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(fc.array(anyPackage), (input) => {
|
||||
const options = shootOptions(input);
|
||||
expect(options.at(-1)).toEqual(OTHER_SHOOT);
|
||||
expect(options.slice(0, -1)).toEqual(
|
||||
visiblePackages(input).map((pkg) => ({
|
||||
value: pkg.id,
|
||||
label: pkg.name,
|
||||
})),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ShootOption } from '../contact/types.ts';
|
||||
import type { PricingPackage } from '../content/types.ts';
|
||||
import { visiblePackages } from './visiblePackages.ts';
|
||||
|
||||
export const OTHER_SHOOT: ShootOption = { 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.
|
||||
export function shootOptions(
|
||||
packages: readonly PricingPackage[],
|
||||
): ShootOption[] {
|
||||
return [
|
||||
...visiblePackages(packages).map((pkg) => ({
|
||||
value: pkg.id,
|
||||
label: pkg.name,
|
||||
})),
|
||||
OTHER_SHOOT,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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());
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
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,143 @@
|
||||
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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user