46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
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)
|
|
}
|
|
}
|