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
@@ -0,0 +1,81 @@
import { useEffect, useRef } from 'react';
import { Box } from '@chakra-ui/react';
import type { WidgetHandle } from '@friendlycaptcha/sdk';
import type { CaptchaInfo } from '@/cms-client/contact';
// Room kept for the widget, so nothing below it jumps when it appears
export const CAPTCHA_HEIGHT = '76px';
type CaptchaWidgetProps = {
captcha: CaptchaInfo;
// Goes up after every send attempt: a response can be used only once, so
// the widget starts over
resetCount: number;
// The response when solved, null when it expired or failed
onToken: (token: string | null) => void;
};
// The Friendly Captcha v2 widget (the bundled @friendlycaptcha/sdk). Client
// only: it is a separate chunk that loads when the form is open and needs a
// captcha, never part of the prerendered page. The visitor starts it by
// focusing the form (startMode "focus"). The API region comes from the
// server (token response), not from the site.
export default function CaptchaWidget({
captcha,
resetCount,
onToken,
}: CaptchaWidgetProps) {
const element = useRef<HTMLDivElement>(null);
const widget = useRef<WidgetHandle | null>(null);
const latestOnToken = useRef(onToken);
useEffect(() => {
latestOnToken.current = onToken;
}, [onToken]);
const { siteKey, apiEndpoint } = captcha;
useEffect(() => {
let cancelled = false;
let handle: WidgetHandle | null = null;
import('@friendlycaptcha/sdk').then(({ FriendlyCaptchaSDK }) => {
if (cancelled || !element.current) return;
const sdk = new FriendlyCaptchaSDK({ apiEndpoint });
handle = sdk.createWidget({
element: element.current,
sitekey: siteKey,
language: 'nl',
theme: 'light',
startMode: 'focus',
});
widget.current = handle;
handle.addEventListener('frc:widget.complete', (event) =>
latestOnToken.current(event.detail.response),
);
handle.addEventListener('frc:widget.expire', () =>
latestOnToken.current(null),
);
handle.addEventListener('frc:widget.error', () =>
latestOnToken.current(null),
);
});
return () => {
cancelled = true;
handle?.destroy();
widget.current = null;
};
}, [siteKey, apiEndpoint]);
// A used response is gone: start the widget over after each attempt
useEffect(() => {
if (resetCount === 0) return;
widget.current?.reset();
latestOnToken.current(null);
}, [resetCount]);
return (
<Box
ref={element}
minH={CAPTCHA_HEIGHT}
data-testid="contact-form-captcha"
/>
);
}
@@ -1,21 +1,89 @@
import { useState } from 'react';
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type {
CaptchaInfo,
ContactClient,
ContactToken,
SubmitResult,
} from '@/cms-client/contact';
import packages from '@/content/packages';
import siteContent from '@/content/siteContent';
import { shootOptions } from '@/lib/shootOptions';
import { axeResults } from '@/test/axe';
import { serverHtml } from '@/test/hydrate';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactForm from './ContactForm';
import ContactForm, { type FormAvailability } from './ContactForm';
// A stand-in for the Friendly Captcha SDK: widgets the test can solve,
// expire and watch
const sdk = vi.hoisted(() => {
type Listener = (event: { detail: { response: string } }) => void;
class FakeWidget {
listeners = new Map<string, Listener>();
reset = vi.fn();
destroy = vi.fn();
options: Record<string, unknown>;
constructor(options: Record<string, unknown>) {
this.options = options;
}
addEventListener(type: string, listener: Listener) {
this.listeners.set(type, listener);
}
emit(type: string, response = '') {
this.listeners.get(type)?.({ detail: { response } });
}
}
const state = {
widgets: [] as FakeWidget[],
sdkOptions: [] as unknown[],
};
class FriendlyCaptchaSDK {
constructor(options: unknown) {
state.sdkOptions.push(options);
}
createWidget(options: Record<string, unknown>) {
const widget = new FakeWidget(options);
state.widgets.push(widget);
return widget;
}
}
return { state, FriendlyCaptchaSDK };
});
vi.mock('@friendlycaptcha/sdk', () => ({
FriendlyCaptchaSDK: sdk.FriendlyCaptchaSDK,
}));
const options = shootOptions(packages);
const CAPTCHA: CaptchaInfo = {
provider: 'friendlycaptcha',
siteKey: 'FCMTEST',
apiEndpoint: 'global',
};
// The time check needs over 3 s between showing and sending (BR-SPAM-01)
let now = 0;
const tokenWith = (captcha: CaptchaInfo | null): ContactToken => ({
token: 'signed-token',
minSeconds: 3,
captcha,
});
let submit: ReturnType<typeof vi.fn>;
let refreshToken: ReturnType<typeof vi.fn>;
let client: ContactClient;
beforeEach(() => {
now = 0;
vi.spyOn(Date, 'now').mockImplementation(() => now);
sdk.state.widgets.length = 0;
sdk.state.sdkOptions.length = 0;
submit = vi.fn().mockResolvedValue({ kind: 'ok' } satisfies SubmitResult);
refreshToken = vi.fn().mockResolvedValue({ kind: 'failed' });
client = {
getToken: vi.fn(),
submit: submit as unknown as ContactClient['submit'],
};
});
const open = (captcha: CaptchaInfo | null = null): FormAvailability => ({
token: tokenWith(captcha),
refreshToken: refreshToken as unknown as FormAvailability['refreshToken'],
});
const renderForm = (
@@ -25,10 +93,10 @@ const renderForm = (
<ContactForm
idPrefix="test"
options={options}
mailSubject="Vraag via andreaslop.nl"
email={siteContent.email}
replyTime="1-2 werkdagen"
submit={vi.fn().mockResolvedValue(undefined)}
availability={open()}
client={client}
{...props}
/>,
);
@@ -39,13 +107,10 @@ const type = (name: string, value: string) =>
const fillIn = () => {
type('naam', 'Demi');
type('email', 'demi@example.nl');
type('shoot', 'newborn');
type('shoot', 'Newborn');
type('bericht', 'Wanneer heb je plek?');
};
const send = () => {
now = 10_000;
fireEvent.click(screen.getByTestId('contact-form-submit'));
};
const send = () => fireEvent.click(screen.getByTestId('contact-form-submit'));
describe('ContactForm', () => {
it('shows the four labelled fields and the button', async () => {
@@ -65,67 +130,59 @@ describe('ContactForm', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows nothing when tabbing through an untouched field', async () => {
it('offers the package names and Overig as shoots, the label being the value', async () => {
await renderForm();
fireEvent.blur(field('naam'));
expect(screen.queryByText('Vul je naam in.')).toBeNull();
});
it('checks a field on leaving once typed in, and clears it once fine', async () => {
await renderForm();
type('email', 'demi@');
fireEvent.blur(field('email'));
expect(
screen.getByText('Dit e-mailadres is ongeldig.'),
).toBeInTheDocument();
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
type('email', 'demi@example.nl');
expect(screen.queryByText('Dit e-mailadres is ongeldig.')).toBeNull();
const values = [...field('shoot').querySelectorAll('option')].map(
(option) => option.getAttribute('value'),
);
expect(values).toEqual([
'',
...packages.map((pkg) => pkg.name),
'Overig',
]);
});
it('stops an incomplete submit and focuses the first invalid field', async () => {
const submit = vi.fn();
await renderForm({ submit });
await renderForm();
type('naam', 'Demi');
send();
expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument();
expect(screen.getByText('Kies een soort shoot.')).toBeInTheDocument();
expect(screen.getByText('Kies een onderwerp.')).toBeInTheDocument();
expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument();
expect(field('email')).toHaveFocus();
await waitFor(() => expect(field('email')).toHaveFocus());
expect(field('email')).toHaveAttribute('aria-invalid', 'true');
expect(submit).not.toHaveBeenCalled();
});
it('sends the trimmed form and shows the thank-you with focus', async () => {
const submit = vi.fn().mockResolvedValue(undefined);
await renderForm({ submit });
it('sends the trimmed form with the token and the label as subject', async () => {
await renderForm();
fillIn();
type('naam', ' Demi ');
send();
expect(screen.getByTestId('contact-form-submit')).toHaveTextContent(
'Versturen…',
);
expect(submit).toHaveBeenCalledWith({
naam: 'Demi',
await screen.findByTestId('contact-form-sent');
expect(submit).toHaveBeenCalledTimes(1);
const [payload, context] = submit.mock.calls[0];
expect(payload).toEqual({
name: 'Demi',
email: 'demi@example.nl',
shoot: 'newborn',
bericht: 'Wanneer heb je plek?',
subject: 'Newborn',
message: 'Wanneer heb je plek?',
hpCheck: '',
token: 'signed-token',
});
const thanks = await screen.findByTestId('contact-form-sent');
expect(thanks).toHaveTextContent(
'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.',
);
await waitFor(() => expect(thanks).toHaveFocus());
expect(screen.queryByTestId('contact-form')).toBeNull();
expect(context.idempotencyKey).toMatch(/^[0-9a-f-]{36}$/);
});
it('takes the reply time for the thank-you from the content', async () => {
it('shows the thank-you with focus and takes the reply time from the content', async () => {
await renderForm({ replyTime: '3 werkdagen' });
fillIn();
send();
expect(
await screen.findByTestId('contact-form-sent'),
).toHaveTextContent('Ik reageer binnen 3 werkdagen.');
const thanks = await screen.findByTestId('contact-form-sent');
expect(thanks).toHaveTextContent(
'Bedankt voor je bericht! Ik reageer binnen 3 werkdagen.',
);
await waitFor(() => expect(thanks).toHaveFocus());
expect(screen.queryByTestId('contact-form')).toBeNull();
});
it('shows the privacy line under the submit button', async () => {
@@ -137,65 +194,62 @@ describe('ContactForm', () => {
).toHaveAttribute('href', '/privacyverklaring');
});
it('keeps the input and offers the mail link when sending fails', async () => {
await renderForm({ submit: vi.fn().mockRejectedValue(new Error('x')) });
it('keeps the input and names the address when sending fails', async () => {
submit.mockResolvedValue({ kind: 'failed' });
await renderForm();
fillIn();
send();
const status = await screen.findByRole('alert');
expect(status).toHaveTextContent(
'Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl',
);
expect(
screen.getByRole('link', { name: 'info@andreaslop.nl' }),
).toHaveAttribute(
'href',
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
);
expect(field('naam')).toHaveValue('Demi');
expect(screen.getByTestId('contact-form-submit')).not.toBeDisabled();
await waitFor(() =>
expect(
screen.getByTestId('contact-form-submit'),
).not.toBeDisabled(),
);
});
it('uses the text of the package for a rate limit (minutes from Retry-After)', async () => {
submit.mockResolvedValue({
kind: 'rateLimited',
retryAfterSeconds: 120,
});
await renderForm();
fillIn();
send();
expect(await screen.findByRole('alert')).toHaveTextContent(
'Je hebt net al een bericht gestuurd. Probeer het over 2 minuten opnieuw.',
);
});
it('treats a filled honeypot as spam: thank-you, nothing sent', async () => {
const submit = vi.fn();
const { container } = await renderForm({ submit });
const { container } = await renderForm();
fillIn();
fireEvent.change(
container.querySelector('input[name="website"]') as Element,
{ target: { value: 'https://spam.example' } },
);
fireEvent.change(container.querySelector('input[name="test-hp"]')!, {
target: { value: 'https://spam.example' },
});
send();
expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument();
expect(
await screen.findByTestId('contact-form-sent'),
).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
});
it('treats a submit within 3 seconds as spam', async () => {
const submit = vi.fn();
await renderForm({ submit });
fillIn();
now = 1_000;
fireEvent.click(screen.getByTestId('contact-form-submit'));
expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
it('keeps the honeypot away from people and assistive technology', async () => {
const { container } = await renderForm();
const honeypot = container.querySelector('input[name="test-hp"]');
expect(honeypot).toHaveAttribute('tabindex', '-1');
expect(honeypot).toHaveAttribute('autocomplete', 'off');
expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull();
});
it('ignores a second submit while sending', async () => {
let finish = () => {};
const submit = vi.fn(
() => new Promise<void>((resolve) => (finish = resolve)),
);
await renderForm({ submit });
fillIn();
send();
fireEvent.click(screen.getByTestId('contact-form-submit'));
expect(submit).toHaveBeenCalledTimes(1);
await act(async () => finish());
});
it('takes over a preselected package, also again after a change', async () => {
it('applies a choice made before the form existed, and later clicks too', async () => {
// A second "Boek" click for the same package raises the key
function Harness() {
const [preselect, setPreselect] = useState({
shoot: 'newborn',
subject: 'Newborn',
key: 1,
});
return (
@@ -212,44 +266,142 @@ describe('ContactForm', () => {
idPrefix="test"
options={options}
preselect={preselect}
mailSubject="Vraag via andreaslop.nl"
email={siteContent.email}
replyTime="1-2 werkdagen"
availability={open()}
client={client}
/>
</>
);
}
await renderWithProviders(<Harness />);
expect(field('shoot')).toHaveValue('newborn');
type('shoot', 'gezin');
expect(field('shoot')).toHaveValue('gezin');
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
type('shoot', 'Gezin');
expect(field('shoot')).toHaveValue('Gezin');
fireEvent.click(screen.getByRole('button', { name: 'nog eens' }));
expect(field('shoot')).toHaveValue('newborn');
await waitFor(() => expect(field('shoot')).toHaveValue('Newborn'));
});
it('keeps the honeypot away from people and assistive technology', async () => {
const { container } = await renderForm();
const honeypot = container.querySelector('input[name="website"]');
expect(honeypot).toHaveAttribute('tabindex', '-1');
expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull();
expect(container.querySelector('[data-robot-check]')).not.toBeNull();
it('sends a label with special characters unchanged', async () => {
const special = `Zwanger & "mooi" <b>'s`;
await renderForm({
options: [{ value: special, label: special }],
});
type('naam', 'Demi');
type('email', 'demi@example.nl');
type('shoot', special);
type('bericht', 'Hoi');
send();
await screen.findByTestId('contact-form-sent');
expect(submit.mock.calls[0][0].subject).toBe(special);
});
});
describe('ContactForm with a captcha', () => {
const lastWidget = () => sdk.state.widgets[sdk.state.widgets.length - 1];
const widget = async () => {
await waitFor(() => expect(sdk.state.widgets).toHaveLength(1));
return lastWidget();
};
it('mounts the widget with the key and region from the server', async () => {
await renderForm({
availability: open({ ...CAPTCHA, apiEndpoint: 'eu' }),
});
const created = await widget();
expect(created.options).toMatchObject({
sitekey: 'FCMTEST',
language: 'nl',
startMode: 'focus',
});
expect(sdk.state.sdkOptions[0]).toEqual({ apiEndpoint: 'eu' });
expect(screen.getByTestId('contact-form-captcha')).toBeInTheDocument();
});
it('sends nothing and says so until the captcha is solved', async () => {
await renderForm({ availability: open(CAPTCHA) });
await widget();
fillIn();
send();
expect(
await screen.findByText('Bevestig eerst dat je geen robot bent.'),
).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
});
it('sends the solved response with the form', async () => {
await renderForm({ availability: open(CAPTCHA) });
const created = await widget();
fillIn();
act(() => created.emit('frc:widget.complete', 'solved-response'));
send();
await screen.findByTestId('contact-form-sent');
expect(submit.mock.calls[0][0].captchaToken).toBe('solved-response');
});
it('never sends an expired response', async () => {
await renderForm({ availability: open(CAPTCHA) });
const created = await widget();
fillIn();
act(() => created.emit('frc:widget.complete', 'old-response'));
act(() => created.emit('frc:widget.expire', '.EXPIRED'));
send();
expect(
await screen.findByText('Bevestig eerst dat je geen robot bent.'),
).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
});
it('never sends a response of a failed widget', async () => {
await renderForm({ availability: open(CAPTCHA) });
const created = await widget();
fillIn();
act(() => created.emit('frc:widget.complete', 'a-response'));
act(() => created.emit('frc:widget.error', '.ERROR'));
send();
await screen.findByText('Bevestig eerst dat je geen robot bent.');
expect(submit).not.toHaveBeenCalled();
});
it('resets the widget after a send attempt (a response is single-use)', async () => {
submit.mockResolvedValue({ kind: 'failed' });
await renderForm({ availability: open(CAPTCHA) });
const created = await widget();
fillIn();
act(() => created.emit('frc:widget.complete', 'r1'));
send();
await screen.findByRole('alert');
await waitFor(() => expect(created.reset).toHaveBeenCalled());
});
it('destroys the widget when the form goes away', async () => {
const { unmount } = await renderForm({ availability: open(CAPTCHA) });
const created = await widget();
unmount();
expect(created.destroy).toHaveBeenCalled();
});
it('shows no widget without a captcha', async () => {
await renderForm();
expect(screen.queryByTestId('contact-form-captcha')).toBeNull();
expect(sdk.state.widgets).toHaveLength(0);
});
});
describe('ContactForm in the prerendered HTML', () => {
it('does not hold the address (BR-MAIL-06)', async () => {
it('does not hold the address, a token or a widget (BR-MAIL-06)', async () => {
const html = await serverHtml(
<ContactForm
idPrefix="test"
options={options}
mailSubject="Vraag via andreaslop.nl"
email={siteContent.email}
replyTime="1-2 werkdagen"
submit={vi.fn()}
/>,
);
expect(html).toContain('contact-form-submit');
expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
expect(html).not.toContain('mailto:');
expect(html).not.toContain('signed-token');
expect(html).not.toContain('contact-form-captcha');
});
});
+124 -140
View File
@@ -1,10 +1,9 @@
import { useEffect, useRef, useState, useReducer } from 'react';
import { lazy, Suspense, useEffect, useRef } from 'react';
import {
Box,
chakra,
Field,
Input,
Link,
NativeSelect,
SimpleGrid,
Stack,
@@ -13,89 +12,107 @@ import {
useRecipe,
} from '@chakra-ui/react';
import PrivacyNote from '@/components/PrivacyNote/PrivacyNote';
import { submitContactForm } from '@/contact/submitContactForm';
import {
CONTACT_LIMITS,
useContactForm,
type ContactClient,
type ContactField,
type ContactPayload,
type ShootOption,
} from '@/contact/types';
type ContactToken,
type SubjectOption,
type TokenResult,
} from '@/cms-client/contact';
import { contactClient } from '@/contact/contactClient';
import type { EmailAddress } from '@/content/types';
import {
contactFormReducer,
INITIAL_CONTACT_STATE,
type ContactFormEvent,
} from '@/lib/contactFormReducer';
import useEmailAddress from '@/hooks/useEmailAddress';
import { mailtoLink } from '@/lib/mailLink';
import { toContactPayload } from '@/lib/toContactPayload';
import { CONTACT_FIELDS } from '@/lib/validateContact';
import { trackContactEvent } from '@/lib/trackEvent';
import { CAPTCHA_HEIGHT } from './CaptchaWidget';
// What the form needs once the server said it is open
export type FormAvailability = {
token: ContactToken;
refreshToken: () => Promise<TokenResult>;
};
// Behind the gate the form is only a dimmed picture (inert), so it needs no
// real token and never sends anything
// The widget is its own chunk (SDK included), loaded only when needed
const CaptchaWidget = lazy(() => import('./CaptchaWidget'));
const PREVIEW_AVAILABILITY: FormAvailability = {
token: { token: '', minSeconds: 0, captcha: null },
refreshToken: async () => ({ kind: 'failed' }),
};
type ContactFormProps = {
// Prefix for the field ids, so the form can appear on more than one page
idPrefix: string;
options: ShootOption[];
// A package chosen via "Boek ..."; key changes on every click, so the
// same package can be applied again after the visitor changed it
preselect?: { shoot: string; key: number };
mailSubject: string;
// Value and label are the same text: the label is what is sent as subject
options: SubjectOption[];
// A package chosen via "Boek ..." (its label); key changes on every
// click, so the same package can be applied again after a change
preselect?: { subject: string; key: number };
email: EmailAddress;
// How soon Andrea answers, e.g. '1-2 werkdagen' (siteContent)
replyTime: string;
submit?: (payload: ContactPayload) => Promise<void>;
// Null while the form is only shown behind the gate
availability?: FormAvailability | null;
client?: ContactClient;
};
// The test ids keep the Dutch field names of the page; the package fields
// are English
const FIELD_TEST_ID: Record<ContactField, string> = {
name: 'naam',
email: 'email',
subject: 'shoot',
message: 'bericht',
};
// The contact form (design .form): name and e-mail, the shoot, the question,
// and the browser-side anti-spam. Its behaviour is the pure
// contactFormReducer; this component wires it to the fields.
// and the browser-side honeypot. Its behaviour (validation, sending, token
// refresh) is the headless useContactForm of the cms-client package; this
// component is only the skin.
export default function ContactForm({
idPrefix,
options,
preselect,
mailSubject,
email,
replyTime,
submit = submitContactForm,
availability = null,
client = contactClient,
}: ContactFormProps) {
const reduce = (
state: typeof INITIAL_CONTACT_STATE,
event: ContactFormEvent,
) => contactFormReducer(state, event, options);
const [state, dispatch] = useReducer(reduce, INITIAL_CONTACT_STATE);
const formControl = useRecipe({ key: 'formControl' });
const linkButton = useRecipe({ key: 'linkButton' });
// When the form became usable, for the time check (BR-SPAM-01)
const [shownAt] = useState(() => Date.now());
const honeypot = useRef<HTMLInputElement>(null);
const { address } = useEmailAddress(email);
const sentMessage = useRef<HTMLDivElement>(null);
// Apply a new "Boek ..." choice while rendering (React's pattern for
// reacting to a changed prop), so it never shows a stale value first
const [seenPreselect, setSeenPreselect] = useState(0);
if (preselect && preselect.key !== seenPreselect) {
setSeenPreselect(preselect.key);
dispatch({ type: 'preselect', shoot: preselect.shoot });
}
// After a stopped submit, focus the first field with an error
useEffect(() => {
if (state.invalidSubmits === 0) return;
const first = CONTACT_FIELDS.find((field) => state.errors[field]);
if (first) document.getElementById(`${idPrefix}-${first}`)?.focus();
// Only on a new stopped submit, not on every error change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.invalidSubmits]);
const { token, refreshToken } = availability ?? PREVIEW_AVAILABILITY;
const form = useContactForm({
idPrefix,
subjectOptions: options,
// A choice made before the form existed is applied at the start,
// later clicks through the changing key
preselect,
initialSubject: preselect?.subject ?? null,
client,
token,
refreshToken,
fallbackAddress: address ?? '',
onEvent: (event) =>
trackContactEvent(
event === 'sent' ? 'contact-sent' : 'contact-failed',
),
});
// The thank-you replaces the form; move focus there (BR-SEND-02)
const { status } = form;
useEffect(() => {
if (state.status === 'sent') sentMessage.current?.focus();
}, [state.status]);
if (status === 'sent') sentMessage.current?.focus();
}, [status]);
const { address } = useEmailAddress(email);
const disabled = state.status === 'sending';
const disabled = status === 'sending';
if (state.status === 'sent') {
if (status === 'sent') {
return (
<Box
ref={sentMessage}
@@ -112,39 +129,14 @@ export default function ContactForm({
);
}
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const submitEvent: ContactFormEvent = {
type: 'submit',
honeypot: honeypot.current?.value ?? '',
shownAt,
now: Date.now(),
};
// Sending starts here, not in an effect, so it happens exactly once
const next = reduce(state, submitEvent);
dispatch(submitEvent);
if (next.status === 'sending') {
submit(toContactPayload(state.values)).then(
() => dispatch({ type: 'resolved' }),
() => dispatch({ type: 'rejected' }),
);
}
};
// The control's id comes from Field.Root's id (Ark uses it for the
// control and the label's htmlFor), so label and error stay linked
const fieldProps = (field: ContactField) => ({
name: field,
value: state.values[field],
onChange: (
event: React.ChangeEvent<
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
>,
) => dispatch({ type: 'edit', field, value: event.target.value }),
onBlur: () => dispatch({ type: 'blur', field }),
// The control's id comes from the hook (the same id Field.Root gets), so
// label, input and error stay linked
const control = (field: ContactField) => ({
...form.getFieldProps(field).inputProps,
css: formControl(),
'data-testid': `contact-form-${field}`,
'data-testid': `contact-form-${FIELD_TEST_ID[field]}`,
});
const fieldId = (field: ContactField) => `${idPrefix}-${field}`;
const label = (text: string) => (
// ink.soft instead of the design's muted grey: meets 4.5:1
@@ -152,44 +144,49 @@ export default function ContactForm({
{text}
</Field.Label>
);
const error = (field: ContactField) => (
<Field.ErrorText color="error" fontSize="sm">
{state.errors[field]}
</Field.ErrorText>
);
// Outside the label, so the accessible name of the field stays clean
const error = (field: ContactField) => {
const { error: message, errorId } = form.getFieldProps(field);
return (
<Field.ErrorText id={errorId} color="error" fontSize="sm">
{message}
</Field.ErrorText>
);
};
const invalid = (field: ContactField) =>
Boolean(form.getFieldProps(field).error);
return (
<chakra.form
noValidate
onSubmit={onSubmit}
{...form.formProps}
data-testid="contact-form"
position="relative"
>
<Stack gap={6}>
<SimpleGrid columns={{ base: 1, sm: 2 }} gap={6}>
<Field.Root
invalid={Boolean(state.errors.naam)}
invalid={invalid('name')}
required
id={`${idPrefix}-naam`}
id={fieldId('name')}
>
{label('Naam')}
<Input
{...fieldProps('naam')}
{...control('name')}
type="text"
autoComplete="name"
maxLength={CONTACT_LIMITS.naam}
maxLength={CONTACT_LIMITS.name}
placeholder="Jouw naam"
/>
{error('naam')}
{error('name')}
</Field.Root>
<Field.Root
invalid={Boolean(state.errors.email)}
invalid={invalid('email')}
required
id={`${idPrefix}-email`}
id={fieldId('email')}
>
{label('E-mail')}
<Input
{...fieldProps('email')}
{...control('email')}
type="email"
autoComplete="email"
maxLength={CONTACT_LIMITS.email}
@@ -200,13 +197,13 @@ export default function ContactForm({
</SimpleGrid>
<Field.Root
invalid={Boolean(state.errors.shoot)}
invalid={invalid('subject')}
required
id={`${idPrefix}-shoot`}
id={fieldId('subject')}
>
{label('In welke shoot heb je interesse?')}
<NativeSelect.Root>
<NativeSelect.Field {...fieldProps('shoot')}>
<NativeSelect.Field {...control('subject')}>
<option value="">Kies een optie...</option>
{options.map((option) => (
<option key={option.value} value={option.value}>
@@ -216,27 +213,27 @@ export default function ContactForm({
</NativeSelect.Field>
<NativeSelect.Indicator />
</NativeSelect.Root>
{error('shoot')}
{error('subject')}
</Field.Root>
<Field.Root
invalid={Boolean(state.errors.bericht)}
invalid={invalid('message')}
required
id={`${idPrefix}-bericht`}
id={fieldId('message')}
>
{label('Stel hier je vraag')}
<Textarea
{...fieldProps('bericht')}
maxLength={CONTACT_LIMITS.bericht}
{...control('message')}
maxLength={CONTACT_LIMITS.message}
placeholder="Vul hier je bericht in"
minH="170px"
resize="vertical"
/>
{error('bericht')}
{error('message')}
</Field.Root>
{/* Honeypot: off-screen and hidden from assistive
technology; only bots fill it in (BR-SPAM-01) */}
technology; only bots fill it in */}
<Box
aria-hidden="true"
position="absolute"
@@ -245,22 +242,22 @@ export default function ContactForm({
h="1px"
overflow="hidden"
>
<label htmlFor={`${idPrefix}-website`}>Website</label>
<input
ref={honeypot}
id={`${idPrefix}-website`}
name="website"
type="text"
tabIndex={-1}
autoComplete="off"
/>
<input {...form.honeypotProps} type="text" />
</Box>
{/* Place for the robot check (Friendly Captcha), added with
the API (FR-HP-09) */}
<div data-robot-check />
{/* The robot check (Friendly Captcha) when the server asks
for it; its room is kept while the widget loads */}
{form.captcha && (
<Suspense fallback={<Box minH={CAPTCHA_HEIGHT} />}>
<CaptchaWidget
captcha={form.captcha}
resetCount={form.captchaResetCount}
onToken={form.setCaptchaToken}
/>
</Suspense>
)}
{state.status === 'failed' && (
{form.failureMessage && (
<Box
role="alert"
data-testid="contact-form-status"
@@ -270,22 +267,7 @@ export default function ContactForm({
bg="paper.alt"
fontSize="sm"
>
<Text>
Versturen lukte niet. Probeer het later nog eens
{address ? (
<>
{' of mail naar '}
<Link
variant="underline"
href={mailtoLink(address, mailSubject)}
>
{address}
</Link>
</>
) : (
'.'
)}
</Text>
<Text>{form.failureMessage}</Text>
</Box>
)}
@@ -297,7 +279,9 @@ export default function ContactForm({
cursor={disabled ? 'progress' : 'pointer'}
data-testid="contact-form-submit"
>
{disabled ? 'Versturen…' : '(Aan)vraag versturen'}
{disabled
? form.messages.sendingLabel
: '(Aan)vraag versturen'}
</chakra.button>
{/* Under the submit button, aligned with it */}
<PrivacyNote textAlign="end" />