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
@@ -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 };
}