Compare commits

...
8 Commits
77 changed files with 1673 additions and 201 deletions
+3 -1
View File
@@ -194,7 +194,7 @@ Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md.
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie zamiast wstrzyknięcia: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
@@ -236,6 +236,8 @@ Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-ki
| Walidacja ENV na starcie (assertEnv) | `env.md` |
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
+8
View File
@@ -0,0 +1,8 @@
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
+9
View File
@@ -0,0 +1,9 @@
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/ export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
//# sourceMappingURL=admin.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"}
+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"}
+52
View File
@@ -0,0 +1,52 @@
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
* set by the editor in the panel — not hardcoded per project. Wired
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
*/
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string;
/** Field holding the site name. Default 'siteName'. */
nameField?: string;
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string;
};
/**
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
* falls back to `siteName` text. Sized generously for the login screen.
*/
export declare function AdminLogo(props?: BrandingProps): Promise<import("react/jsx-runtime").JSX.Element | null>;
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */
export declare function AdminIcon(props?: BrandingProps): Promise<import("react/jsx-runtime").JSX.Element | null>;
/**
* Discreet vendor credit: "Technology supported by Intecion.com". This is the
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
* data — a sensible default here is fine and A0-safe. The client's own brand
* still owns the logo/name; this is a small line stating who supports the tech.
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
*
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
* (login screen footer). `variant` adjusts placement:
* - 'nav' → left-aligned line under the nav links
* - 'login' → centered line below the login form
*/
export declare function IntecionCredit(props?: {
text?: string;
url?: string;
variant?: 'login' | 'nav';
}): import("react/jsx-runtime").JSX.Element;
export {};
+124
View File
@@ -0,0 +1,124 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { getPayload } from 'payload';
async function loadBranding(settingsSlug, nameField, imageField) {
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config';
const mod = await import(spec);
const payload = await getPayload({
config: mod.default
});
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 1
});
const name = typeof settings[nameField] === 'string' ? settings[nameField] : null;
const image = settings[imageField];
const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null;
return {
name,
url
};
} catch {
return {
name: null,
url: null
};
}
}
/**
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
* falls back to `siteName` text. Sized generously for the login screen.
*/ export async function AdminLogo(props = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
src: url,
style: {
height: 'auto',
maxHeight: 120,
maxWidth: 420,
width: 'auto'
}
});
}
if (name) {
return /*#__PURE__*/ _jsx("div", {
style: {
fontSize: '2rem',
fontWeight: 600
},
children: name
});
}
return null // nothing configured → Payload's default
;
}
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
src: url,
style: {
height: 'auto',
maxHeight: 28,
maxWidth: 28,
width: 'auto'
}
});
}
if (name) {
return /*#__PURE__*/ _jsx("div", {
style: {
fontWeight: 700
},
children: name.slice(0, 2).toUpperCase()
});
}
return null;
}
/**
* Discreet vendor credit: "Technology supported by Intecion.com". This is the
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
* data — a sensible default here is fine and A0-safe. The client's own brand
* still owns the logo/name; this is a small line stating who supports the tech.
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
*
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
* (login screen footer). `variant` adjusts placement:
* - 'nav' → left-aligned line under the nav links
* - 'login' → centered line below the login form
*/ export function IntecionCredit(props = {}) {
const { text = 'Technology supported by Intecion.com', url = 'https://intecion.com', variant = 'nav' } = props;
const style = variant === 'login' ? {
color: 'inherit',
display: 'block',
fontSize: '0.75rem',
marginTop: '2rem',
opacity: 0.6,
padding: '0.5rem',
textAlign: 'center',
textDecoration: 'none'
} : {
color: 'inherit',
display: 'block',
fontSize: '0.75rem',
opacity: 0.6,
padding: '0.75rem 1rem',
textDecoration: 'none'
};
return /*#__PURE__*/ _jsx("a", {
href: url,
rel: "noopener noreferrer",
style: style,
target: "_blank",
children: text
});
}
//# sourceMappingURL=adminGraphics.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js';
+3
View File
@@ -0,0 +1,3 @@
export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/branding/index.ts"],"sourcesContent":["export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,qBAAoB"}
+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
+110 -21
View File
@@ -62,29 +62,118 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
if (!tf?.issuer) {
throw new Error('[ipal] twoFactor.issuer is required (name shown in the authenticator ' + 'app). Pass twoFactor: { issuer: "Your Site" }, or twoFactor: false to ' + 'opt out (discouraged).');
}
try {
// Dynamic specifier via a variable so TS doesn't try to resolve this
// optional peer dependency at build time (it isn't in the plugin's own
// node_modules). Avoids TS2307 without @ts-expect-error; the module
// exists at runtime in projects that installed it.
// @ts-ignore
const mod = await import('@clocklimited/payload-2fa');
// The package exports `payloadTotp`; older/other builds may use
// `totpPlugin`. Accept either so a rename doesn't break us.
const totp = mod.payloadTotp ?? mod.totpPlugin;
if (typeof totp !== 'function') {
throw new Error('expected export payloadTotp (or totpPlugin) to be a function — ' + 'check the installed @clocklimited/payload-2fa version');
// Prefer the INJECTED plugin factory (recommended): the project imports
// payloadTotp from @clocklimited/payload-2fa and passes it in. Then the
// plugin never imports the optional peer itself — no dynamic import, so
// Next can't fail to bundle it (the cause of "Cannot find module
// '@clocklimited/payload-2fa'" crashing even public frontend pages).
let totp = tf.plugin;
if (!totp) {
// Fallback: dynamic import. Variable specifier dodges the plugin's own
// TS2307, but Next may NOT trace it into the server bundle — projects
// using this path MUST add '@clocklimited/payload-2fa' to
// serverExternalPackages in next.config (see docs/security.md).
try {
const pkg = '@clocklimited/payload-2fa';
const mod = await import(pkg);
totp = mod.payloadTotp ?? mod.totpPlugin;
} catch (err) {
throw new Error('[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' + 'Best fix — inject it: `import { payloadTotp } from "@clocklimited/payload-2fa"` ' + 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' + "'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set " + `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`);
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true,
totp: {
issuer: tf.issuer
}
})(config);
} catch (err) {
throw new Error('[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' + 'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' + `opt out (discouraged). Original error: ${String(err)}`);
}
if (typeof totp !== 'function') {
throw new Error('[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' + 'injected `plugin` or the installed @clocklimited/payload-2fa version.');
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true,
totp: {
issuer: tf.issuer
}
})(config);
}
// --- white-label admin branding ---
// Inject admin.components.graphics.Logo/Icon pointing at the plugin's
// /admin export. The components read SiteSettings at render, so each client
// sees their own brand from the panel (no brand in code). Project must run
// `pnpm generate:importmap` so Payload resolves the component paths.
if (options.whiteLabel) {
const wl = options.whiteLabel === true ? {} : options.whiteLabel;
const serverProps = {};
if (wl.settingsSlug) {
serverProps.settingsSlug = wl.settingsSlug;
}
if (wl.nameField) {
serverProps.nameField = wl.nameField;
}
const logoProps = {
...serverProps,
...wl.logoField ? {
imageField: wl.logoField
} : {}
};
const iconProps = {
...serverProps,
...wl.iconField ? {
imageField: wl.iconField
} : {}
};
// Vendor credit ("Technology by Intecion.com") under the nav — on by
// default, hidden with credit:false, text/url overridable.
const creditOn = wl.credit !== false;
const creditProps = wl.credit && typeof wl.credit === 'object' ? {
...wl.credit.text ? {
text: wl.credit.text
} : {},
...wl.credit.url ? {
url: wl.credit.url
} : {}
} : {};
config.admin = {
...config.admin ?? {},
components: {
...config.admin?.components ?? {},
graphics: {
...config.admin?.components?.graphics ?? {},
Icon: {
path: '@intecion/ipal-kit/admin#AdminIcon',
serverProps: iconProps
},
Logo: {
path: '@intecion/ipal-kit/admin#AdminLogo',
serverProps: logoProps
}
},
...creditOn ? {
afterLogin: [
...config.admin?.components?.afterLogin ?? [],
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: {
...creditProps,
variant: 'login'
}
}
],
afterNavLinks: [
...config.admin?.components?.afterNavLinks ?? [],
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: {
...creditProps,
variant: 'nav'
}
}
]
} : {}
},
...wl.titleSuffix ? {
meta: {
...config.admin?.meta ?? {},
titleSuffix: wl.titleSuffix
}
} : {}
};
}
// --- i18n ---
config.localization = buildLocalizationConfig(options.i18n);
+1 -1
View File
File diff suppressed because one or more lines are too long
+55 -1
View File
@@ -1,4 +1,15 @@
import type { Field } from 'payload';
import type { Field, Plugin } from 'payload';
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
* so the plugin never imports the optional peer itself.
*/
export type TotpPluginFactory = (options: {
collection: string;
forceSetup: boolean;
totp: {
issuer: string;
};
}) => Plugin;
import type { AccessOption } from './modules/access/types.js';
import type { ContentOption } from './modules/content/types.js';
import type { FormsOption } from './modules/forms/types.js';
@@ -71,5 +82,48 @@ export type IpalOptions = {
collectionSlug?: string;
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string;
/**
* The 2FA plugin factory, INJECTED from the project:
* `import { payloadTotp } from '@clocklimited/payload-2fa'`. Strongly
* recommended — injecting it (the same pattern as NextResponse /
* revalidatePath) means the plugin never dynamically imports the
* optional peer, which Next can fail to bundle into the server chunks
* ("Cannot find module '@clocklimited/payload-2fa'" at runtime, even on
* public frontend pages). If omitted, the plugin falls back to a dynamic
* import and you MUST add '@clocklimited/payload-2fa' to
* serverExternalPackages in next.config. See docs/security.md.
*/
plugin?: TotpPluginFactory;
} | false;
/**
* White-label the admin panel: show the CLIENT's brand (logo + name) in the
* admin — login screen and nav — pulled from SiteSettings, set by the editor
* in the panel (no brand hardcoded in code). `true` wires it with defaults
* (SiteSettings `logo`/`favicon`/`siteName`); the object form overrides the
* global slug, field names, or the browser-tab title suffix.
*
* Injects admin.components.graphics.Logo/Icon pointing at
* `@intecion/ipal-kit/admin`. After enabling, run `pnpm generate:importmap`
* so Payload can resolve the components. See docs/white-label.md.
*/
whiteLabel?: {
/**
* Vendor credit ("Technology by Intecion.com") at the bottom of the
* admin nav. Default on; `false` hides it, or override text/url.
*/
credit?: {
text?: string;
url?: string;
} | boolean;
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string;
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string;
/** Field with the site name. Default 'siteName'. */
nameField?: string;
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string;
/** Static browser-tab title suffix (e.g. ' · Acme Admin'). */
titleSuffix?: string;
} | boolean;
};
+1 -1
View File
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -125,11 +125,13 @@ export default buildConfig({
| turnstile | Cloudflare Turnstile (widget + verify) | [turnstile.md](./turnstile.md) |
| email | Wysyłka: SMTP z panelu lub Microsoft Graph (M365) | [email.md](./email.md) |
| forms | Form-builder + submitForm + useForm/useContactForm (logika klienta) | [forms.md](./forms.md) |
| analytics | GA4 / GTM spięte z Consent Mode | [analytics.md](./analytics.md) |
| analytics | GA4 / GTM spięte z Consent Mode, pushDataLayer | [analytics.md](./analytics.md) |
| gtm-meta-pixel | Konfiguracja GTM + Meta Pixel krok po kroku (pod ten stack) | [gtm-meta-pixel.md](./gtm-meta-pixel.md) |
| slug | Auto-slug z tytułu, per locale | [slug.md](./slug.md) |
| notifications | Teksty wyników akcji (formularz) per język | [notifications.md](./notifications.md) |
| storage | Media na Cloudflare R2 (offload z .env) | [storage.md](./storage.md) |
| security | Nagłówki bezpieczeństwa HTTP (HSTS, X-Frame...) | [security.md](./security.md) |
| white-label | Branding panelu admina (logo + nazwa z SiteSettings) | [white-label.md](./white-label.md) |
| content | Blog/archiwa: kolekcje pod stroną-archiwum, listing, paginacja, redirecty (resolveRedirect) | [content.md](./content.md) |
Nowy projekt krok po kroku: [getting-started.md](./getting-started.md)
+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)
+3 -1
View File
@@ -210,7 +210,7 @@ Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md.
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
@@ -252,6 +252,8 @@ Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-ki
| Walidacja ENV na starcie (assertEnv) | `env.md` |
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
+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) |
+24 -6
View File
@@ -258,23 +258,41 @@ pnpm add @clocklimited/[email protected]
Uwaga: pakiet nie ma jeszcze stabilnego 3.0.0 — użyj konkretnej wersji beta
(albo `^3.0.0-0`, żeby dopuścić prereleasy). Sam `^3.0.0` da błąd
ERR_PNPM_NO_MATCHING_VERSION.
To PEER dependency — ipal-kit importuje ją dynamicznie tylko gdy 2FA włączone
(domyślnie). Bez niej i z włączonym 2FA plugin rzuci jasny błąd.
### Konfiguracja (payload.config.ts)
### Konfiguracja (payload.config.ts) — WSTRZYKNIJ plugin (zalecane)
```ts
import { payloadTotp } from '@clocklimited/payload-2fa'
ipalKit({
i18n: i18nConfig,
twoFactor: {
issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator (Google Auth itp.)
// collectionSlug: 'users', // domyślnie 'users'
issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator
plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego
// collectionSlug: 'users',
},
})
```
**Dlaczego `plugin: payloadTotp` (wstrzyknięcie):** to ten sam wzorzec co
`NextResponse`/`revalidatePath` — projekt podaje peer-dep, plugin go NIE
importuje. Bez tego plugin robi dynamiczny import, którego **Next potrafi nie
wbundlować** do server chunks → błąd runtime **„Cannot find module
'@clocklimited/payload-2fa'"** lecący nawet na publicznych stronach frontu.
Wstrzyknięcie eliminuje ten problem u źródła.
**Jeśli NIE wstrzykujesz** (zostawiasz dynamiczny import) — MUSISZ dodać pakiet do
`serverExternalPackages` w `next.config`, żeby Next nie próbował go bundlować:
```ts
// next.config.ts
const nextConfig = {
serverExternalPackages: ['@clocklimited/payload-2fa'],
}
```
Plugin ustawia `forceSetup: true` — każdy użytkownik MUSI skonfigurować TOTP po
zalogowaniu (przekierowanie na setup). Nie ma opcji „włącz/wyłącz" dla użytkownika.
zalogowaniu. Nie ma opcji „włącz/wyłącz" dla użytkownika.
### Wyłączenie (ODRADZANE)
+91
View File
@@ -0,0 +1,91 @@
# white-label — branding panelu admina z panelu
Panel admina pokazuje **markę klienta** (logo + nazwa) na ekranie logowania i w
nawigacji, pobraną z **SiteSettings** — czyli ustawioną przez redaktora w panelu,
nie zahardkodowaną w kodzie. Każdy klient loguje się do „swojego" panelu.
Powiązane: [security.md](./security.md) (adminRoute), [accessibility.md](./accessibility.md).
## Włączenie
```ts
// payload.config.ts
ipalKit({
i18n: { /* … */ },
whiteLabel: true,
})
```
`true` wpina branding z domyślnych pól SiteSettings: `logo` (logo panelu),
`favicon` (mała ikona nawigacji), `siteName` (nazwa / fallback tekstowy).
> **Po włączeniu uruchom `pnpm generate:importmap`.** Plugin wstrzykuje
> `admin.components.graphics.Logo/Icon` wskazujące na `@intecion/ipal-kit/admin`;
> Payload musi zregenerować import map, żeby je znaleźć. Bez tego kroku panel
> użyje domyślnego logo Payload.
## Konfiguracja (opcjonalnie)
```ts
whiteLabel: {
settingsSlug: 'site-settings', // globalny slug ustawień
nameField: 'siteName', // pole z nazwą
logoField: 'logo', // upload na logo (login + nav)
iconField: 'favicon', // upload na ikonę nav
titleSuffix: ' · Acme Admin', // sufiks tytułu w karcie przeglądarki (statyczny)
credit: true, // kredyt dostawcy pod nawigacją (domyślnie on)
}
```
## Kredyt dostawcy — „Technology supported by Intecion.com"
Dyskretny kredyt **„Technology supported by Intecion.com"** (link do
`https://intecion.com`) pojawia się w **dwóch miejscach**:
- **pod nawigacją** panelu (`afterNavLinks`, wariant `nav` — wyrównany do lewej),
- **na dole ekranu logowania** (`afterLogin`, wariant `login` — wyśrodkowany).
To kredyt DOSTAWCY technologii (Intecion dostarcza framework ipal-kit) — marka
klienta nadal rządzi logiem i nazwą; to tylko linijka „kto wspiera technologię".
Domyślnie włączony z `whiteLabel`. Sterowanie:
```ts
whiteLabel: { credit: false } // ukryj (oba miejsca)
whiteLabel: { credit: { text: 'Powered by Intecion', url: 'https://intecion.com' } } // własny tekst/url
```
## Logo na ekranie logowania
`AdminLogo` to DUŻE logo na ekranie logowania (Payload używa `graphics.Icon` do
małej ikony w nawigacji). Renderuje się sporo większe (`maxHeight 120 / maxWidth
420`), żeby marka klienta była wyraźna przy logowaniu. Mała ikona nav to `favicon`
przez `AdminIcon`.
## Jak to działa
- `AdminLogo` / `AdminIcon` to **Server Components** czytające SiteSettings przy
renderze (przez alias `@payload-config`, uniwersalny w projektach Payload 3 +
Next).
- **Bezpieczne fallbacki:** gdy baza jest niedostępna (ekran logowania zanim
wstanie DB, build bez bazy) albo logo nie jest ustawione → komponent pokazuje
nazwę (`siteName`), a gdy i jej brak → `null` (domyślne Payload). Nigdy nie
rzuca, nie blokuje panelu.
- **A0:** żadnej marki klienta w kodzie. Logo i nazwa pochodzą z panelu; jak nic
nie ustawiono, nic nie jest narzucane.
## Granice
- **`titleSuffix` jest statyczny** — tytuł karty przeglądarki ustawia się w
configu (build-time), więc nie czyta się z bazy. Logo i ikona (to, co widać) są
dynamiczne z SiteSettings; sufiks tytułu podajesz w opcji, jeśli chcesz.
- **To branding panelu, nie front** — wygląd strony publicznej robisz jak dotąd
(bloki, style projektu). White-label dotyczy wyłącznie panelu admina.
- Ścieżkę panelu (`/admin → /its`) ustawiasz osobno przez `adminRoute` — patrz
[security.md](./security.md).
## Checklist
- [ ] `ipalKit({ whiteLabel: true })`
- [ ] Redaktor wgrał `logo` i `favicon` w SiteSettings (+ `siteName`)
- [ ] `pnpm generate:importmap`
- [ ] Restart dev / rebuild → panel pokazuje markę klienta na loginie i w nav
+30 -31
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.0",
"version": "1.7.4",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -33,13 +33,17 @@
"import": "./dist/exports/next-middleware.js",
"types": "./dist/exports/next-middleware.d.ts",
"default": "./dist/exports/next-middleware.js"
},
"./admin": {
"import": "./dist/exports/admin.js",
"types": "./dist/exports/admin.d.ts",
"default": "./dist/exports/admin.js"
}
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist",
"docs"
"dist"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
@@ -60,59 +64,54 @@
"test:int": "vitest"
},
"dependencies": {
"@payloadcms/storage-s3": "^3.88.0",
"lucide-react": "^0.400.0",
"nodemailer": "^8.0.1",
"server-only": "^0.0.1",
"slugify": "^1.6.6"
},
"peerDependencies": {
"@clocklimited/payload-2fa": "^3.0.0",
"@payloadcms/next": "^3.88.0",
"@payloadcms/plugin-form-builder": "^3.88.0",
"@payloadcms/plugin-seo": "^3.88.0",
"@payloadcms/ui": "^3.88.0",
"@payloadcms/plugin-form-builder": "^3.90.2",
"@payloadcms/plugin-seo": "^3.90.2",
"next": ">=15",
"payload": "^3.88.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"payload": "^3.90.2",
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@payloadcms/db-postgres": "3.88.0",
"@payloadcms/db-sqlite": "3.88.0",
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/db-sqlite": "3.90.2",
"@payloadcms/eslint-config": "3.28.0",
"@payloadcms/next": "3.88.0",
"@payloadcms/plugin-form-builder": "3.88.0",
"@payloadcms/plugin-seo": "3.88.0",
"@payloadcms/richtext-lexical": "3.88.0",
"@payloadcms/ui": "3.88.0",
"@playwright/test": "1.58.2",
"@payloadcms/next": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/ui": "3.90.2",
"@playwright/test": "1.64.0",
"@swc-node/register": "1.10.9",
"@swc/cli": "0.6.0",
"@types/node": "22.19.9",
"@types/node": "22.20.5",
"@types/nodemailer": "^8.0.1",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"copyfiles": "2.4.1",
"cross-env": "^7.0.3",
"eslint": "^9.23.0",
"eslint-config-next": "16.2.6",
"eslint-config-next": "16.4.0",
"graphql": "^16.8.1",
"mongodb-memory-server": "10.1.4",
"next": "16.2.6",
"next": "16.4.0",
"open": "^10.1.0",
"payload": "3.88.0",
"payload": "3.90.2",
"prettier": "^3.4.2",
"qs-esm": "8.0.1",
"react": "19.2.6",
"react-dom": "19.2.6",
"react": "19.3.0",
"react-dom": "19.3.0",
"rimraf": "3.0.2",
"sharp": "0.34.2",
"sharp": "0.34.5",
"sort-package-json": "^2.10.0",
"typescript": "5.7.3",
"typescript": "5.9.3",
"vite-tsconfig-paths": "6.0.5",
"vitest": "4.0.18"
"vitest": "5.0.4"
},
"engines": {
"node": "^18.20.2 || >=20.9.0",
+8
View File
@@ -0,0 +1,8 @@
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
+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 })
}
+141
View File
@@ -0,0 +1,141 @@
import { getPayload } from 'payload'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
* set by the editor in the panel — not hardcoded per project. Wired
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
*/
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** Field holding the site name. Default 'siteName'. */
nameField?: string
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
}
type MediaLike = { url?: null | string } | null | undefined
async function loadBranding(
settingsSlug: string,
nameField: string,
imageField: string,
): Promise<{ name: null | string; url: null | string }> {
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config'
const mod = (await import(spec)) as { default: unknown }
const payload = await getPayload({ config: mod.default as never })
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
})) as Record<string, unknown>
const name = typeof settings[nameField] === 'string' ? (settings[nameField]) : null
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
return { name, url }
} catch {
return { name: null, url: null }
}
}
/**
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
* falls back to `siteName` text. Sized generously for the login screen.
*/
export async function AdminLogo(props: BrandingProps = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
if (url) {
return (
<img
alt={name ?? ''}
src={url}
style={{ height: 'auto', maxHeight: 120, maxWidth: 420, width: 'auto' }}
/>
)
}
if (name) {return <div style={{ fontSize: '2rem', fontWeight: 600 }}>{name}</div>}
return null // nothing configured → Payload's default
}
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */
export async function AdminIcon(props: BrandingProps = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
if (url) {
return (
<img
alt={name ?? ''}
src={url}
style={{ height: 'auto', maxHeight: 28, maxWidth: 28, width: 'auto' }}
/>
)
}
if (name) {return <div style={{ fontWeight: 700 }}>{name.slice(0, 2).toUpperCase()}</div>}
return null
}
/**
* Discreet vendor credit: "Technology supported by Intecion.com". This is the
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
* data — a sensible default here is fine and A0-safe. The client's own brand
* still owns the logo/name; this is a small line stating who supports the tech.
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
*
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
* (login screen footer). `variant` adjusts placement:
* - 'nav' → left-aligned line under the nav links
* - 'login' → centered line below the login form
*/
export function IntecionCredit(
props: { text?: string; url?: string; variant?: 'login' | 'nav' } = {},
) {
const {
text = 'Technology supported by Intecion.com',
url = 'https://intecion.com',
variant = 'nav',
} = props
const style =
variant === 'login'
? {
color: 'inherit' as const,
display: 'block',
fontSize: '0.75rem',
marginTop: '2rem',
opacity: 0.6,
padding: '0.5rem',
textAlign: 'center' as const,
textDecoration: 'none',
}
: {
color: 'inherit' as const,
display: 'block',
fontSize: '0.75rem',
opacity: 0.6,
padding: '0.75rem 1rem',
textDecoration: 'none',
}
return (
<a href={url} rel="noopener noreferrer" style={style} target="_blank">
{text}
</a>
)
}
+1
View File
@@ -0,0 +1 @@
export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js'
+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 = {},
+95 -26
View File
@@ -1,6 +1,6 @@
import type { Config, Plugin } from 'payload'
import type { IpalOptions } from './types.js'
import type { IpalOptions, TotpPluginFactory } from './types.js'
import { buildCookieSettings } from './globals/CookieSettings/index.js'
import { buildNotifications } from './globals/Notifications/index.js'
@@ -71,37 +71,106 @@ export const ipalKit = (options: IpalOptions): Plugin => {
'opt out (discouraged).',
)
}
try {
// Dynamic specifier via a variable so TS doesn't try to resolve this
// optional peer dependency at build time (it isn't in the plugin's own
// node_modules). Avoids TS2307 without @ts-expect-error; the module
// exists at runtime in projects that installed it.
// @ts-ignore
const mod = (await import('@clocklimited/payload-2fa')) as {
payloadTotp?: (opts: Record<string, unknown>) => Plugin
totpPlugin?: (opts: Record<string, unknown>) => Plugin
}
// The package exports `payloadTotp`; older/other builds may use
// `totpPlugin`. Accept either so a rename doesn't break us.
const totp = mod.payloadTotp ?? mod.totpPlugin
if (typeof totp !== 'function') {
// Prefer the INJECTED plugin factory (recommended): the project imports
// payloadTotp from @clocklimited/payload-2fa and passes it in. Then the
// plugin never imports the optional peer itself — no dynamic import, so
// Next can't fail to bundle it (the cause of "Cannot find module
// '@clocklimited/payload-2fa'" crashing even public frontend pages).
let totp: TotpPluginFactory | undefined = tf.plugin
if (!totp) {
// Fallback: dynamic import. Variable specifier dodges the plugin's own
// TS2307, but Next may NOT trace it into the server bundle — projects
// using this path MUST add '@clocklimited/payload-2fa' to
// serverExternalPackages in next.config (see docs/security.md).
try {
const pkg = '@clocklimited/payload-2fa'
const mod = (await import(pkg)) as {
payloadTotp?: TotpPluginFactory
totpPlugin?: TotpPluginFactory
}
totp = mod.payloadTotp ?? mod.totpPlugin
} catch (err) {
throw new Error(
'expected export payloadTotp (or totpPlugin) to be a function — ' +
'check the installed @clocklimited/payload-2fa version',
'[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' +
'Best fix — inject it: `import { payloadTotp } from "@clocklimited/payload-2fa"` ' +
'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' +
"'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set " +
`twoFactor: false to opt out (discouraged). Original error: ${String(err)}`,
)
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
} catch (err) {
}
if (typeof totp !== 'function') {
throw new Error(
'[ipal] 2FA is enforced but @clocklimited/payload-2fa is not installed. ' +
'Run: pnpm add @clocklimited/payload-2fa — or set twoFactor: false to ' +
`opt out (discouraged). Original error: ${String(err)}`,
'[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' +
'injected `plugin` or the installed @clocklimited/payload-2fa version.',
)
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
}
// --- white-label admin branding ---
// Inject admin.components.graphics.Logo/Icon pointing at the plugin's
// /admin export. The components read SiteSettings at render, so each client
// sees their own brand from the panel (no brand in code). Project must run
// `pnpm generate:importmap` so Payload resolves the component paths.
if (options.whiteLabel) {
const wl = options.whiteLabel === true ? {} : options.whiteLabel
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
// Vendor credit ("Technology by Intecion.com") under the nav — on by
// default, hidden with credit:false, text/url overridable.
const creditOn = wl.credit !== false
const creditProps =
wl.credit && typeof wl.credit === 'object'
? {
...(wl.credit.text ? { text: wl.credit.text } : {}),
...(wl.credit.url ? { url: wl.credit.url } : {}),
}
: {}
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
graphics: {
...(config.admin?.components?.graphics ?? {}),
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
},
...(creditOn
? {
afterLogin: [
...(config.admin?.components?.afterLogin ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'login' },
},
],
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'nav' },
},
],
}
: {}),
},
...(wl.titleSuffix
? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }
: {}),
}
}
// --- i18n ---
+58 -1
View File
@@ -1,5 +1,14 @@
import type { Field } from 'payload'
import type { Field, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
* so the plugin never imports the optional peer itself.
*/
export type TotpPluginFactory = (options: {
collection: string
forceSetup: boolean
totp: { issuer: string }
}) => Plugin
import type { AccessOption } from './modules/access/types.js'
import type { ContentOption } from './modules/content/types.js'
import type { FormsOption } from './modules/forms/types.js'
@@ -84,6 +93,54 @@ export type IpalOptions = {
collectionSlug?: string
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string
/**
* The 2FA plugin factory, INJECTED from the project:
* `import { payloadTotp } from '@clocklimited/payload-2fa'`. Strongly
* recommended — injecting it (the same pattern as NextResponse /
* revalidatePath) means the plugin never dynamically imports the
* optional peer, which Next can fail to bundle into the server chunks
* ("Cannot find module '@clocklimited/payload-2fa'" at runtime, even on
* public frontend pages). If omitted, the plugin falls back to a dynamic
* import and you MUST add '@clocklimited/payload-2fa' to
* serverExternalPackages in next.config. See docs/security.md.
*/
plugin?: TotpPluginFactory
}
| false
/**
* White-label the admin panel: show the CLIENT's brand (logo + name) in the
* admin — login screen and nav — pulled from SiteSettings, set by the editor
* in the panel (no brand hardcoded in code). `true` wires it with defaults
* (SiteSettings `logo`/`favicon`/`siteName`); the object form overrides the
* global slug, field names, or the browser-tab title suffix.
*
* Injects admin.components.graphics.Logo/Icon pointing at
* `@intecion/ipal-kit/admin`. After enabling, run `pnpm generate:importmap`
* so Payload can resolve the components. See docs/white-label.md.
*/
whiteLabel?:
| {
/**
* Vendor credit ("Technology by Intecion.com") at the bottom of the
* admin nav. Default on; `false` hides it, or override text/url.
*/
credit?:
| {
text?: string
url?: string
}
| boolean
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string
/** Field with the site name. Default 'siteName'. */
nameField?: string
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Static browser-tab title suffix (e.g. ' · Acme Admin'). */
titleSuffix?: string
}
| boolean
}