'use client' import { useMemo } from 'react' import { type FormSubmitAction, useForm } from './useForm.js' import { buildValidator, checked, email, minLength, required } from './validators.js' /** * Field values of the STANDARD contact form. This is a preset shape — projects * that need a different field set (or dynamic builder fields) should use * `useForm` directly instead, where the shape is fully open. */ export type ContactFormValues = { consent: boolean email: string message: string name: string phone: string topic: string } export type ContactFormErrors = Partial> export type SubmitAction = FormSubmitAction type UseContactFormOptions = { /** Generic error message shown when the action fails/throws. */ errorFallback?: string initialTopic?: string /** Override the per-field error message (shown via `errors.`). */ messages?: Partial> /** Minimum message length. Default 10. */ minMessageLength?: number /** Whether consent is required (project passes true when consentText shown). */ requireConsent?: boolean /** Whether a topic must be chosen (project passes this when topics exist). */ requireTopic?: boolean /** Require a Turnstile token before submit (when the widget is shown). */ requireTurnstile?: boolean submitAction: SubmitAction } /** * Zero-config preset over `useForm` for the everyday contact form: standard * fields (name/email/phone/topic/message/consent) and standard rules, wired * for you. Markup and styling stay 100% in the project — this only removes the * duplicated logic. * * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey), * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) }) * * Need custom or dynamic fields? Drop the preset and call `useForm` + validators. */ export function useContactForm(options: UseContactFormOptions) { const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction, } = options const validate = useMemo( () => buildValidator({ name: [required(messages?.name)], email: [required(messages?.email), email(messages?.email)], ...(requireTopic ? { topic: [required(messages?.topic)] } : {}), message: [required(messages?.message), minLength(minMessageLength, messages?.message)], ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}), }), [requireTopic, requireConsent, minMessageLength, messages], ) return useForm({ errorFallback, initialValues: { name: '', consent: false, email: '', message: '', phone: '', topic: initialTopic, }, requireTurnstile, submitAction, validate, }) }