Compare commits

..
2 Commits
Author SHA1 Message Date
radoslaw.smolinski 10d1806130 1.7.1 2026-10-11 14:46:56 +02:00
radoslaw.smolinski 6be783bc5a Added better support for GTM, improved accesibility 2026-10-11 14:46:47 +02:00
54 changed files with 850 additions and 111 deletions
+3
View File
@@ -3,6 +3,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
@@ -12,6 +13,8 @@ export { Analytics } from '../modules/analytics/client.js';
*/
export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
export type { CookieBannerClassNames } from '../modules/consent/client.js';
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
+2
View File
@@ -3,6 +3,7 @@ export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
@@ -10,6 +11,7 @@ export { Analytics } from '../modules/analytics/client.js';
* components. Kept separate from the main entry so server bundles don't pull in
* client-only code.
*/ export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport { pushDataLayer } from '../modules/analytics/client.js'\n\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,aAAa,QAAQ,iCAAgC;AAE9D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
+1
View File
@@ -18,6 +18,7 @@ export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js';
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js';
+2
View File
@@ -11,6 +11,8 @@ export { mailAdapter } from './modules/email/mailAdapter.js';
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
// Validation rules are pure — exported server-side too, for re-validating a
+1 -1
View File
File diff suppressed because one or more lines are too long
+10
View File
@@ -34,6 +34,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 declare function AccessibilityWidget({ classNames, texts, }: {
classNames?: A11yClassNames;
+29 -15
View File
@@ -2,21 +2,25 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { useAccessibility } from './AccessibilityProvider.js';
const DEFAULT_TEXTS = {
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'
/**
* 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 = {
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'
};
/**
* Accessibility toolbar: a floating button that opens a panel of options (text
@@ -28,6 +32,16 @@ const DEFAULT_TEXTS = {
* 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, texts }) {
const { reset, set, state } = useAccessibility();
const [open, setOpen] = useState(false);
File diff suppressed because one or more lines are too long
+1
View File
@@ -1 +1,2 @@
export { Analytics } from './Analytics.js';
export { pushDataLayer } from './pushDataLayer.js';
+1
View File
@@ -1,4 +1,5 @@
'use client';
export { Analytics } from './Analytics.js';
export { pushDataLayer } from './pushDataLayer.js';
//# sourceMappingURL=client.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\n"],"names":["Analytics"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB"}
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB"}
+19
View File
@@ -0,0 +1,19 @@
/**
* 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 declare function pushDataLayer(event: string, params?: Record<string, unknown>): void;
+28
View File
@@ -0,0 +1,28 @@
/**
* 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, params = {}) {
if (typeof window === 'undefined') return;
const w = window;
w.dataLayer = w.dataLayer || [];
w.dataLayer.push({
event,
...params
});
}
//# sourceMappingURL=pushDataLayer.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/pushDataLayer.ts"],"sourcesContent":["/**\n * Pushes an event onto the GTM `window.dataLayer`. SSR-safe (no-op on the\n * server), and tolerant of GTM not being present yet — the array is created so\n * the event is buffered and picked up once GTM loads.\n *\n * The bridge between the form engine and GTM: fire a `form_submit` event after\n * a successful submit so a Meta Pixel / GA \"Lead\" tag can trigger on it.\n *\n * import { pushDataLayer } from '@intecion/ipal-kit/client'\n * const f = useContactForm({\n * submitAction,\n * onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),\n * })\n *\n * The GTM \"Lead\" tag then reads `form_name` via a Data Layer Variable\n * (`DLV – form_name`) and fires on the custom event `form_submit`. Consent still\n * gates the tag in GTM (ad_storage) — this only emits the event.\n */\nexport function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {\n if (typeof window === 'undefined') return\n const w = window as unknown as { dataLayer?: unknown[] }\n w.dataLayer = w.dataLayer || []\n w.dataLayer.push({ event, ...params })\n}\n"],"names":["pushDataLayer","event","params","window","w","dataLayer","push"],"mappings":"AAAA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,cAAcC,KAAa,EAAEC,SAAkC,CAAC,CAAC;IAC/E,IAAI,OAAOC,WAAW,aAAa;IACnC,MAAMC,IAAID;IACVC,EAAEC,SAAS,GAAGD,EAAEC,SAAS,IAAI,EAAE;IAC/BD,EAAEC,SAAS,CAACC,IAAI,CAAC;QAAEL;QAAO,GAAGC,MAAM;IAAC;AACtC"}
+29
View File
@@ -0,0 +1,29 @@
/**
* 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 declare function formAnalyticsOnSuccess<T extends Record<string, unknown>>(config: FormAnalyticsConfig): (result: {
success: boolean;
}, values: T) => void;
+35
View File
@@ -0,0 +1,35 @@
import { pushDataLayer } from '../analytics/pushDataLayer.js';
/**
* 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(config) {
return (_result, values)=>{
const event = config?.event?.trim();
if (!event) {
return;
}
const params = {};
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);
};
}
//# sourceMappingURL=formAnalytics.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/forms/formAnalytics.ts"],"sourcesContent":["import { pushDataLayer } from '../analytics/pushDataLayer.js'\n\n/**\n * Shape of the per-form analytics config an editor fills in the panel (see\n * buildFormAnalyticsFields). Loose by design — it comes from Payload.\n */\nexport type FormAnalyticsConfig =\n | {\n event?: null | string\n params?: { key?: null | string; value?: null | string }[] | null\n }\n | null\n | undefined\n\n/**\n * Builds an `onSuccess` handler from a form's panel-configured analytics, so the\n * GTM `dataLayer` event is emitted on submit with ZERO per-form code. Wire it\n * once in the shared form renderer — every form then gets its tracking from the\n * panel:\n *\n * const f = useContactForm({\n * submitAction,\n * onSuccess: formAnalyticsOnSuccess(form.analytics),\n * })\n *\n * A param value starting with `$` is resolved from the submitted values, so an\n * editor can set `form_name = $topic` and get the chosen topic with no code.\n * No event name configured → the returned handler is a no-op.\n */\nexport function formAnalyticsOnSuccess<T extends Record<string, unknown>>(\n config: FormAnalyticsConfig,\n): (result: { success: boolean }, values: T) => void {\n return (_result, values) => {\n const event = config?.event?.trim()\n if (!event) {return}\n const params: Record<string, unknown> = {}\n for (const p of config?.params ?? []) {\n const key = p?.key?.trim()\n if (!key) {continue}\n const raw = typeof p?.value === 'string' ? p.value : ''\n params[key] = raw.startsWith('$') ? (values[raw.slice(1)] ?? '') : raw\n }\n pushDataLayer(event, params)\n }\n}\n"],"names":["pushDataLayer","formAnalyticsOnSuccess","config","_result","values","event","trim","params","p","key","raw","value","startsWith","slice"],"mappings":"AAAA,SAASA,aAAa,QAAQ,gCAA+B;AAc7D;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,uBACdC,MAA2B;IAE3B,OAAO,CAACC,SAASC;QACf,MAAMC,QAAQH,QAAQG,OAAOC;QAC7B,IAAI,CAACD,OAAO;YAAC;QAAM;QACnB,MAAME,SAAkC,CAAC;QACzC,KAAK,MAAMC,KAAKN,QAAQK,UAAU,EAAE,CAAE;YACpC,MAAME,MAAMD,GAAGC,KAAKH;YACpB,IAAI,CAACG,KAAK;gBAAC;YAAQ;YACnB,MAAMC,MAAM,OAAOF,GAAGG,UAAU,WAAWH,EAAEG,KAAK,GAAG;YACrDJ,MAAM,CAACE,IAAI,GAAGC,IAAIE,UAAU,CAAC,OAAQR,MAAM,CAACM,IAAIG,KAAK,CAAC,GAAG,IAAI,KAAMH;QACrE;QACAV,cAAcK,OAAOE;IACvB;AACF"}
+21
View File
@@ -0,0 +1,21 @@
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 declare function buildFormAnalyticsFields(): Field[];
+63
View File
@@ -0,0 +1,63 @@
/**
* 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() {
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)'
}
];
}
//# sourceMappingURL=formAnalyticsFields.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/forms/formAnalyticsFields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Panel fields that let an EDITOR configure a form's analytics event — the GTM\n * `dataLayer` push fired on successful submit — without any code change. Add\n * them to the Forms collection via the plugin's `formOverrides`:\n *\n * ipalKit({\n * forms: {\n * formOverrides: {\n * fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],\n * },\n * },\n * })\n *\n * The front reads this config and emits the event automatically via\n * `formAnalyticsOnSuccess` (see forms.md) — so adding a tracked form, or\n * changing its event name/params, is panel-only. The GTM side (the Lead/Pixel\n * tag, its trigger and consent gate) stays in GTM, which is itself a no-code\n * panel for tags.\n */\nexport function buildFormAnalyticsFields(): Field[] {\n return [\n {\n name: 'analytics',\n type: 'group',\n admin: {\n description:\n 'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.',\n },\n fields: [\n {\n name: 'event',\n type: 'text',\n admin: {\n description:\n 'Empty = nothing is pushed. Default \"form_submit\" — attach your GTM trigger to it.',\n },\n defaultValue: 'form_submit',\n label: 'Event name',\n },\n {\n name: 'params',\n type: 'array',\n admin: {\n description:\n 'Key/value pairs sent with the event. A value starting with \"$\" is taken from a form field, e.g. $topic → the chosen topic.',\n },\n fields: [\n { name: 'key', type: 'text', required: true },\n { name: 'value', type: 'text', required: true },\n ],\n label: 'Event parameters',\n },\n ],\n label: 'Analytics (GTM / dataLayer)',\n },\n ]\n}\n"],"names":["buildFormAnalyticsFields","name","type","admin","description","fields","defaultValue","label","required"],"mappings":"AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASA;IACd,OAAO;QACL;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,aACE;YACJ;YACAC,QAAQ;gBACN;oBACEJ,MAAM;oBACNC,MAAM;oBACNC,OAAO;wBACLC,aACE;oBACJ;oBACAE,cAAc;oBACdC,OAAO;gBACT;gBACA;oBACEN,MAAM;oBACNC,MAAM;oBACNC,OAAO;wBACLC,aACE;oBACJ;oBACAC,QAAQ;wBACN;4BAAEJ,MAAM;4BAAOC,MAAM;4BAAQM,UAAU;wBAAK;wBAC5C;4BAAEP,MAAM;4BAASC,MAAM;4BAAQM,UAAU;wBAAK;qBAC/C;oBACDD,OAAO;gBACT;aACD;YACDA,OAAO;QACT;KACD;AACH"}
+3
View File
@@ -1,3 +1,6 @@
export { formAnalyticsOnSuccess } from './formAnalytics.js';
export type { FormAnalyticsConfig } from './formAnalytics.js';
export { buildFormAnalyticsFields } from './formAnalyticsFields.js';
export { buildFormsPlugin } from './formsPluginConfig.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js';
export { checkRateLimit } from './rateLimit.js';
+3
View File
@@ -1,3 +1,6 @@
export { formAnalyticsOnSuccess } 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';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\n// Honeypot anti-spam (pure — client renders the input, server checks it).\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,gBAAe;AACrF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["export { formAnalyticsOnSuccess } from './formAnalytics.js'\nexport type { FormAnalyticsConfig } from './formAnalytics.js'\n// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).\nexport { buildFormAnalyticsFields } from './formAnalyticsFields.js'\n// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\n// Honeypot anti-spam (pure — client renders the input, server checks it).\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["formAnalyticsOnSuccess","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,qBAAoB;AAE3D,kFAAkF;AAClF,SAASC,wBAAwB,QAAQ,2BAA0B;AACnE,6EAA6E;AAC7E,gEAAgE;AAChE,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,gBAAe;AACrF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
+17 -9
View File
@@ -22,6 +22,14 @@ 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). */
@@ -42,19 +50,19 @@ type UseContactFormOptions = {
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/
export declare function useContactForm(options: UseContactFormOptions): {
values: ContactFormValues;
errors: Partial<Record<keyof ContactFormValues, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
errors: Partial<Record<keyof ContactFormValues, string>>;
handleSubmit: (e?: {
preventDefault?: (() => void) | undefined;
} | undefined) => Promise<void>;
isSubmitting: boolean;
isSuccess: boolean;
reset: () => void;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
turnstileToken: string | null;
values: ContactFormValues;
};
export {};
+2 -1
View File
@@ -13,7 +13,7 @@ import { buildValidator, checked, email, minLength, required } from './validator
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/ export function useContactForm(options) {
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, onSuccess, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const validate = useMemo(()=>buildValidator({
name: [
required(messages?.name)
@@ -52,6 +52,7 @@ import { buildValidator, checked, email, minLength, required } from './validator
phone: '',
topic: initialTopic
},
onSuccess,
requireTurnstile,
submitAction,
validate
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAoCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGR;IAEJ,MAAMS,WAAWjB,QACf,IACEE,eAAkC;YAChCgB,MAAM;gBAACZ,SAASK,UAAUO;aAAM;YAChCd,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIU,eAAe;gBAAEK,OAAO;oBAACb,SAASK,UAAUQ;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACd,SAASK,UAAUS;gBAAUf,UAAUO,kBAAkBD,UAAUS;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAAClB,QAAQQ,UAAUU;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBD;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAa,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTjB,OAAO;YACPgB,SAAS;YACTG,OAAO;YACPJ,OAAOT;QACT;QACAK;QACAC;QACAC;IACF;AACF"}
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /**\n * Called once after a successful submit — e.g. to fire a GTM `form_submit`\n * event: `onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic })`.\n */\n onSuccess?: (result: { message?: string; success: boolean }, values: ContactFormValues) => void\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n onSuccess,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n onSuccess,\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","onSuccess","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAyCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,SAAS,EACTC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGT;IAEJ,MAAMU,WAAWlB,QACf,IACEE,eAAkC;YAChCiB,MAAM;gBAACb,SAASK,UAAUQ;aAAM;YAChCf,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIW,eAAe;gBAAEK,OAAO;oBAACd,SAASK,UAAUS;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACf,SAASK,UAAUU;gBAAUhB,UAAUO,kBAAkBD,UAAUU;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAACnB,QAAQQ,UAAUW;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBF;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAc,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTlB,OAAO;YACPiB,SAAS;YACTG,OAAO;YACPJ,OAAOV;QACT;QACAG;QACAG;QACAC;QACAC;IACF;AACF"}
+30 -16
View File
@@ -11,23 +11,37 @@ export type FormErrors<T> = Partial<Record<keyof T, string>>;
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
*/
export type FormSubmitAction<T> = (values: T, turnstileToken?: string) => Promise<{
success: boolean;
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;
};
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
@@ -52,19 +66,19 @@ type UseFormOptions<T extends Record<string, unknown>> = {
* <form onSubmit={f.handleSubmit}>…</form>
*/
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
values: T;
errors: Partial<Record<keyof T, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof T>(key: K, value: T[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
errors: Partial<Record<keyof T, string>>;
handleSubmit: (e?: {
preventDefault?: () => void;
}) => Promise<void>;
isSubmitting: boolean;
isSuccess: boolean;
reset: () => void;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
setField: <K extends keyof T>(key: K, value: T[K]) => void;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
turnstileToken: string | null;
values: T;
};
export {};
+22 -11
View File
@@ -1,5 +1,5 @@
'use client';
import { useState, useCallback, useRef, useMemo } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
@@ -22,7 +22,7 @@ import { useState, useCallback, useRef, useMemo } from 'react';
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/ export function useForm(options) {
const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options;
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);
@@ -39,7 +39,9 @@ import { useState, useCallback, useRef, useMemo } from 'react';
}));
if (clearErrorOnChange) {
setErrors((prev)=>{
if (!prev[key]) return prev;
if (!prev[key]) {
return prev;
}
const next = {
...prev
};
@@ -56,12 +58,16 @@ import { useState, useCallback, useRef, useMemo } from 'react';
valuesRef.current = values;
const validateRef = useRef(validate);
validateRef.current = validate;
const onSuccessRef = useRef(options.onSuccess);
onSuccessRef.current = options.onSuccess;
const handleSubmit = useCallback(async (e)=>{
e?.preventDefault?.();
setErrorMessage(null);
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);
return;
@@ -72,6 +78,11 @@ import { useState, useCallback, useRef, useMemo } from 'react';
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);
}
@@ -94,18 +105,18 @@ import { useState, useCallback, useRef, useMemo } from 'react';
setTurnstileToken(null);
}, []);
return useMemo(()=>({
values,
errorMessage,
errors,
handleSubmit,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
setValues,
reset,
setErrors,
setField,
setTurnstileToken,
handleSubmit,
reset
setValues,
turnstileToken,
values
}), [
values,
errors,
+1 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -28,7 +28,7 @@ import { APIError } from 'payload';
const assigned = settings[field];
const assignedId = assigned && typeof assigned === 'object' ? assigned.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.`, 400);
throw new APIError(`Cannot delete a page assigned to the system role "${field}". ` + `Detach the role in Site Settings first.`, 400);
}
}
};
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/hooks/preventDeleteSystemPage.ts"],"sourcesContent":["import type { CollectionBeforeDeleteHook } from 'payload'\n\nimport { APIError } from 'payload'\n\n/**\n * Blocks deletion of a page assigned a System Page role (homepage,\n * privacyPolicy, cookiePolicy, termsOfService). An editor deleting the privacy\n * policy or homepage by accident would break routing and compliance links; this\n * stops it with a clear error. They must unassign the role first (deliberate).\n *\n * Reads the role assignments from SiteSettings (which page holds which role).\n *\n * hooks: { beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })] }\n */\nexport function buildPreventDeleteSystemPage(\n args: { roleFields?: string[]; settingsSlug?: string } = {},\n): CollectionBeforeDeleteHook {\n const settingsSlug = args.settingsSlug ?? 'site-settings'\n const roleFields = args.roleFields ?? [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n ]\n\n return async ({ id, req }) => {\n const settings = (await req.payload\n .findGlobal({ slug: settingsSlug as never, depth: 0 })\n .catch(() => null)) as null | Record<string, unknown>\n if (!settings) {return}\n\n for (const field of roleFields) {\n const assigned = settings[field]\n const assignedId =\n assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned\n if (assignedId != null && String(assignedId) === String(id)) {\n throw new APIError(\n `Nie można usunąć strony przypisanej do roli systemowej \"${field}\". ` +\n `Najpierw odłącz rolę w Site Settings.`,\n 400,\n )\n }\n }\n }\n}\n"],"names":["APIError","buildPreventDeleteSystemPage","args","settingsSlug","roleFields","id","req","settings","payload","findGlobal","slug","depth","catch","field","assigned","assignedId","String"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAElC;;;;;;;;;CASC,GACD,OAAO,SAASC,6BACdC,OAAyD,CAAC,CAAC;IAE3D,MAAMC,eAAeD,KAAKC,YAAY,IAAI;IAC1C,MAAMC,aAAaF,KAAKE,UAAU,IAAI;QACpC;QACA;QACA;QACA;KACD;IAED,OAAO,OAAO,EAAEC,EAAE,EAAEC,GAAG,EAAE;QACvB,MAAMC,WAAY,MAAMD,IAAIE,OAAO,CAChCC,UAAU,CAAC;YAAEC,MAAMP;YAAuBQ,OAAO;QAAE,GACnDC,KAAK,CAAC,IAAM;QACf,IAAI,CAACL,UAAU;YAAC;QAAM;QAEtB,KAAK,MAAMM,SAAST,WAAY;YAC9B,MAAMU,WAAWP,QAAQ,CAACM,MAAM;YAChC,MAAME,aACJD,YAAY,OAAOA,aAAa,WAAW,AAACA,SAA8BT,EAAE,GAAGS;YACjF,IAAIC,cAAc,QAAQC,OAAOD,gBAAgBC,OAAOX,KAAK;gBAC3D,MAAM,IAAIL,SACR,CAAC,wDAAwD,EAAEa,MAAM,GAAG,CAAC,GACnE,CAAC,qCAAqC,CAAC,EACzC;YAEJ;QACF;IACF;AACF"}
{"version":3,"sources":["../../../src/modules/hooks/preventDeleteSystemPage.ts"],"sourcesContent":["import type { CollectionBeforeDeleteHook } from 'payload'\n\nimport { APIError } from 'payload'\n\n/**\n * Blocks deletion of a page assigned a System Page role (homepage,\n * privacyPolicy, cookiePolicy, termsOfService). An editor deleting the privacy\n * policy or homepage by accident would break routing and compliance links; this\n * stops it with a clear error. They must unassign the role first (deliberate).\n *\n * Reads the role assignments from SiteSettings (which page holds which role).\n *\n * hooks: { beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })] }\n */\nexport function buildPreventDeleteSystemPage(\n args: { roleFields?: string[]; settingsSlug?: string } = {},\n): CollectionBeforeDeleteHook {\n const settingsSlug = args.settingsSlug ?? 'site-settings'\n const roleFields = args.roleFields ?? [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n ]\n\n return async ({ id, req }) => {\n const settings = (await req.payload\n .findGlobal({ slug: settingsSlug as never, depth: 0 })\n .catch(() => null)) as null | Record<string, unknown>\n if (!settings) {return}\n\n for (const field of roleFields) {\n const assigned = settings[field]\n const assignedId =\n assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned\n if (assignedId != null && String(assignedId) === String(id)) {\n throw new APIError(\n `Cannot delete a page assigned to the system role \"${field}\". ` +\n `Detach the role in Site Settings first.`,\n 400,\n )\n }\n }\n }\n}\n"],"names":["APIError","buildPreventDeleteSystemPage","args","settingsSlug","roleFields","id","req","settings","payload","findGlobal","slug","depth","catch","field","assigned","assignedId","String"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAElC;;;;;;;;;CASC,GACD,OAAO,SAASC,6BACdC,OAAyD,CAAC,CAAC;IAE3D,MAAMC,eAAeD,KAAKC,YAAY,IAAI;IAC1C,MAAMC,aAAaF,KAAKE,UAAU,IAAI;QACpC;QACA;QACA;QACA;KACD;IAED,OAAO,OAAO,EAAEC,EAAE,EAAEC,GAAG,EAAE;QACvB,MAAMC,WAAY,MAAMD,IAAIE,OAAO,CAChCC,UAAU,CAAC;YAAEC,MAAMP;YAAuBQ,OAAO;QAAE,GACnDC,KAAK,CAAC,IAAM;QACf,IAAI,CAACL,UAAU;YAAC;QAAM;QAEtB,KAAK,MAAMM,SAAST,WAAY;YAC9B,MAAMU,WAAWP,QAAQ,CAACM,MAAM;YAChC,MAAME,aACJD,YAAY,OAAOA,aAAa,WAAW,AAACA,SAA8BT,EAAE,GAAGS;YACjF,IAAIC,cAAc,QAAQC,OAAOD,gBAAgBC,OAAOX,KAAK;gBAC3D,MAAM,IAAIL,SACR,CAAC,kDAAkD,EAAEa,MAAM,GAAG,CAAC,GAC7D,CAAC,uCAAuC,CAAC,EAC3C;YAEJ;QACF;IACF;AACF"}
+1 -1
View File
@@ -34,7 +34,7 @@
* import { buildNoindexField } from '@intecion/ipal-kit'
* fields: [ /* … *\/ buildNoindexField() ],
*/ export function buildNoindexField(args = {}) {
const { name = 'noindex', description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.', label = 'Wyklucz z indeksowania (noindex)', metaPath = 'meta.noindex', overrides = {} } = args;
const { name = '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;
const segments = metaPath.split('.');
const mirror = ({ data, value })=>{
const shouldNoindex = Boolean(value ?? readPath(data, segments));
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -34,7 +34,7 @@ import { blocksToMarkdown } from '../content/blocksToMarkdown.js';
* buildLlmsTxt({ …, summaryField: 'aiSummary' })
* createSearchRoute({ …, summaryField: 'aiSummary' })
*/ export function buildSummaryField(args = {}) {
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', layoutField = 'layout', maxLength = 300, overrides = {} } = args;
const { name = 'aiSummary', autoFill = true, 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 = {} } = args;
const autofillHook = ({ data, value })=>{
if (typeof value === 'string' && value.trim()) {
return value;
File diff suppressed because one or more lines are too long
+23 -1
View File
@@ -40,7 +40,7 @@ import { AccessibilityProvider, AccessibilityWidget } from '@intecion/ipal-kit/c
resetButton: 'a11y-reset',
closeButton: 'a11y-close',
}}
texts={{ title: 'Dostępność', reset: 'Resetuj' }} // opcjonalne, PL domyślnie
texts={A11Y[locale]} // etykiety per locale; domyślnie ANGIELSKI
/>
</body>
</AccessibilityProvider>
@@ -48,6 +48,28 @@ import { AccessibilityProvider, AccessibilityWidget } from '@intecion/ipal-kit/c
Widget jest bez stylów (jak CookieBanner) — classNames dopasowujesz do designu.
## Etykiety — domyślnie angielski, konfiguracja per locale
Domyślne etykiety są **angielskie** (plugin jest wielojęzyczny, neutralny bazowo).
Tłumaczenia trzymasz w projekcie i podajesz zestaw dla aktywnego języka przez
`texts` (`A11yTexts`). Plugin pozostaje content-agnostyczny:
```tsx
import type { A11yTexts } from '@intecion/ipal-kit/client'
const A11Y: Record<string, A11yTexts> = {
pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', reset: 'Resetuj', /* … */ },
de: { title: 'Barrierefreiheit', textSize: 'Textgröße', /* … */ },
}
<AccessibilityWidget texts={A11Y[locale]} classNames={{ /* … */ }} />
```
Podajesz tylko te klucze, które chcesz nadpisać — reszta spadnie na angielski
default. Możesz też trzymać etykiety w zlokalizowanym globalu i czytać je z panelu
(spójne z „zarządzanie z panelu"), ale to już decyzja projektu — plugin wymaga
tylko `A11yTexts` dla bieżącego locale.
---
## 2. CSS reagujący na atrybuty (OBOWIĄZKOWE — projekt)
+23
View File
@@ -68,6 +68,29 @@ W konsoli: `window.dataLayer` — powinien zawierać `Arguments(3)` z `consent`
Ciasteczko `_ga` pojawia się dopiero po zgodzie na analytics — to jest sedno
Consent Mode.
## Zdarzenia do GTM — pushDataLayer
Do wypchnięcia własnego zdarzenia (np. `form_submit` pod tag Lead w GTM) jest
helper `pushDataLayer` (SSR-safe, buforuje gdy GTM jeszcze nie wstał):
```tsx
import { pushDataLayer } from '@intecion/ipal-kit/client'
pushDataLayer('form_submit', { form_name: 'kontakt' })
```
Najczęstsze użycie — `onSuccess` formularza (patrz [forms.md](./forms.md)):
```tsx
const f = useContactForm({
submitAction,
onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
})
```
**To tylko emisja zdarzenia — zgodę nadal gatuje GTM** (`ad_storage` dla tagów
marketingowych jak Meta Pixel). `pushDataLayer` nie omija consentu; daje GTM
czysty event, na którym tag może się odpalić, gdy zgoda jest udzielona.
**GTM sam nie ustawia ciasteczek** — to pojemnik. Bez opublikowanego (Submit →
Publish, nie sam zapis) tagu GA4 w kontenerze wszystko wygląda dobrze:
`gtm.load` w dataLayer, Tag Assistant widzi kontener — a `_ga` nie ma, bo nic go
+61
View File
@@ -338,6 +338,67 @@ const f = useForm({ initialValues, submitAction, validate })
jak dawny boolean, a dodatkowo masz tekst do wyświetlenia. `setField` czyści błąd
pola przy edycji (domyślnie).
### Event GTM/analytics po wysłaniu (Lead/Pixel)
Tag „Lead" (Meta Pixel / GA) w GTM zwykle odpala się na zdarzeniu `form_submit`
w `dataLayer`. Hook ma `onSuccess` (odpala się RAZ po udanej wysyłce), a plugin
daje helper `pushDataLayer` — więc event leci automatycznie, bez ręcznego pushu
w każdym projekcie:
```tsx
import { useContactForm, pushDataLayer } from '@intecion/ipal-kit/client'
const f = useContactForm({
submitAction,
onSuccess: (_result, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
})
```
W GTM: Data Layer Variable `DLV – form_name` (klucz `form_name`) + custom event
trigger `form_submit`. **Zgodę nadal gatuje GTM** (`ad_storage`) — `pushDataLayer`
tylko emituje zdarzenie, nie omija consentu. `onSuccess` jest owinięty w
try/catch — zepsuty analytics nie zablokuje udanej wysyłki. `pushDataLayer` jest
SSR-safe i buforuje event, gdy GTM jeszcze się nie załadował.
#### Zarządzanie z PANELU (bez kodu per formularz)
Zamiast wpisywać nazwę eventu/parametry w kodzie, przenieś to do panelu. Dodaj
pola analityki do kolekcji Forms:
```ts
// payload.config.ts
import { buildFormAnalyticsFields } from '@intecion/ipal-kit'
ipalKit({
forms: {
formOverrides: {
fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
},
},
})
```
Redaktor ustawia per formularz (etykiety panelu po angielsku): **Event name**
(domyślnie `form_submit`) i **Event parameters** (klucz/wartość; wartość `$pole`
bierze się z pola formularza, np. `form_name = $topic`). Grupa pól nazywa się
**Analytics (GTM / dataLayer)**. Front czyta to i emituje automatycznie — jedna, generyczna
linia w współdzielonym rendererze, działa dla WSZYSTKICH formularzy:
```tsx
import { useContactForm, formAnalyticsOnSuccess } from '@intecion/ipal-kit/client'
const f = useContactForm({
submitAction,
onSuccess: formAnalyticsOnSuccess(form.analytics), // form.analytics z panelu
})
```
Efekt: dodanie śledzonego formularza albo zmiana nazwy eventu/parametrów = **tylko
panel, zero deployu**. Pusta nazwa zdarzenia → nic się nie wypycha.
Co zostaje w GTM (świadomie — to też panel, tylko Google): sam tag (Lead/Pixel),
jego trigger na nazwę zdarzenia i warunek zgody `ad_storage`. Plugin dostarcza
event + sygnał consentu; GTM decyduje, co i kiedy odpalić.
### resolveLocalized — koniec z getSafeString
Rozwiązywanie wartości lokalizowanej (topics, etykiety) to jeden import, nie
+182
View File
@@ -0,0 +1,182 @@
# GTM + Meta Pixel — konfiguracja (stack ipal-kit)
Przewodnik krok po kroku, jak podpiąć Meta Pixel przez Google Tag Manager na
stronie zbudowanej na `@intecion/ipal-kit`. Napisany pod nasz stack: część
roboty robi już plugin, resztę klikasz w panelu GTM — **bez zmian w kodzie per
projekt**.
Powiązane: [analytics.md](./analytics.md), [consent.md](./consent.md),
[forms.md](./forms.md).
---
## Co plugin robi ZA Ciebie (nie konfigurujesz tego w kodzie)
- **Ładuje kontener GTM** — `Analytics` bierze `GTM Container ID` z panelu
(Settings → Site Integrations). Zero kodu.
- **Consent Mode v2** — przed załadowaniem tagów wysyła `consent default`
(domyślnie `denied`), a po kliknięciu w banerze `consent update`. Kategoria
**marketing** → `ad_storage` / `ad_user_data` / `ad_personalization`.
- **Zdarzenie `form_submit`** — po udanej wysyłce formularza, z parametrami
ustawionymi **w panelu** (grupa pól „Analytics (GTM / dataLayer)" na
formularzu — panel jest po angielsku; patrz niżej).
Czyli w kodzie NIE dotykasz nic. Zostaje: wpisać ID w panelu, skonfigurować tagi
w GTM, ustawić event na formularzu w panelu.
---
## 0. Wymagania wstępne (panel Payload)
1. **GTM Container ID** w Settings → Site Integrations (`GTM-XXXXXXX`).
2. **Baner cookies** aktywny (`CookieBanner` + `ConsentProvider`) — inaczej
Consent Mode nie dostanie decyzji.
3. **Pole analityki na formularzu** — dodaj `buildFormAnalyticsFields()` do
kolekcji Forms (patrz [forms.md](./forms.md) → „Zarządzanie z panelu"), a w
rendererze: `onSuccess: formAnalyticsOnSuccess(form.analytics)`. W panelu (po
angielsku), na formularzu kontaktowym w grupie **Analytics (GTM / dataLayer)**
ustaw: **Event name** `form_submit`, parametr `form_name = $topic` (albo
stała, np. `kontakt`).
---
## 1. Pixel ID jako zmienna GTM
Events Manager → Źródła danych → Twój pixel → skopiuj **Pixel ID** (15–16 cyfr).
GTM → Zmienne → Zmienne zdefiniowane przez użytkownika → **Nowa** → **Stała** →
wartość = Pixel ID → nazwij `Meta Pixel ID`.
## 2. Szablon tagu Meta
Meta nie ma natywnego tagu w GTM. Dwie drogi:
- **Szablon społeczności (wygodniej):** Szablony → Szablony tagów → Przeszukaj
galerię → „Facebook Pixel" → Dodaj do obszaru roboczego.
- **Custom HTML:** wklej kod bazowy pixela z Events Manera (wariant dla pełnej
kontroli; wtedy pomijasz szablon i robisz tagi jako Custom HTML).
Poniżej zakładam szablon.
## 3. Tag bazowy — PageView
Tagi → **Nowy** → typ **Facebook Pixel**:
- **Pixel ID:** `{{Meta Pixel ID}}`
- **Event:** Standard → `PageView`
- **Ustawienia zgody** (Zaawansowane → Consent Settings): wymagaj **`ad_storage`**.
- **Trigger:** `All Pages` + (dla Next.js) drugi trigger **History Change** —
patrz sekcja SPA niżej.
Nazwij np. `Meta – Base + PageView`.
## 4. Zmienna dla parametru z formularza
Zmienne → **Nowa** → **Zmienna warstwy danych**:
- Nazwa zmiennej warstwy danych: `form_name`
- Wersja: Wersja 2
- Nazwij u góry dokładnie `DLV – form_name`.
> Nazwa w tagu i w zmiennej musi być **znak w znak** taka sama, łącznie z
> myślnikiem. Jeśli w tagu jest długi myślnik „–", a w zmiennej wpiszesz zwykły
> „-", GTM uzna to za dwie różne zmienne. Najbezpieczniej skopiuj tekst spomiędzy
> `{{` a `}}`.
## 5. Trigger — wysłanie formularza
Triggery → **Nowy** → **Zdarzenie niestandardowe**:
- Nazwa zdarzenia: `form_submit` (dokładnie tak, jak event z panelu formularza)
- Uruchamiany na: Wszystkie zdarzenia niestandardowe.
Nazwij `CE – form_submit`.
## 6. Tag konwersji — Lead
Tagi → **Nowy** → **Facebook Pixel**:
- **Pixel ID:** `{{Meta Pixel ID}}`
- **Event:** Standard → `Lead`
- **Object Properties / parametry:** `content_name` = `{{DLV – form_name}}`
- **Ustawienia zgody:** wymagaj **`ad_storage`** (tak samo jak tag bazowy).
- **Trigger:** `CE – form_submit`.
Nazwij `Meta – Lead`.
Inne konwersje analogicznie, każda jako osobny tag z tego samego szablonu:
- **Contact** — trigger na kliknięcie w `tel:` / `mailto:`.
- **ViewContent / AddToCart / Purchase** — parametry (`value`, `currency`,
`content_ids`) ze zmiennych warstwy danych; zdarzenie pushowane z kodu/panelu
tam, gdzie zachodzi akcja.
---
## 7. Zgoda (RODO) — krytyczne
Pixel marketingowy **nie może odpalić przed zgodą**. W każdym tagu Meta ustaw
Consent Settings → wymagaj `ad_storage`. Plugin trzyma `ad_storage = denied` do
czasu akceptacji w banerze i wysyła `update` po kliknięciu — tag odpali się
dopiero wtedy. Bez tego warunku pixel strzeli mimo braku zgody (naruszenie RODO).
W Podglądzie sprawdź: **przed** akceptacją baner → tag `Meta – Base + PageView`
ma być **zablokowany**; **po** akceptacji → „Uruchomiono".
## 8. Next.js / SPA — PageView przy zmianie trasy
Przy nawigacji po stronie klienta (routing Next.js bez pełnego przeładowania)
`All Pages` odpali się tylko raz. Dwie opcje:
- **W GTM (bez kodu, zalecane):** dodaj do tagu PageView drugi trigger typu
**Zmiana historii** (History Change). GTM łapie zmianę trasy.
- **Z kodu (jeśli wolisz jawne eventy):** pushuj `page_view` do dataLayer przy
zmianie trasy (`pushDataLayer('page_view')` na zmianę `usePathname`) i zrób
trigger `CE – page_view`.
W Podglądzie / Events Manager policz: ma być **jeden** PageView na zmianę
podstrony i brak podwójnego liczenia pierwszego wejścia.
## 9. Duplikaty
Jeśli pixel jest też wklejony na sztywno w kodzie strony albo przez inną wtyczkę
— **usuń go stamtąd**. Ma być tylko w GTM, inaczej zdarzenia liczą się podwójnie.
---
## 10. Test
1. **Podgląd GTM** (prawy górny róg) → podaj adres strony.
2. Zaakceptuj cookies marketingowe.
3. Tag Assistant: `Meta – Base + PageView` = „Uruchomiono" (przed zgodą
zablokowany).
4. Wyślij formularz → w lewej kolumnie zdarzenie `form_submit`, przy nim tag
`Meta – Lead` „Uruchomiono"; w zakładce Zmienne `DLV – form_name` ma wartość
(np. `kontakt`).
5. **Meta Pixel Helper** (rozszerzenie Chrome) → widzi PageView i Lead.
6. **Events Manager → Testuj zdarzenia** → wpisz adres → `PageView` i po
wysłaniu formularza `Lead` z parametrem `content_name`.
## 11. Publikacja
GTM → **Prześlij** → nazwa wersji (np. „Meta Pixel – PageView + Lead") →
**Opublikuj**. Do tego momentu nic nie działa na produkcji — sam zapis tagu nie
wystarczy.
---
## 12. (Opcjonalnie) Conversions API (CAPI)
Żeby wysyłać zdarzenia także z serwera (odporność na blokery/iOS), każde
zdarzenie potrzebuje wspólnego `event_id` w pixelu i w CAPI, żeby Meta mogła je
deduplikować. To osobny temat (server-side GTM albo wysyłka z backendu) — w tym
stacku `submitForm` (server) mógłby generować `event_id`, a `pushDataLayer`
używałby tego samego. Jeśli wchodzicie w CAPI, zgłoś — to rozszerzenie modułu
forms + analytics, nie konfiguracja GTM.
---
## Ściąga — kto co robi
| Element | Gdzie |
|---|---|
| Ładowanie GTM, Consent Mode | plugin (auto) |
| Event `form_submit` + parametry | panel Payload (grupa „Analytics" na formularzu) |
| Pixel ID, tagi, triggery, warunki zgody | panel GTM |
| Publikacja kontenera | panel GTM |
| Kod projektu | nic (poza jednorazowym `onSuccess` w rendererze) |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.0",
"version": "1.7.1",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+4 -1
View File
@@ -8,6 +8,8 @@ export {
} from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
/**
* Entry point: ipal-kit/client
*
@@ -23,8 +25,9 @@ export {
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type {
+2
View File
@@ -74,6 +74,8 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
export type {
@@ -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 = {},