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:
2026-10-21 00:36:43 +02:00
co-authored by Claude Opus 5.5
parent 0b8e8d5f8b
commit 0fce403ebc
46 changed files with 2505 additions and 16 deletions
@@ -0,0 +1,216 @@
import { useState } from 'react';
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import packages from '@/content/packages';
import siteContent from '@/content/siteContent';
import { shootOptions } from '@/lib/shootOptions';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactForm from './ContactForm';
const options = shootOptions(packages);
// The time check needs over 3 s between showing and sending (BR-SPAM-01)
let now = 0;
beforeEach(() => {
now = 0;
vi.spyOn(Date, 'now').mockImplementation(() => now);
});
const renderForm = (
props: Partial<React.ComponentProps<typeof ContactForm>> = {},
) =>
renderWithProviders(
<ContactForm
idPrefix="test"
options={options}
mailSubject="Vraag via andreaslop.nl"
email={siteContent.email}
submit={vi.fn().mockResolvedValue(undefined)}
{...props}
/>,
);
const field = (name: string) => screen.getByTestId(`contact-form-${name}`);
const type = (name: string, value: string) =>
fireEvent.change(field(name), { target: { value } });
const fillIn = () => {
type('naam', 'Demi');
type('email', 'demi@example.nl');
type('shoot', 'newborn');
type('bericht', 'Wanneer heb je plek?');
};
const send = () => {
now = 10_000;
fireEvent.click(screen.getByTestId('contact-form-submit'));
};
describe('ContactForm', () => {
it('shows the four labelled fields and the button', async () => {
const { container } = await renderForm();
expect(screen.getByLabelText(/Naam/)).toBe(field('naam'));
expect(screen.getByLabelText(/E-mail/)).toBe(field('email'));
expect(screen.getByLabelText(/In welke shoot/)).toBe(field('shoot'));
expect(screen.getByLabelText(/Stel hier je vraag/)).toBe(
field('bericht'),
);
expect(
screen.getByRole('option', { name: 'Kies een optie...' }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: '(Aan)vraag versturen' }),
).toBeInTheDocument();
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows nothing when tabbing through an untouched field', 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();
});
it('stops an incomplete submit and focuses the first invalid field', async () => {
const submit = vi.fn();
await renderForm({ submit });
type('naam', 'Demi');
send();
expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument();
expect(screen.getByText('Kies een soort shoot.')).toBeInTheDocument();
expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument();
expect(field('email')).toHaveFocus();
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 });
fillIn();
type('naam', ' Demi ');
send();
expect(screen.getByTestId('contact-form-submit')).toHaveTextContent(
'Versturen…',
);
expect(submit).toHaveBeenCalledWith({
naam: 'Demi',
email: 'demi@example.nl',
shoot: 'newborn',
bericht: 'Wanneer heb je plek?',
});
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();
});
it('keeps the input and offers the mail link when sending fails', async () => {
await renderForm({ submit: vi.fn().mockRejectedValue(new Error('x')) });
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();
});
it('treats a filled honeypot as spam: thank-you, nothing sent', async () => {
const submit = vi.fn();
const { container } = await renderForm({ submit });
fillIn();
fireEvent.change(
container.querySelector('input[name="website"]') as Element,
{ target: { value: 'https://spam.example' } },
);
send();
expect(screen.getByTestId('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('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 () => {
// A second "Boek" click for the same package raises the key
function Harness() {
const [preselect, setPreselect] = useState({
shoot: 'newborn',
key: 1,
});
return (
<>
<button
type="button"
onClick={() =>
setPreselect((p) => ({ ...p, key: p.key + 1 }))
}
>
nog eens
</button>
<ContactForm
idPrefix="test"
options={options}
preselect={preselect}
mailSubject="Vraag via andreaslop.nl"
email={siteContent.email}
/>
</>
);
}
await renderWithProviders(<Harness />);
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');
});
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();
});
});
@@ -0,0 +1,304 @@
import { useEffect, useRef, useState, useReducer } from 'react';
import {
Box,
chakra,
Field,
Input,
Link,
NativeSelect,
SimpleGrid,
Stack,
Text,
Textarea,
useRecipe,
} from '@chakra-ui/react';
import { submitContactForm } from '@/contact/submitContactForm';
import {
CONTACT_LIMITS,
type ContactField,
type ContactPayload,
type ShootOption,
} from '@/contact/types';
import type { EmailAddress } from '@/content/types';
import {
contactFormReducer,
INITIAL_CONTACT_STATE,
type ContactFormEvent,
} from '@/lib/contactFormReducer';
import { emailAddress } from '@/lib/emailAddress';
import { mailtoLink } from '@/lib/mailLink';
import { toContactPayload } from '@/lib/toContactPayload';
import { CONTACT_FIELDS } from '@/lib/validateContact';
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;
email: EmailAddress;
submit?: (payload: ContactPayload) => Promise<void>;
};
const SENT_MESSAGE =
'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.';
// 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.
export default function ContactForm({
idPrefix,
options,
preselect,
mailSubject,
email,
submit = submitContactForm,
}: 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 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]);
// The thank-you replaces the form; move focus there (BR-SEND-02)
useEffect(() => {
if (state.status === 'sent') sentMessage.current?.focus();
}, [state.status]);
const address = emailAddress(email);
const disabled = state.status === 'sending';
if (state.status === 'sent') {
return (
<Box
ref={sentMessage}
role="status"
tabIndex={-1}
data-testid="contact-form-sent"
p={6}
borderStartWidth="2px"
borderStartColor="accent"
bg="paper.alt"
>
{SENT_MESSAGE}
</Box>
);
}
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 }),
css: formControl(),
'data-testid': `contact-form-${field}`,
});
const label = (text: string) => (
// ink.soft instead of the design's muted grey: meets 4.5:1
<Field.Label textStyle="eyebrow" color="ink.soft" fontWeight="400">
{text}
</Field.Label>
);
const error = (field: ContactField) => (
<Field.ErrorText color="error" fontSize="sm">
{state.errors[field]}
</Field.ErrorText>
);
return (
<chakra.form
noValidate
onSubmit={onSubmit}
data-testid="contact-form"
position="relative"
>
<Stack gap={6}>
<SimpleGrid columns={{ base: 1, sm: 2 }} gap={6}>
<Field.Root
invalid={Boolean(state.errors.naam)}
required
id={`${idPrefix}-naam`}
>
{label('Naam')}
<Input
{...fieldProps('naam')}
type="text"
autoComplete="name"
maxLength={CONTACT_LIMITS.naam}
placeholder="Jouw naam"
/>
{error('naam')}
</Field.Root>
<Field.Root
invalid={Boolean(state.errors.email)}
required
id={`${idPrefix}-email`}
>
{label('E-mail')}
<Input
{...fieldProps('email')}
type="email"
autoComplete="email"
maxLength={CONTACT_LIMITS.email}
placeholder="jouw@email.nl"
/>
{error('email')}
</Field.Root>
</SimpleGrid>
<Field.Root
invalid={Boolean(state.errors.shoot)}
required
id={`${idPrefix}-shoot`}
>
{label('In welke shoot heb je interesse?')}
<NativeSelect.Root>
<NativeSelect.Field {...fieldProps('shoot')}>
<option value="">Kies een optie...</option>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</NativeSelect.Field>
<NativeSelect.Indicator />
</NativeSelect.Root>
{error('shoot')}
</Field.Root>
<Field.Root
invalid={Boolean(state.errors.bericht)}
required
id={`${idPrefix}-bericht`}
>
{label('Stel hier je vraag')}
<Textarea
{...fieldProps('bericht')}
maxLength={CONTACT_LIMITS.bericht}
placeholder="Vul hier je bericht in"
minH="170px"
resize="vertical"
/>
{error('bericht')}
</Field.Root>
{/* Honeypot: off-screen and hidden from assistive
technology; only bots fill it in (BR-SPAM-01) */}
<Box
aria-hidden="true"
position="absolute"
left="-10000px"
w="1px"
h="1px"
overflow="hidden"
>
<label htmlFor={`${idPrefix}-website`}>Website</label>
<input
ref={honeypot}
id={`${idPrefix}-website`}
name="website"
type="text"
tabIndex={-1}
autoComplete="off"
/>
</Box>
{/* Place for the robot check (Friendly Captcha), added with
the API (FR-HP-09) */}
<div data-robot-check />
{state.status === 'failed' && (
<Box
role="alert"
data-testid="contact-form-status"
p={4}
borderStartWidth="2px"
borderStartColor="error"
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>
</Box>
)}
<chakra.button
type="submit"
css={linkButton({ variant: 'accent' })}
alignSelf="flex-start"
disabled={disabled}
cursor={disabled ? 'progress' : 'pointer'}
data-testid="contact-form-submit"
>
{disabled ? 'Versturen…' : '(Aan)vraag versturen'}
</chakra.button>
</Stack>
</chakra.form>
);
}
@@ -0,0 +1,59 @@
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import siteContent from '@/content/siteContent';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactFormGate from './ContactFormGate';
const renderGate = (enabled: boolean, email = siteContent.email) =>
renderWithProviders(
<ContactFormGate
enabled={enabled}
email={email}
subject="Aanvraag fotoshoot: Newborn"
>
<form aria-label="Formulier">
<input aria-label="Naam" />
</form>
</ContactFormGate>,
);
describe('ContactFormGate', () => {
it('keeps the form inert under the coming-soon notice with a mail button', async () => {
const { container } = await renderGate(false);
const form = container.querySelector('form');
expect(form?.closest('[inert]')).not.toBeNull();
const notice = screen.getByTestId('contact-gate-notice');
expect(notice).toHaveTextContent(
'Het contactformulier komt binnenkort. Mail me voor nu op info@andreaslop.nl',
);
const mail = screen.getByRole('link', { name: 'Stuur een e-mail' });
expect(mail).toHaveAttribute(
'href',
'mailto:info@andreaslop.nl?subject=Aanvraag%20fotoshoot%3A%20Newborn',
);
expect(
screen.getByRole('link', { name: 'info@andreaslop.nl' }),
).toHaveAttribute('href', mail.getAttribute('href'));
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows only the coming-soon text when the address is invalid', async () => {
await renderGate(false, { user: '', domain: 'andreaslop.nl' });
expect(screen.getByTestId('contact-gate-notice')).toHaveTextContent(
'Het contactformulier komt binnenkort.',
);
expect(screen.queryByRole('link')).toBeNull();
});
it('shows just the form when switched on', async () => {
const { container } = await renderGate(true);
expect(screen.queryByTestId('contact-gate-notice')).toBeNull();
expect(container.querySelector('[inert]')).toBeNull();
expect(
screen.getByRole('textbox', { name: 'Naam' }),
).toBeInTheDocument();
expect(await axeResults(container)).toHaveNoViolations();
});
});
@@ -0,0 +1,76 @@
import type { ReactNode } from 'react';
import { Box, chakra, Link, Text, useRecipe } from '@chakra-ui/react';
import type { EmailAddress } from '@/content/types';
import { emailAddress } from '@/lib/emailAddress';
import { mailtoLink } from '@/lib/mailLink';
type ContactFormGateProps = {
enabled: boolean;
email: EmailAddress;
subject: string;
children: ReactNode;
};
// Until there is a back-end the form stays visible but dimmed and inert
// under a "coming soon" notice with a mail button (FR-HP-07). inert keeps
// keyboard and screen reader users out of a form that does nothing.
export default function ContactFormGate({
enabled,
email,
subject,
children,
}: ContactFormGateProps) {
const linkButton = useRecipe({ key: 'linkButton' });
if (enabled) return <>{children}</>;
// Assembled in the browser, so the address is nowhere in the bundle
const address = emailAddress(email);
const href = address ? mailtoLink(address, subject) : undefined;
return (
<Box position="relative" data-testid="contact-gate">
<Box inert opacity={0.35} filter="blur(1.5px)" userSelect="none">
{children}
</Box>
<Box
position="absolute"
top="50%"
left="50%"
transform="translate(-50%, -50%)"
w="min(100%, 520px)"
p="clamp(2rem, 4vw, 3rem)"
bg="white"
borderWidth="1px"
borderColor="line"
boxShadow="panel"
textAlign="center"
data-testid="contact-gate-notice"
>
{/* accent.deep instead of the design's accent: meets 4.5:1 */}
<Text textStyle="eyebrow" color="accent.deep" mb={4}>
Binnenkort
</Text>
<Text color="ink.soft" mb={address ? 7 : 0}>
Het contactformulier komt binnenkort.
{address && (
<>
{' Mail me voor nu op '}
<Link variant="underline" href={href}>
{address}
</Link>
</>
)}
</Text>
{address && (
<chakra.a
href={href}
css={linkButton({ variant: 'accent' })}
data-testid="contact-gate-mail"
>
Stuur een e-mail
</chakra.a>
)}
</Box>
</Box>
);
}