'use client' import { useEffect, useId, useRef, useState, type CSSProperties } from 'react' import { HONEYPOT_FIELD_NAMES, TURNSTILE_TOKEN_FIELD } from '../constants' import type { ContactErrorCode, ContactField } from '../types' import { Turnstile, type TurnstileHandle } from './Turnstile' type MessageKey = ContactErrorCode | 'default' export interface ContactMessages { submit: string sending: string successTitle: string successMessage: string errors: Record } export interface ContactClassNames { form: string field: string label: string required: string input: string textarea: string select: string button: string honeypot: string alert: string alertError: string alertSuccess: string } export interface ContactFormProps { /** API route the form POSTs to (e.g. `/api/contact`). */ action: string /** Field schema — should mirror the server route's fields. */ fields: ReadonlyArray /** Cloudflare Turnstile site key. Omit to render without a captcha. */ turnstileSiteKey?: string turnstileAppearance?: 'always' | 'execute' | 'interaction-only' /** Locale sent with the submission + used as the Turnstile language. */ locale?: string /** Copy overrides (English defaults). */ messages?: Partial> & { errors?: Partial> } /** Class name overrides — map to your design system (e.g. `ds-input`). */ classNames?: Partial /** Extra hidden values merged into the payload (e.g. a source tag). */ hiddenValues?: Record onSuccess?: () => void onError?: (code: MessageKey) => void className?: string } const DEFAULT_MESSAGES: ContactMessages = { submit: 'Send message', sending: 'Sending…', successTitle: 'Message sent', successMessage: "Thanks for reaching out. We'll get back to you soon.", errors: { invalid_request: 'Something went wrong. Please check your entries and try again.', missing_fields: 'Please fill in all required fields.', invalid_email: 'Please enter a valid email address.', too_long: 'One of the fields is too long.', rate_limited: 'Too many attempts. Please try again later.', captcha_failed: 'Captcha verification failed. Please try again.', server_error: 'Something went wrong on our side. Please try again later.', default: 'Something went wrong. Please try again.', }, } const DEFAULT_CLASSNAMES: ContactClassNames = { form: 'acf-form', field: 'acf-field', label: 'acf-label', required: 'acf-required', input: 'acf-input', textarea: 'acf-textarea', select: 'acf-select', button: 'acf-button', honeypot: 'acf-sr-only', alert: 'acf-alert', alertError: 'acf-alert--error', alertSuccess: 'acf-alert--success', } function cx(...parts: Array): string { return parts.filter(Boolean).join(' ') } // Guarantees the honeypot is visually hidden even when the consumer doesn't // import the default stylesheet (e.g. a design-system consumer that maps // classNames to its own classes). A visible honeypot gets browser-autofilled, // which defeats the trap — so hiding must not depend on optional CSS. const HONEYPOT_HIDDEN_STYLE: CSSProperties = { position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clipPath: 'inset(50%)', whiteSpace: 'nowrap', border: 0, } type Status = | { kind: 'idle' } | { kind: 'submitting' } | { kind: 'success' } | { kind: 'error'; code: MessageKey } export function ContactForm({ action, fields, turnstileSiteKey, turnstileAppearance = 'always', locale, messages, classNames, hiddenValues, onSuccess, onError, className, }: ContactFormProps) { const msg: ContactMessages = { ...DEFAULT_MESSAGES, ...messages, errors: { ...DEFAULT_MESSAGES.errors, ...(messages?.errors ?? {}) }, } const cls: ContactClassNames = { ...DEFAULT_CLASSNAMES, ...classNames } const [values, setValues] = useState>(() => Object.fromEntries(fields.map((field) => [field.name, ''])) ) const [token, setToken] = useState(null) const [status, setStatus] = useState({ kind: 'idle' }) const turnstileRef = useRef(null) const renderedAtRef = useRef(null) useEffect(() => { renderedAtRef.current = Date.now() }, []) const fieldId = useId() const isSubmitting = status.kind === 'submitting' const requiredFilled = fields.every( (field) => !field.required || (values[field.name]?.trim().length ?? 0) > 0 ) const captchaReady = !turnstileSiteKey || token !== null const canSubmit = !isSubmitting && requiredFilled && captchaReady function setValue(name: string, value: string) { setValues((prev) => ({ ...prev, [name]: value })) } function resetCaptcha() { turnstileRef.current?.reset() setToken(null) } async function handleSubmit(event: React.FormEvent) { event.preventDefault() if (!canSubmit) return setStatus({ kind: 'submitting' }) const formEl = event.currentTarget const honeypotValue = (formEl.elements.namedItem(HONEYPOT_FIELD_NAMES.honeypot) as HTMLInputElement | null) ?.value ?? '' try { const res = await fetch(action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...values, ...(hiddenValues ?? {}), ...(locale ? { locale } : {}), [TURNSTILE_TOKEN_FIELD]: token, [HONEYPOT_FIELD_NAMES.honeypot]: honeypotValue, [HONEYPOT_FIELD_NAMES.renderedAt]: renderedAtRef.current ?? Date.now(), }), }) if (res.ok) { setStatus({ kind: 'success' }) setValues(Object.fromEntries(fields.map((field) => [field.name, '']))) resetCaptcha() onSuccess?.() return } const data = (await res.json().catch(() => ({}))) as { error?: ContactErrorCode } const code: MessageKey = data.error ?? 'default' setStatus({ kind: 'error', code }) resetCaptcha() onError?.(code) } catch { setStatus({ kind: 'error', code: 'default' }) resetCaptcha() onError?.('default') } } function renderField(field: ContactField) { const id = `${fieldId}-${field.name}` const type = field.type ?? 'text' const value = values[field.name] ?? '' const common = { id, name: field.name, required: field.required, placeholder: field.placeholder, 'aria-required': field.required || undefined, } return (
{type === 'textarea' ? (