Files
AndreaSlopFotografie/web/src/components/ContactForm/ContactForm.tsx
T
SluijsensandClaude Opus 5.5 1afa7d905b Aligns the submit button right and starts the contact page at the top
The submit button of the contact form now sits on the right, with the
privacy line below it, on the homepage and the contact page. Arriving on
the contact page from a link further down another page now starts at
the top: removing ?pakket= from the address no longer cancels the
router's scroll reset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 20:14:28 +01:00

308 lines
11 KiB
TypeScript

import { useEffect, useRef, useState, useReducer } from 'react';
import {
Box,
chakra,
Field,
Input,
Link,
NativeSelect,
SimpleGrid,
Stack,
Text,
Textarea,
useRecipe,
} from '@chakra-ui/react';
import PrivacyNote from '@/components/PrivacyNote/PrivacyNote';
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;
// How soon Andrea answers, e.g. '1-2 werkdagen' (siteContent)
replyTime: string;
submit?: (payload: ContactPayload) => Promise<void>;
};
// 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,
replyTime,
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"
>
{`Bedankt voor je bericht! Ik reageer binnen ${replyTime}.`}
</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-end"
disabled={disabled}
cursor={disabled ? 'progress' : 'pointer'}
data-testid="contact-form-submit"
>
{disabled ? 'Versturen…' : '(Aan)vraag versturen'}
</chakra.button>
{/* Under the submit button, aligned with it */}
<PrivacyNote textAlign="end" />
</Stack>
</chakra.form>
);
}