Added better support for GTM, improved accesibility

This commit is contained in:
2026-10-11 14:46:47 +02:00
parent fd6fb426b3
commit 6be783bc5a
53 changed files with 849 additions and 110 deletions
@@ -23,21 +23,26 @@ export type A11yTexts = {
underlineLinks?: string
}
/**
* English defaults. The widget is end-user facing and multilingual projects run
* in many locales, so the plugin ships a neutral English baseline — NOT Polish.
* Localize by passing `texts` for the active locale (see the component doc).
*/
const DEFAULT_TEXTS: Required<A11yTexts> = {
bigCursor: 'Duży kursor',
close: 'Zamknij',
contrast: 'Kontrast',
contrastHigh: 'Wysoki',
contrastInverted: 'Odwrócony',
grayscale: 'Skala szarości',
lineHeight: 'Odstęp między liniami',
open: 'Otwórz panel dostępności',
readableFont: 'Czytelna czcionka',
reduceMotion: 'Wyłącz animacje',
reset: 'Resetuj',
textSize: 'Rozmiar tekstu',
title: 'Dostępność',
underlineLinks: 'Podkreśl linki',
bigCursor: 'Large cursor',
close: 'Close',
contrast: 'Contrast',
contrastHigh: 'High',
contrastInverted: 'Inverted',
grayscale: 'Grayscale',
lineHeight: 'Line spacing',
open: 'Open accessibility panel',
readableFont: 'Readable font',
reduceMotion: 'Reduce motion',
reset: 'Reset',
textSize: 'Text size',
title: 'Accessibility',
underlineLinks: 'Underline links',
}
export type A11yClassNames = {
@@ -61,6 +66,16 @@ export type A11yClassNames = {
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*
* Labels default to English; localize per locale by passing `texts` for the
* active language. Keep the translations in the project (or a localized global)
* and pass the active locale's set — the plugin stays content-agnostic:
*
* const A11Y: Record<string, A11yTexts> = {
* pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … },
* de: { title: 'Barrierefreiheit', … },
* }
* <AccessibilityWidget texts={A11Y[locale]} classNames={…} />
*/
export function AccessibilityWidget({
classNames,
+1
View File
@@ -1,2 +1,3 @@
'use client'
export { Analytics } from './Analytics.js'
export { pushDataLayer } from './pushDataLayer.js'
+24
View File
@@ -0,0 +1,24 @@
/**
* Pushes an event onto the GTM `window.dataLayer`. SSR-safe (no-op on the
* server), and tolerant of GTM not being present yet — the array is created so
* the event is buffered and picked up once GTM loads.
*
* The bridge between the form engine and GTM: fire a `form_submit` event after
* a successful submit so a Meta Pixel / GA "Lead" tag can trigger on it.
*
* import { pushDataLayer } from '@intecion/ipal-kit/client'
* const f = useContactForm({
* submitAction,
* onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
* })
*
* The GTM "Lead" tag then reads `form_name` via a Data Layer Variable
* (`DLV – form_name`) and fires on the custom event `form_submit`. Consent still
* gates the tag in GTM (ad_storage) — this only emits the event.
*/
export function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {
if (typeof window === 'undefined') return
const w = window as unknown as { dataLayer?: unknown[] }
w.dataLayer = w.dataLayer || []
w.dataLayer.push({ event, ...params })
}
+45
View File
@@ -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)
}
}
+59
View File
@@ -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)',
},
]
}
+4
View File
@@ -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'
+7
View File
@@ -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,
+42 -23
View File
@@ -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,
+2 -2
View File
@@ -35,8 +35,8 @@ export function buildPreventDeleteSystemPage(
assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned
if (assignedId != null && String(assignedId) === String(id)) {
throw new APIError(
`Nie można usunąć strony przypisanej do roli systemowej "${field}". ` +
`Najpierw odłącz rolę w Site Settings.`,
`Cannot delete a page assigned to the system role "${field}". ` +
`Detach the role in Site Settings first.`,
400,
)
}
+2 -2
View File
@@ -57,8 +57,8 @@ function writePath(obj: Record<string, unknown>, path: string[], value: unknown)
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
const {
name = 'noindex',
description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.',
label = 'Wyklucz z indeksowania (noindex)',
description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.',
label = 'Exclude from indexing (noindex)',
metaPath = 'meta.noindex',
overrides = {},
} = args
+2 -2
View File
@@ -62,8 +62,8 @@ export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {
const {
name = 'aiSummary',
autoFill = true,
description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.',
label = 'Streszczenie dla AI',
description = 'Concise page description for AI agents and llms.txt (richer than the meta description). Leave empty to auto-generate from the content.',
label = 'AI summary',
layoutField = 'layout',
maxLength = 300,
overrides = {},