'use client' import { useCallback, useMemo, useRef, useState } from 'react' /** * Error map: a field key → its error message. A field is "in error" iff it has * a key here, so `errors.email` is both the truthy flag (for a red border) AND * the message (to display). Empty object = valid. */ export type FormErrors = Partial> /** * The project's server action that calls submitForm (server-only, holds the * Turnstile secret). This hook is a client hook, so it can't call submitForm * directly — the project injects its action. The result only needs `success` * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it. */ export type FormSubmitAction = ( values: T, turnstileToken?: string, ) => Promise<{ message?: string; success: boolean }> /** Turns the current values into an error map. Empty map = valid. */ export type Validator = (values: T) => FormErrors type UseFormOptions> = { /** Clear a field's error as soon as the user edits it. Default true. */ clearErrorOnChange?: boolean /** Generic error message shown when the action fails/throws with no message. */ errorFallback?: string /** Defines the field set AND the reset state. Any shape you like. */ initialValues: T /** * Called once after a SUCCESSFUL submit, with the submitted values and the * action's result. The place to fire analytics — e.g. a GTM `form_submit` * event so a Meta Pixel / GA "Lead" tag can trigger: * * onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }) * * Runs client-side after the server action resolves; errors thrown here are * swallowed so a broken analytics call can't blank out a successful submit. */ onSuccess?: (result: { message?: string; success: boolean }, values: T) => void /** Require a Turnstile token before submit (when the widget is shown). */ requireTurnstile?: boolean submitAction: FormSubmitAction /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */ validate?: Validator } /** * Fully generic form engine: state, validation, Turnstile token, submit, * success/error — WITHOUT any markup. The project owns 100% of the look AND * the field set: there is no baked-in shape here. Replaces the identical * ~150 lines of form plumbing copied into every project. * * The field set comes from `initialValues`; the rules come from `validate` * (so dynamic/builder-driven forms just build both at runtime). For the * everyday contact form use the `useContactForm` preset instead — it wires * the standard fields and rules for you. * * const f = useForm({ * initialValues: { email: '', message: '' }, * submitAction, // your server action * validate: buildValidator({ email: [required(), email()], message: [required()] }), * requireTurnstile: Boolean(siteKey), * }) * f.setField('email', e.target.value)} * className={f.errors.email ? 'border-red-500' : '…'} /> *
…
*/ export function useForm>(options: UseFormOptions) { const { clearErrorOnChange = true, errorFallback = 'Something went wrong. Please try again.', initialValues, requireTurnstile = false, submitAction, validate, } = options // Freeze the initial snapshot so `reset` is stable even though callers pass a // fresh object literal every render. const initialRef = useRef(initialValues) const [values, setValues] = useState(initialRef.current) const [errors, setErrors] = useState>({}) const [isSubmitting, setIsSubmitting] = useState(false) const [isSuccess, setIsSuccess] = useState(false) const [errorMessage, setErrorMessage] = useState(null) const [turnstileToken, setTurnstileToken] = useState(null) const setField = useCallback( (key: K, value: T[K]) => { setValues((prev) => ({ ...prev, [key]: value })) if (clearErrorOnChange) { setErrors((prev) => { if (!prev[key]) {return prev} const next = { ...prev } delete next[key] return next }) } }, [clearErrorOnChange], ) // Validate against the LATEST values via a ref, so handleSubmit stays stable // and never reads a stale snapshot. const valuesRef = useRef(values) valuesRef.current = values const validateRef = useRef(validate) validateRef.current = validate const onSuccessRef = useRef(options.onSuccess) onSuccessRef.current = options.onSuccess const handleSubmit = useCallback( async (e?: { preventDefault?: () => void }) => { e?.preventDefault?.() setErrorMessage(null) const errs = validateRef.current ? validateRef.current(valuesRef.current) : {} setErrors(errs) if (Object.keys(errs).length > 0) {return} if (requireTurnstile && !turnstileToken) { setErrorMessage(errorFallback) return } setIsSubmitting(true) try { const result = await submitAction(valuesRef.current, turnstileToken ?? undefined) if (result.success) { setIsSuccess(true) setTurnstileToken(null) // Fire analytics (e.g. GTM form_submit) — never let it break the submit. try { onSuccessRef.current?.(result, valuesRef.current) } catch { /* analytics must not affect the form outcome */ } } else { setErrorMessage(result.message || errorFallback) } } catch (err) { setErrorMessage(err instanceof Error ? err.message : errorFallback) } finally { setIsSubmitting(false) } }, [requireTurnstile, turnstileToken, submitAction, errorFallback], ) const reset = useCallback(() => { setValues(initialRef.current) setErrors({}) setIsSuccess(false) setErrorMessage(null) setTurnstileToken(null) }, []) return useMemo( () => ({ errorMessage, errors, handleSubmit, isSubmitting, isSuccess, reset, setErrors, setField, setTurnstileToken, setValues, turnstileToken, values, }), [ values, errors, isSubmitting, isSuccess, errorMessage, turnstileToken, setField, handleSubmit, reset, ], ) }