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
+23 -1
View File
@@ -4,7 +4,7 @@ import {
createRouter,
RouterProvider,
} from '@tanstack/react-router';
import { render, screen } from '@testing-library/react';
import { render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import lighthouseConfig from '../lighthouserc.cjs';
import ErrorPage from './components/StatusPage/ErrorPage';
@@ -146,6 +146,7 @@ describe('homepage', () => {
}),
screen.getByRole('region', { name: 'Prijzen' }),
screen.getByRole('region', { name: 'Lieve woorden' }),
screen.getByRole('region', { name: 'Contact' }),
];
let previous: Element = hero;
@@ -162,6 +163,27 @@ describe('homepage', () => {
});
describe('homepage ?pakket=', () => {
it('a "Boek Newborn" link selects Newborn, tidies the URL and focuses Contact', async () => {
const { router } = await renderApp('/?pakket=newborn#contact');
// The form is lazy; arriving via "Boek" loads it straight away
expect(
await screen.findByTestId('contact-form-shoot', undefined, {
timeout: 10_000,
}),
).toHaveValue('newborn');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.hash).toBe('contact');
// The form stays once loaded, also now that ?pakket= is gone
expect(screen.getByTestId('contact-form-shoot')).toHaveValue('newborn');
// within the section: the footer has a "Contact" heading too
expect(
within(screen.getByRole('region', { name: 'Contact' })).getByRole(
'heading',
{ level: 2 },
),
).toHaveFocus();
});
it.each(['/?pakket=newborn', '/?pakket=123', '/?pakket=%3Cscript%3E'])(
'%s renders the homepage without errors',
async (path) => {
@@ -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>
);
}
@@ -9,6 +9,8 @@ type SectionHeadingProps = {
align?: 'center' | 'start';
// compact: little space below, for a heading above running text
spacing?: 'default' | 'compact';
// Lets code move focus to the heading (no visible ring, theme rule)
focusable?: boolean;
};
// Heading block of a homepage section (design .section__head): optional
@@ -20,6 +22,7 @@ export default function SectionHeading({
lead,
align = 'center',
spacing = 'default',
focusable = false,
}: SectionHeadingProps) {
const centered = align === 'center';
@@ -36,7 +39,12 @@ export default function SectionHeading({
{eyebrow}
</Text>
)}
<Heading as="h2" id={id} textStyle="sectionTitle">
<Heading
as="h2"
id={id}
textStyle="sectionTitle"
tabIndex={focusable ? -1 : undefined}
>
{title}
</Heading>
{lead && (
@@ -0,0 +1,73 @@
import { screen, waitFor } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import homeContent from '@/content/homeContent';
import packages from '@/content/packages';
import siteContent from '@/content/siteContent';
import { axeResults } from '@/test/axe';
import { renderWithProviders } from '@/test/renderWithProviders';
import ContactSection from './ContactSection';
const renderSection = (pakket?: string, path = '/') =>
renderWithProviders(
<ContactSection
content={homeContent.contact}
packages={packages}
enabled={false}
email={siteContent.email}
pakket={pakket}
/>,
{ path },
);
const heading = () =>
screen.getByRole('heading', { level: 2, name: 'Contact' });
// The form is a lazy chunk; its first import can take over a second under
// the full suite with coverage
const LAZY_LOAD = { timeout: 10_000 };
const shoot = () =>
screen.findByTestId('contact-form-shoot', undefined, LAZY_LOAD);
describe('ContactSection', () => {
it('is the contact anchor with heading, lead and the gated form', async () => {
const { container } = await renderSection();
const section = screen.getByRole('region', { name: 'Contact' });
await shoot();
expect(section).toHaveAttribute('id', 'contact');
expect(screen.getByText(homeContent.contact.lead)).toBeInTheDocument();
expect(screen.getByTestId('contact-gate-notice')).toBeInTheDocument();
expect(
screen.getByRole('link', { name: 'Stuur een e-mail' }),
).toHaveAttribute(
'href',
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
);
expect(heading()).not.toHaveFocus();
expect(await axeResults(container)).toHaveNoViolations();
});
it('takes over a package from "Boek ...", tidies the URL and moves focus here', async () => {
const { router } = await renderSection(
'newborn',
'/?pakket=newborn#contact',
);
expect(await shoot()).toHaveValue('newborn');
expect(
screen.getByRole('link', { name: 'Stuur een e-mail' }),
).toHaveAttribute(
'href',
'mailto:info@andreaslop.nl?subject=Aanvraag%20fotoshoot%3A%20Newborn',
);
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
expect(router.state.location.hash).toBe('contact');
expect(heading()).toHaveFocus();
});
it('ignores an unknown package but still tidies the URL', async () => {
const { router } = await renderSection(
'bruiloft',
'/?pakket=bruiloft#contact',
);
expect(await shoot()).toHaveValue('');
await waitFor(() => expect(router.state.location.searchStr).toBe(''));
});
});
@@ -0,0 +1,140 @@
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
import { Box } from '@chakra-ui/react';
import { useNavigate } from '@tanstack/react-router';
import { DEFERRED_LOAD_MARGIN } from '@/components/DeferredImage/DeferredImage';
import ContactFormGate from '@/components/ContactForm/ContactFormGate';
import HomeSection from '@/components/HomeSection/HomeSection';
import Reveal from '@/components/Reveal/Reveal';
import SectionHeading from '@/components/SectionHeading/SectionHeading';
import type {
EmailAddress,
HomeContent,
PricingPackage,
} from '@/content/types';
import useInView from '@/hooks/useInView';
import { mailSubject } from '@/lib/mailLink';
import { packageFromSearch } from '@/lib/packageFromSearch';
import { shootOptions } from '@/lib/shootOptions';
import { visiblePackages } from '@/lib/visiblePackages';
// The form (Chakra fields, validation, reducer) sits far below the hero.
// Loading it with the page cost ±0.03 Lighthouse performance on mobile, so
// it loads when the section comes near the screen, or straight away when
// the visitor arrives via "Boek ...".
const ContactForm = lazy(() => import('@/components/ContactForm/ContactForm'));
const TITLE_ID = 'contact-title';
// Keeps the form's space while it loads, so the notice sits where it will
// stay and the page below does not jump (measured: 604px on phones, where
// name and e-mail are stacked, 502px from sm)
const FORM_PLACEHOLDER_HEIGHT = { base: '604px', sm: '502px' };
type ContactSectionProps = {
content: HomeContent['contact'];
packages: PricingPackage[];
enabled: boolean;
email: EmailAddress;
// ?pakket= from a "Boek ..." link on a price card
pakket?: string;
};
// "Contact" on the homepage (design #contact): heading and lead, and the
// contact form behind the coming-soon gate. Takes over a package chosen via
// "Boek ...", then tidies the URL and moves focus here (BR-PARAM-02,
// BR-FOCUS-01).
export default function ContactSection({
content,
packages,
enabled,
email,
pakket,
}: ContactSectionProps) {
const navigate = useNavigate();
const shown = useMemo(() => visiblePackages(packages), [packages]);
const options = useMemo(() => shootOptions(packages), [packages]);
// Take over a new ?pakket= while rendering (React's pattern for a
// changed prop); the last "Boek" click wins (BR-PARAM-03)
const [seenPakket, setSeenPakket] = useState<string | undefined>();
const [preselect, setPreselect] = useState<{
shoot: string;
key: number;
}>();
const [chosenName, setChosenName] = useState<string>();
if (pakket !== seenPakket) {
setSeenPakket(pakket);
const id =
pakket === undefined ? undefined : packageFromSearch(pakket, shown);
if (id) {
setPreselect({ shoot: id, key: (preselect?.key ?? 0) + 1 });
setChosenName(shown.find((pkg) => pkg.id === id)?.name);
}
}
// Then remove ?pakket= from the address bar (no extra history entry, no
// scroll) and continue keyboard and screen reader users here
useEffect(() => {
if (pakket === undefined) return;
void navigate({
to: '/',
search: {},
hash: 'contact',
replace: true,
resetScroll: false,
hashScrollIntoView: false,
});
document.getElementById(TITLE_ID)?.focus({ preventScroll: true });
}, [pakket, navigate]);
const subject = mailSubject(chosenName);
const { ref, inView } = useInView<HTMLDivElement>({
rootMargin: DEFERRED_LOAD_MARGIN,
});
// Once loaded the form stays, also after ?pakket= is removed from the
// URL; otherwise it would be recreated and lose what was typed
const [formLoaded, setFormLoaded] = useState(false);
if (!formLoaded && (inView || pakket !== undefined)) setFormLoaded(true);
const placeholder = <Box minH={FORM_PLACEHOLDER_HEIGHT} />;
return (
<HomeSection
labelledBy={TITLE_ID}
id="contact"
width="narrow"
data-testid="contact-section"
>
<Reveal>
<SectionHeading
id={TITLE_ID}
title={content.title}
lead={content.lead}
focusable
/>
</Reveal>
<Reveal>
<ContactFormGate
enabled={enabled}
email={email}
subject={subject}
>
<Box ref={ref}>
{formLoaded ? (
<Suspense fallback={placeholder}>
<ContactForm
idPrefix="home-contact"
options={options}
preselect={preselect}
mailSubject={subject}
email={email}
/>
</Suspense>
) : (
placeholder
)}
</Box>
</ContactFormGate>
</Reveal>
</HomeSection>
);
}
@@ -1,7 +1,7 @@
import {
Box,
chakra,
Heading,
List,
Text,
useRecipe,
VisuallyHidden,
@@ -50,7 +50,9 @@ export default function PriceCard({ pkg }: PriceCardProps) {
>
{formatPrice(pkg.price)}
</Text>
<List.Root
{/* A plain list, not Chakra's List: its slot recipe would pull
shared code into the chunk the hero waits for */}
<chakra.ul
listStyleType="none"
display="grid"
gap={3}
@@ -62,9 +64,9 @@ export default function PriceCard({ pkg }: PriceCardProps) {
fontSize="sm"
>
{pkg.features.map((feature) => (
<List.Item key={feature}>{feature}</List.Item>
<chakra.li key={feature}>{feature}</chakra.li>
))}
</List.Root>
</chakra.ul>
{/* The router's own Link keeps the route types, so search is
checked against the homepage's ?pakket=; the button style
goes on via asChild */}
@@ -1,4 +1,4 @@
import { Blockquote, Box, Grid, Text } from '@chakra-ui/react';
import { Box, chakra, Grid, Text } from '@chakra-ui/react';
import FramedImage from '@/components/FramedImage/FramedImage';
import type { Testimonial } from '@/content/types';
@@ -48,23 +48,25 @@ export default function TestimonialSlide({
<Text textStyle="eyebrow" color="accent.deep" mb={4}>
{testimonial.shoot}
</Text>
<Blockquote.Root variant="plain" px={0} gap={7}>
<Blockquote.Content
{/* Plain elements, not Chakra's Blockquote: its slot recipe
would pull shared code into the chunk the hero waits for */}
<chakra.figure display="flex" flexDirection="column" gap={7}>
<chakra.blockquote
fontFamily="heading"
fontSize="clamp(1.35rem, 2.2vw, 1.75rem)"
lineHeight="1.5"
color="ink"
>
{testimonial.quote}
</Blockquote.Content>
<Blockquote.Caption
</chakra.blockquote>
<chakra.figcaption
textStyle="eyebrow"
color="ink.soft"
_before={{ content: '"— "' }}
>
{testimonial.author}
</Blockquote.Caption>
</Blockquote.Root>
</chakra.figcaption>
</chakra.figure>
</Box>
</Grid>
);
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { submitContactForm } from './submitContactForm';
describe('submitContactForm', () => {
it('fails until the API exists', async () => {
await expect(
submitContactForm({
naam: 'Demi',
email: 'demi@example.nl',
shoot: 'newborn',
bericht: 'Hoi!',
}),
).rejects.toThrow('not available');
});
});
+21
View File
@@ -0,0 +1,21 @@
import type { ContactPayload } from './types';
// The one place where the contact form is sent. There is no back-end yet, so
// this always fails; the form is switched off (siteContent.contactForm) until
// it works. In the API feature this becomes:
//
// const response = await fetch('/api/contact', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ ...payload, captcha: token }),
// });
// if (!response.ok) throw new Error(`Contact form: ${response.status}`);
//
// plus the Friendly Captcha token and the CSP entries it needs (FR-HP-09).
// Visitors never see this error's text, only the generic failure message.
export async function submitContactForm(
payload: ContactPayload,
): Promise<void> {
void payload;
throw new Error('Contact form is not available yet');
}
+32
View File
@@ -0,0 +1,32 @@
// What the contact form works with. The payload is what POST /api/contact
// will receive (plus the robot-check token, added in the API feature).
export type ContactField = 'naam' | 'email' | 'shoot' | 'bericht';
// What the visitor typed
export type ContactValues = Record<ContactField, string>;
// At most one message per field
export type ContactErrors = Partial<Record<ContactField, string>>;
// Trimmed values; shoot is a package id or 'overig'
export type ContactPayload = Record<ContactField, string>;
export interface ShootOption {
value: string;
label: string;
}
// Maximum lengths; also set as maxLength on the fields (BR-FORM-06)
export const CONTACT_LIMITS = {
naam: 100,
email: 254,
bericht: 2000,
} as const;
export const EMPTY_CONTACT: ContactValues = {
naam: '',
email: '',
shoot: '',
bericht: '',
};
+4
View File
@@ -69,6 +69,10 @@ const homeContent: HomeContent = {
testimonials: {
title: 'Lieve woorden',
},
contact: {
title: 'Contact',
lead: 'Wil je meer informatie ontvangen? Neem gerust contact met mij op.',
},
};
export default homeContent;
+2
View File
@@ -16,6 +16,8 @@ const siteContent: SiteContent = {
},
],
email: { user: 'info', domain: 'andreaslop.nl' },
// Switched on once the API can receive the form
contactForm: { enabled: false },
};
export default siteContent;
+6
View File
@@ -20,6 +20,8 @@ export interface SiteContent {
footerIntro: string;
socials: SocialLink[];
email: EmailAddress;
// Off: the form is shown dimmed under a "coming soon" notice (FR-HP-07)
contactForm: { enabled: boolean };
}
// An image as the API will deliver it. width and height are the intrinsic
@@ -74,6 +76,10 @@ export interface HomeContent {
testimonials: {
title: string;
};
contact: {
title: string;
lead: string;
};
}
export interface HeroSlide {
+174
View File
@@ -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;
}
}),
);
});
});
+118
View File
@@ -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;
}
}
+36
View File
@@ -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);
},
),
);
});
});
+16
View File
@@ -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;
}
+37
View File
@@ -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);
}),
);
});
});
+11
View File
@@ -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)}`;
}
+32
View File
@@ -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,
})),
);
}),
);
});
});
+20
View File
@@ -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,
];
}
+34
View File
@@ -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());
}
}),
);
});
});
+11
View File
@@ -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(),
};
}
+143
View File
@@ -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);
}
}),
);
});
});
+76
View File
@@ -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;
}
+37
View File
@@ -0,0 +1,37 @@
import { defineRecipe } from '@chakra-ui/react';
// The design's square form fields (.form__input, .form__textarea): white,
// a hairline border, light text, and the heidegroen border with a soft ring
// on focus. Applied with css={formControl()} to Chakra's Input, Textarea and
// NativeSelect.Field, so all three look the same.
const formControlRecipe = defineRecipe({
className: 'form-control',
base: {
width: '100%',
px: '1.1rem',
py: '0.95rem',
h: 'auto',
minH: '3.25rem',
bg: 'white',
color: 'ink',
borderWidth: '1px',
borderColor: 'line',
rounded: 'none',
fontSize: '1.0625rem',
fontWeight: '300',
transitionProperty: 'border-color, box-shadow',
transitionDuration: 'interaction',
transitionTimingFunction: 'smooth',
// Placeholder in ink.soft: the design's lighter grey fails 4.5:1
_placeholder: { color: 'ink.soft', opacity: 1 },
_focusVisible: {
outline: 'none',
borderColor: 'accent.deep',
boxShadow:
'0 0 0 3px color-mix(in srgb, {colors.accent} 25%, transparent)',
},
_invalid: { borderColor: 'error' },
},
});
export default formControlRecipe;
+9
View File
@@ -1,6 +1,7 @@
import { createFileRoute } from '@tanstack/react-router';
import Hero from '../components/Hero/Hero';
import AboutBlock from '../components/home/AboutBlock/AboutBlock';
import ContactSection from '../components/home/ContactSection/ContactSection';
import Pricing from '../components/home/Pricing/Pricing';
import Testimonials from '../components/home/Testimonials/Testimonials';
import IntroGallery from '../components/home/IntroGallery/IntroGallery';
@@ -24,6 +25,7 @@ export const Route = createFileRoute('/')({
// The homepage: the hero, then the sections in the order of LAYOUT.md
function Index() {
const { pakket } = Route.useSearch();
return (
<>
<Hero content={heroContent} socials={siteContent.socials} />
@@ -34,6 +36,13 @@ function Index() {
content={homeContent.testimonials}
testimonials={testimonials}
/>
<ContactSection
content={homeContent.contact}
packages={packages}
enabled={siteContent.contactForm.enabled}
email={siteContent.email}
pakket={pakket}
/>
</>
);
}
+73
View File
@@ -1,4 +1,6 @@
import fc from 'fast-check';
import type { ContactField, ContactValues } from '../contact/types';
import type { ContactFormEvent } from '../lib/contactFormReducer';
import type {
EmailAddress,
PricingPackage,
@@ -138,3 +140,74 @@ export const anyTestimonial: fc.Arbitrary<Testimonial> = fc.oneof(
}),
}),
);
// Shoot values as the form offers them for the live packages
const shootValue = fc.constantFrom(
'zwangerschap',
'newborn',
'gezin',
'overig',
);
// Values that pass every rule: realistic text within the limits
export const contactValues: fc.Arbitrary<ContactValues> = fc.record({
naam: nonBlank,
email: validEmail.map(({ user, domain }) => `${user}@${domain}`),
shoot: shootValue,
bericht: fc
.string({ minLength: 1, maxLength: 300 })
.filter((text) => text.trim() !== ''),
});
// Valid and broken values mixed: empty, whitespace, too long, bad e-mail
export const anyContactValues: fc.Arbitrary<ContactValues> = fc.oneof(
contactValues,
fc.record({
naam: fc.oneof(nonBlank, fc.constantFrom('', ' ', 'x'.repeat(101))),
email: fc.oneof(
validEmail.map(({ user, domain }) => `${user}@${domain}`),
fc.constantFrom(
'',
'geen-adres',
'a@b',
'a b@c.nl',
'x'.repeat(255),
),
fc.string({ maxLength: 20 }),
),
shoot: fc.oneof(shootValue, fc.constantFrom('', 'bruiloft')),
bericht: fc.oneof(
nonBlank,
fc.constantFrom('', ' ', 'x'.repeat(2001)),
),
}),
);
const contactField = fc.constantFrom<ContactField>(
'naam',
'email',
'shoot',
'bericht',
);
// Anything that can happen to the form, for the state machine test
export const contactEvent: fc.Arbitrary<ContactFormEvent> = fc.oneof(
fc.record({
type: fc.constant('edit' as const),
field: contactField,
value: fc.oneof(
nonBlank,
fc.constantFrom('', 'a@b.nl', 'newborn', 'overig'),
),
}),
fc.record({ type: fc.constant('blur' as const), field: contactField }),
fc.record({ type: fc.constant('preselect' as const), shoot: shootValue }),
fc.record({
type: fc.constant('submit' as const),
honeypot: fc.constantFrom('', '', '', 'http://spam.example'),
shownAt: fc.constant(0),
now: fc.constantFrom(500, 5000, 10000),
}),
fc.constant({ type: 'resolved' as const }),
fc.constant({ type: 'rejected' as const }),
);
+2
View File
@@ -32,6 +32,8 @@ Object.defineProperty(window, 'matchMedia', {
}),
});
window.scrollTo = () => {};
// The router scrolls to a #hash with scrollIntoView, which jsdom lacks too
Element.prototype.scrollIntoView = () => {};
// jsdom has no ResizeObserver either; the carousel (Zag) needs one. Nothing
// is measured in jsdom, so a no-op is enough. IntersectionObserver is left
+10
View File
@@ -1,6 +1,7 @@
import { createSystem, defaultConfig, defineConfig } from '@chakra-ui/react';
import carouselControlRecipe from './recipes/carouselControl';
import containerRecipe from './recipes/container';
import formControlRecipe from './recipes/formControl';
import iconControlRecipe from './recipes/iconControl';
import linkRecipe from './recipes/link';
import linkButtonRecipe from './recipes/linkButton';
@@ -55,6 +56,8 @@ const config = defineConfig({
deep: { value: '#5f6a58' }, // accent hover
},
sand: { value: '#d9cdbc' }, // zachte vlakken en decoratie
// Form errors: the design's #a4443a, 5.7:1 on paper, 6.1:1 on white
error: { value: '#a4443a' },
},
fonts: {
heading: {
@@ -96,6 +99,12 @@ const config = defineConfig({
// Binnen de header: de hamburger boven het logo en menu
menuToggle: { value: 1 },
},
shadows: {
// Soft shadow under a floating panel (design --shadow-md)
panel: {
value: '0 12px 40px color-mix(in srgb, {colors.ink} 12%, transparent)',
},
},
gradients: {
// Donker verloop over hero-foto's, zodat witte tekst leesbaar blijft
scrim: {
@@ -210,6 +219,7 @@ const config = defineConfig({
linkButton: linkButtonRecipe,
iconControl: iconControlRecipe,
carouselControl: carouselControlRecipe,
formControl: formControlRecipe,
},
},
});