Added better support for GTM, improved accesibility
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useRef, useMemo } from 'react'
|
||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
* Error map: a field key → its error message. A field is "in error" iff it has
|
||||
@@ -18,23 +18,34 @@ export type FormErrors<T> = Partial<Record<keyof T, string>>
|
||||
export type FormSubmitAction<T> = (
|
||||
values: T,
|
||||
turnstileToken?: string,
|
||||
) => Promise<{ success: boolean; message?: string }>
|
||||
) => Promise<{ message?: string; success: boolean }>
|
||||
|
||||
/** Turns the current values into an error map. Empty map = valid. */
|
||||
export type Validator<T> = (values: T) => FormErrors<T>
|
||||
|
||||
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
/** 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<T>
|
||||
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||
validate?: Validator<T>
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean
|
||||
/** Generic error message shown when the action fails/throws with no message. */
|
||||
errorFallback?: string
|
||||
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||
clearErrorOnChange?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,12 +72,12 @@ type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
*/
|
||||
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
|
||||
const {
|
||||
clearErrorOnChange = true,
|
||||
errorFallback = 'Something went wrong. Please try again.',
|
||||
initialValues,
|
||||
requireTurnstile = false,
|
||||
submitAction,
|
||||
validate,
|
||||
requireTurnstile = false,
|
||||
errorFallback = 'Something went wrong. Please try again.',
|
||||
clearErrorOnChange = true,
|
||||
} = options
|
||||
|
||||
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
||||
@@ -77,15 +88,15 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
|
||||
const [errors, setErrors] = useState<FormErrors<T>>({})
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||
const [errorMessage, setErrorMessage] = useState<null | string>(null)
|
||||
const [turnstileToken, setTurnstileToken] = useState<null | string>(null)
|
||||
|
||||
const setField = useCallback(
|
||||
<K extends keyof T>(key: K, value: T[K]) => {
|
||||
setValues((prev) => ({ ...prev, [key]: value }))
|
||||
if (clearErrorOnChange) {
|
||||
setErrors((prev) => {
|
||||
if (!prev[key]) return prev
|
||||
if (!prev[key]) {return prev}
|
||||
const next = { ...prev }
|
||||
delete next[key]
|
||||
return next
|
||||
@@ -101,6 +112,8 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
|
||||
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 }) => {
|
||||
@@ -109,7 +122,7 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
|
||||
|
||||
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}
|
||||
setErrors(errs)
|
||||
if (Object.keys(errs).length > 0) return
|
||||
if (Object.keys(errs).length > 0) {return}
|
||||
|
||||
if (requireTurnstile && !turnstileToken) {
|
||||
setErrorMessage(errorFallback)
|
||||
@@ -122,6 +135,12 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
|
||||
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)
|
||||
}
|
||||
@@ -144,18 +163,18 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
values,
|
||||
errorMessage,
|
||||
errors,
|
||||
handleSubmit,
|
||||
isSubmitting,
|
||||
isSuccess,
|
||||
errorMessage,
|
||||
turnstileToken,
|
||||
setField,
|
||||
setValues,
|
||||
setErrors,
|
||||
setTurnstileToken,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setErrors,
|
||||
setField,
|
||||
setTurnstileToken,
|
||||
setValues,
|
||||
turnstileToken,
|
||||
values,
|
||||
}),
|
||||
[
|
||||
values,
|
||||
|
||||
Reference in New Issue
Block a user