Added better support for GTM, improved accesibility
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { pushDataLayer } from '../analytics/pushDataLayer.js'
|
||||
|
||||
/**
|
||||
* Shape of the per-form analytics config an editor fills in the panel (see
|
||||
* buildFormAnalyticsFields). Loose by design — it comes from Payload.
|
||||
*/
|
||||
export type FormAnalyticsConfig =
|
||||
| {
|
||||
event?: null | string
|
||||
params?: { key?: null | string; value?: null | string }[] | null
|
||||
}
|
||||
| null
|
||||
| undefined
|
||||
|
||||
/**
|
||||
* Builds an `onSuccess` handler from a form's panel-configured analytics, so the
|
||||
* GTM `dataLayer` event is emitted on submit with ZERO per-form code. Wire it
|
||||
* once in the shared form renderer — every form then gets its tracking from the
|
||||
* panel:
|
||||
*
|
||||
* const f = useContactForm({
|
||||
* submitAction,
|
||||
* onSuccess: formAnalyticsOnSuccess(form.analytics),
|
||||
* })
|
||||
*
|
||||
* A param value starting with `$` is resolved from the submitted values, so an
|
||||
* editor can set `form_name = $topic` and get the chosen topic with no code.
|
||||
* No event name configured → the returned handler is a no-op.
|
||||
*/
|
||||
export function formAnalyticsOnSuccess<T extends Record<string, unknown>>(
|
||||
config: FormAnalyticsConfig,
|
||||
): (result: { success: boolean }, values: T) => void {
|
||||
return (_result, values) => {
|
||||
const event = config?.event?.trim()
|
||||
if (!event) {return}
|
||||
const params: Record<string, unknown> = {}
|
||||
for (const p of config?.params ?? []) {
|
||||
const key = p?.key?.trim()
|
||||
if (!key) {continue}
|
||||
const raw = typeof p?.value === 'string' ? p.value : ''
|
||||
params[key] = raw.startsWith('$') ? (values[raw.slice(1)] ?? '') : raw
|
||||
}
|
||||
pushDataLayer(event, params)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
/**
|
||||
* Panel fields that let an EDITOR configure a form's analytics event — the GTM
|
||||
* `dataLayer` push fired on successful submit — without any code change. Add
|
||||
* them to the Forms collection via the plugin's `formOverrides`:
|
||||
*
|
||||
* ipalKit({
|
||||
* forms: {
|
||||
* formOverrides: {
|
||||
* fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
|
||||
* },
|
||||
* },
|
||||
* })
|
||||
*
|
||||
* The front reads this config and emits the event automatically via
|
||||
* `formAnalyticsOnSuccess` (see forms.md) — so adding a tracked form, or
|
||||
* changing its event name/params, is panel-only. The GTM side (the Lead/Pixel
|
||||
* tag, its trigger and consent gate) stays in GTM, which is itself a no-code
|
||||
* panel for tags.
|
||||
*/
|
||||
export function buildFormAnalyticsFields(): Field[] {
|
||||
return [
|
||||
{
|
||||
name: 'analytics',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description:
|
||||
'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'event',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description:
|
||||
'Empty = nothing is pushed. Default "form_submit" — attach your GTM trigger to it.',
|
||||
},
|
||||
defaultValue: 'form_submit',
|
||||
label: 'Event name',
|
||||
},
|
||||
{
|
||||
name: 'params',
|
||||
type: 'array',
|
||||
admin: {
|
||||
description:
|
||||
'Key/value pairs sent with the event. A value starting with "$" is taken from a form field, e.g. $topic → the chosen topic.',
|
||||
},
|
||||
fields: [
|
||||
{ name: 'key', type: 'text', required: true },
|
||||
{ name: 'value', type: 'text', required: true },
|
||||
],
|
||||
label: 'Event parameters',
|
||||
},
|
||||
],
|
||||
label: 'Analytics (GTM / dataLayer)',
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
export { formAnalyticsOnSuccess } from './formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from './formAnalytics.js'
|
||||
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
||||
export { buildFormAnalyticsFields } from './formAnalyticsFields.js'
|
||||
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
||||
// (Turnstile secret) — never import it from a client component.
|
||||
export { buildFormsPlugin } from './formsPluginConfig.js'
|
||||
|
||||
@@ -30,6 +30,11 @@ type UseContactFormOptions = {
|
||||
messages?: Partial<Record<keyof ContactFormValues, string>>
|
||||
/** Minimum message length. Default 10. */
|
||||
minMessageLength?: number
|
||||
/**
|
||||
* Called once after a successful submit — e.g. to fire a GTM `form_submit`
|
||||
* event: `onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic })`.
|
||||
*/
|
||||
onSuccess?: (result: { message?: string; success: boolean }, values: ContactFormValues) => void
|
||||
/** Whether consent is required (project passes true when consentText shown). */
|
||||
requireConsent?: boolean
|
||||
/** Whether a topic must be chosen (project passes this when topics exist). */
|
||||
@@ -56,6 +61,7 @@ export function useContactForm(options: UseContactFormOptions) {
|
||||
initialTopic = '',
|
||||
messages,
|
||||
minMessageLength = 10,
|
||||
onSuccess,
|
||||
requireConsent = false,
|
||||
requireTopic = false,
|
||||
requireTurnstile = false,
|
||||
@@ -84,6 +90,7 @@ export function useContactForm(options: UseContactFormOptions) {
|
||||
phone: '',
|
||||
topic: initialTopic,
|
||||
},
|
||||
onSuccess,
|
||||
requireTurnstile,
|
||||
submitAction,
|
||||
validate,
|
||||
|
||||
@@ -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