diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index c9cce3a..57c7db0 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -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'; diff --git a/dist/exports/client.js b/dist/exports/client.js index 7c72362..566c0b5 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -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'; diff --git a/dist/exports/client.js.map b/dist/exports/client.js.map index 89687e5..6c16486 100644 --- a/dist/exports/client.js.map +++ b/dist/exports/client.js.map @@ -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"} \ No newline at end of file +{"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"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index 4ff67bd..12a59df 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -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'; diff --git a/dist/index.js b/dist/index.js index 2dd1ebb..4ebd7bb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -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 diff --git a/dist/index.js.map b/dist/index.js.map index 38cdb84..807a1e2 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\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'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport {\n buildCrossLocaleFieldSync,\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","createMcpRoute","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,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yBAAwB;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\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'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport {\n buildCrossLocaleFieldSync,\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","createMcpRoute","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","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;AAC/B,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,oBAAoB,QACf,yBAAwB;AAC/B,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file diff --git a/dist/modules/accessibility/AccessibilityWidget.d.ts b/dist/modules/accessibility/AccessibilityWidget.d.ts index 3ab6816..5668d42 100644 --- a/dist/modules/accessibility/AccessibilityWidget.d.ts +++ b/dist/modules/accessibility/AccessibilityWidget.d.ts @@ -34,6 +34,16 @@ export type A11yClassNames = { * CookieBanner). Wrap the app in first. * * + * + * 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 = { + * pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … }, + * de: { title: 'Barrierefreiheit', … }, + * } + * */ export declare function AccessibilityWidget({ classNames, texts, }: { classNames?: A11yClassNames; diff --git a/dist/modules/accessibility/AccessibilityWidget.js b/dist/modules/accessibility/AccessibilityWidget.js index cd5ce1b..e3d772b 100644 --- a/dist/modules/accessibility/AccessibilityWidget.js +++ b/dist/modules/accessibility/AccessibilityWidget.js @@ -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 first. * * + * + * 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 = { + * pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … }, + * de: { title: 'Barrierefreiheit', … }, + * } + * */ export function AccessibilityWidget({ classNames, texts }) { const { reset, set, state } = useAccessibility(); const [open, setOpen] = useState(false); diff --git a/dist/modules/accessibility/AccessibilityWidget.js.map b/dist/modules/accessibility/AccessibilityWidget.js.map index ea03d56..5c5a008 100644 --- a/dist/modules/accessibility/AccessibilityWidget.js.map +++ b/dist/modules/accessibility/AccessibilityWidget.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/accessibility/AccessibilityWidget.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\nimport type { A11yState } from './state.js'\n\nimport { useAccessibility } from './AccessibilityProvider.js'\n\nexport type A11yTexts = {\n bigCursor?: string\n close?: string\n contrast?: string\n contrastHigh?: string\n contrastInverted?: string\n grayscale?: string\n lineHeight?: string\n open?: string\n readableFont?: string\n reduceMotion?: string\n reset?: string\n textSize?: string\n title?: string\n underlineLinks?: string\n}\n\nconst DEFAULT_TEXTS: Required = {\n bigCursor: 'Duży kursor',\n close: 'Zamknij',\n contrast: 'Kontrast',\n contrastHigh: 'Wysoki',\n contrastInverted: 'Odwrócony',\n grayscale: 'Skala szarości',\n lineHeight: 'Odstęp między liniami',\n open: 'Otwórz panel dostępności',\n readableFont: 'Czytelna czcionka',\n reduceMotion: 'Wyłącz animacje',\n reset: 'Resetuj',\n textSize: 'Rozmiar tekstu',\n title: 'Dostępność',\n underlineLinks: 'Podkreśl linki',\n}\n\nexport type A11yClassNames = {\n active?: string\n button?: string\n closeButton?: string\n control?: string\n label?: string\n panel?: string\n resetButton?: string\n row?: string\n}\n\n/**\n * Accessibility toolbar: a floating button that opens a panel of options (text\n * size, line height, contrast, grayscale, underline links, readable font, reduce\n * motion, big cursor). Choices persist in a cookie and apply as data-attributes\n * on (the project's CSS styles them).\n *\n * Unstyled by default — pass classNames to match the project's design (like\n * CookieBanner). Wrap the app in first.\n *\n * \n */\nexport function AccessibilityWidget({\n classNames,\n texts,\n}: {\n classNames?: A11yClassNames\n texts?: A11yTexts\n}) {\n const { reset, set, state } = useAccessibility()\n const [open, setOpen] = useState(false)\n const t = { ...DEFAULT_TEXTS, ...texts }\n const cn = classNames ?? {}\n\n const toggle = (key: K) => set(key, !state[key] as A11yState[K])\n\n const isActive = (on: boolean) => (on ? (cn.active ?? '') : '')\n\n return (\n <>\n setOpen((o) => !o)}\n type=\"button\"\n >\n {/* Project can style/replace via CSS; simple glyph fallback. */}\n ♿\n \n\n {open && (\n
\n
\n {t.textSize}\n
\n {[0, 1, 2, 3].map((n) => (\n set('textSize', n as A11yState['textSize'])}\n type=\"button\"\n >\n A{n > 0 ? '+'.repeat(n) : ''}\n \n ))}\n
\n
\n\n
\n {t.lineHeight}\n
\n {[0, 1, 2].map((n) => (\n set('lineHeight', n as A11yState['lineHeight'])}\n type=\"button\"\n >\n {n === 0 ? '—' : '≡'.repeat(n)}\n \n ))}\n
\n
\n\n
\n {t.contrast}\n
\n set('contrast', state.contrast === 'high' ? 'default' : 'high')}\n type=\"button\"\n >\n {t.contrastHigh}\n \n \n set('contrast', state.contrast === 'inverted' ? 'default' : 'inverted')\n }\n type=\"button\"\n >\n {t.contrastInverted}\n \n
\n
\n\n {(\n [\n ['grayscale', t.grayscale],\n ['underlineLinks', t.underlineLinks],\n ['readableFont', t.readableFont],\n ['reduceMotion', t.reduceMotion],\n ['bigCursor', t.bigCursor],\n ] as Array<[keyof A11yState, string]>\n ).map(([key, label]) => (\n
\n {label}\n toggle(key)}\n type=\"button\"\n >\n {state[key] ? 'ON' : 'OFF'}\n \n
\n ))}\n\n \n \n
\n )}\n \n )\n}\n"],"names":["useState","useAccessibility","DEFAULT_TEXTS","bigCursor","close","contrast","contrastHigh","contrastInverted","grayscale","lineHeight","open","readableFont","reduceMotion","reset","textSize","title","underlineLinks","AccessibilityWidget","classNames","texts","set","state","setOpen","t","cn","toggle","key","isActive","on","active","button","aria-expanded","aria-label","className","onClick","o","type","span","aria-hidden","div","panel","role","row","label","control","map","n","repeat","aria-pressed","Boolean","resetButton","closeButton"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAIhC,SAASC,gBAAgB,QAAQ,6BAA4B;AAmB7D,MAAMC,gBAAqC;IACzCC,WAAW;IACXC,OAAO;IACPC,UAAU;IACVC,cAAc;IACdC,kBAAkB;IAClBC,WAAW;IACXC,YAAY;IACZC,MAAM;IACNC,cAAc;IACdC,cAAc;IACdC,OAAO;IACPC,UAAU;IACVC,OAAO;IACPC,gBAAgB;AAClB;AAaA;;;;;;;;;;CAUC,GACD,OAAO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,GAAGoB,OAAO,IAAI,GAAG,CAAC,EAAEjB,SAASsB,QAAQ5B,KAAK,CAACK,IAAI,IAAI;oCACjEQ,SAAS,IAAMT,OAAOC;oCACtBU,MAAK;8CAEJf,KAAK,CAACK,IAAI,GAAG,OAAO;;;2BARIA;kCAa/B,KAACI;wBAAOG,WAAWT,GAAG0B,WAAW;wBAAEhB,SAASrB;wBAAOuB,MAAK;kCACrDb,EAAEV,KAAK;;kCAEV,KAACiB;wBAAOG,WAAWT,GAAG2B,WAAW;wBAAEjB,SAAS,IAAMZ,QAAQ;wBAAQc,MAAK;kCACpEb,EAAEnB,KAAK;;;;;;AAMpB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/accessibility/AccessibilityWidget.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\nimport type { A11yState } from './state.js'\n\nimport { useAccessibility } from './AccessibilityProvider.js'\n\nexport type A11yTexts = {\n bigCursor?: string\n close?: string\n contrast?: string\n contrastHigh?: string\n contrastInverted?: string\n grayscale?: string\n lineHeight?: string\n open?: string\n readableFont?: string\n reduceMotion?: string\n reset?: string\n textSize?: string\n title?: string\n underlineLinks?: string\n}\n\n/**\n * English defaults. The widget is end-user facing and multilingual projects run\n * in many locales, so the plugin ships a neutral English baseline — NOT Polish.\n * Localize by passing `texts` for the active locale (see the component doc).\n */\nconst DEFAULT_TEXTS: Required = {\n bigCursor: 'Large cursor',\n close: 'Close',\n contrast: 'Contrast',\n contrastHigh: 'High',\n contrastInverted: 'Inverted',\n grayscale: 'Grayscale',\n lineHeight: 'Line spacing',\n open: 'Open accessibility panel',\n readableFont: 'Readable font',\n reduceMotion: 'Reduce motion',\n reset: 'Reset',\n textSize: 'Text size',\n title: 'Accessibility',\n underlineLinks: 'Underline links',\n}\n\nexport type A11yClassNames = {\n active?: string\n button?: string\n closeButton?: string\n control?: string\n label?: string\n panel?: string\n resetButton?: string\n row?: string\n}\n\n/**\n * Accessibility toolbar: a floating button that opens a panel of options (text\n * size, line height, contrast, grayscale, underline links, readable font, reduce\n * motion, big cursor). Choices persist in a cookie and apply as data-attributes\n * on (the project's CSS styles them).\n *\n * Unstyled by default — pass classNames to match the project's design (like\n * CookieBanner). Wrap the app in first.\n *\n * \n *\n * Labels default to English; localize per locale by passing `texts` for the\n * active language. Keep the translations in the project (or a localized global)\n * and pass the active locale's set — the plugin stays content-agnostic:\n *\n * const A11Y: Record = {\n * pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … },\n * de: { title: 'Barrierefreiheit', … },\n * }\n * \n */\nexport function AccessibilityWidget({\n classNames,\n texts,\n}: {\n classNames?: A11yClassNames\n texts?: A11yTexts\n}) {\n const { reset, set, state } = useAccessibility()\n const [open, setOpen] = useState(false)\n const t = { ...DEFAULT_TEXTS, ...texts }\n const cn = classNames ?? {}\n\n const toggle = (key: K) => set(key, !state[key] as A11yState[K])\n\n const isActive = (on: boolean) => (on ? (cn.active ?? '') : '')\n\n return (\n <>\n setOpen((o) => !o)}\n type=\"button\"\n >\n {/* Project can style/replace via CSS; simple glyph fallback. */}\n ♿\n \n\n {open && (\n
\n
\n {t.textSize}\n
\n {[0, 1, 2, 3].map((n) => (\n set('textSize', n as A11yState['textSize'])}\n type=\"button\"\n >\n A{n > 0 ? '+'.repeat(n) : ''}\n \n ))}\n
\n
\n\n
\n {t.lineHeight}\n
\n {[0, 1, 2].map((n) => (\n set('lineHeight', n as A11yState['lineHeight'])}\n type=\"button\"\n >\n {n === 0 ? '—' : '≡'.repeat(n)}\n \n ))}\n
\n
\n\n
\n {t.contrast}\n
\n set('contrast', state.contrast === 'high' ? 'default' : 'high')}\n type=\"button\"\n >\n {t.contrastHigh}\n \n \n set('contrast', state.contrast === 'inverted' ? 'default' : 'inverted')\n }\n type=\"button\"\n >\n {t.contrastInverted}\n \n
\n
\n\n {(\n [\n ['grayscale', t.grayscale],\n ['underlineLinks', t.underlineLinks],\n ['readableFont', t.readableFont],\n ['reduceMotion', t.reduceMotion],\n ['bigCursor', t.bigCursor],\n ] as Array<[keyof A11yState, string]>\n ).map(([key, label]) => (\n
\n {label}\n toggle(key)}\n type=\"button\"\n >\n {state[key] ? 'ON' : 'OFF'}\n \n
\n ))}\n\n \n \n
\n )}\n \n )\n}\n"],"names":["useState","useAccessibility","DEFAULT_TEXTS","bigCursor","close","contrast","contrastHigh","contrastInverted","grayscale","lineHeight","open","readableFont","reduceMotion","reset","textSize","title","underlineLinks","AccessibilityWidget","classNames","texts","set","state","setOpen","t","cn","toggle","key","isActive","on","active","button","aria-expanded","aria-label","className","onClick","o","type","span","aria-hidden","div","panel","role","row","label","control","map","n","repeat","aria-pressed","Boolean","resetButton","closeButton"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAIhC,SAASC,gBAAgB,QAAQ,6BAA4B;AAmB7D;;;;CAIC,GACD,MAAMC,gBAAqC;IACzCC,WAAW;IACXC,OAAO;IACPC,UAAU;IACVC,cAAc;IACdC,kBAAkB;IAClBC,WAAW;IACXC,YAAY;IACZC,MAAM;IACNC,cAAc;IACdC,cAAc;IACdC,OAAO;IACPC,UAAU;IACVC,OAAO;IACPC,gBAAgB;AAClB;AAaA;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,oBAAoB,EAClCC,UAAU,EACVC,KAAK,EAIN;IACC,MAAM,EAAEN,KAAK,EAAEO,GAAG,EAAEC,KAAK,EAAE,GAAGpB;IAC9B,MAAM,CAACS,MAAMY,QAAQ,GAAGtB,SAAS;IACjC,MAAMuB,IAAI;QAAE,GAAGrB,aAAa;QAAE,GAAGiB,KAAK;IAAC;IACvC,MAAMK,KAAKN,cAAc,CAAC;IAE1B,MAAMO,SAAS,CAA4BC,MAAWN,IAAIM,KAAK,CAACL,KAAK,CAACK,IAAI;IAE1E,MAAMC,WAAW,CAACC,KAAiBA,KAAMJ,GAAGK,MAAM,IAAI,KAAM;IAE5D,qBACE;;0BACE,KAACC;gBACCC,iBAAerB;gBACfsB,cAAYT,EAAEb,IAAI;gBA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 100644 --- a/dist/modules/analytics/client.d.ts +++ b/dist/modules/analytics/client.d.ts @@ -1 +1,2 @@ export { Analytics } from './Analytics.js'; +export { pushDataLayer } from './pushDataLayer.js'; diff --git a/dist/modules/analytics/client.js b/dist/modules/analytics/client.js index 8b711fa..292610a 100644 --- a/dist/modules/analytics/client.js +++ b/dist/modules/analytics/client.js @@ -1,4 +1,5 @@ 'use client'; export { Analytics } from './Analytics.js'; +export { pushDataLayer } from './pushDataLayer.js'; //# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/dist/modules/analytics/client.js.map b/dist/modules/analytics/client.js.map index 734ed82..42b6d7d 100644 --- a/dist/modules/analytics/client.js.map +++ b/dist/modules/analytics/client.js.map @@ -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"} \ No newline at end of file +{"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"} \ No newline at end of file diff --git a/dist/modules/analytics/pushDataLayer.d.ts b/dist/modules/analytics/pushDataLayer.d.ts new file mode 100644 index 0000000..951deb6 --- /dev/null +++ b/dist/modules/analytics/pushDataLayer.d.ts @@ -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): void; diff --git a/dist/modules/analytics/pushDataLayer.js b/dist/modules/analytics/pushDataLayer.js new file mode 100644 index 0000000..9743d8c --- /dev/null +++ b/dist/modules/analytics/pushDataLayer.js @@ -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 \ No newline at end of file diff --git a/dist/modules/analytics/pushDataLayer.js.map b/dist/modules/analytics/pushDataLayer.js.map new file mode 100644 index 0000000..bf8e2b2 --- /dev/null +++ b/dist/modules/analytics/pushDataLayer.js.map @@ -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 = {}): 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"} \ No newline at end of file diff --git a/dist/modules/forms/formAnalytics.d.ts b/dist/modules/forms/formAnalytics.d.ts new file mode 100644 index 0000000..b7c711e --- /dev/null +++ b/dist/modules/forms/formAnalytics.d.ts @@ -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>(config: FormAnalyticsConfig): (result: { + success: boolean; +}, values: T) => void; diff --git a/dist/modules/forms/formAnalytics.js b/dist/modules/forms/formAnalytics.js new file mode 100644 index 0000000..393a276 --- /dev/null +++ b/dist/modules/forms/formAnalytics.js @@ -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 \ No newline at end of file diff --git a/dist/modules/forms/formAnalytics.js.map b/dist/modules/forms/formAnalytics.js.map new file mode 100644 index 0000000..fadb270 --- /dev/null +++ b/dist/modules/forms/formAnalytics.js.map @@ -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>(\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 = {}\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"} \ No newline at end of file diff --git a/dist/modules/forms/formAnalyticsFields.d.ts b/dist/modules/forms/formAnalyticsFields.d.ts new file mode 100644 index 0000000..da9009c --- /dev/null +++ b/dist/modules/forms/formAnalyticsFields.d.ts @@ -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[]; diff --git a/dist/modules/forms/formAnalyticsFields.js b/dist/modules/forms/formAnalyticsFields.js new file mode 100644 index 0000000..5c22c91 --- /dev/null +++ b/dist/modules/forms/formAnalyticsFields.js @@ -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 \ No newline at end of file diff --git a/dist/modules/forms/formAnalyticsFields.js.map b/dist/modules/forms/formAnalyticsFields.js.map new file mode 100644 index 0000000..1331279 --- /dev/null +++ b/dist/modules/forms/formAnalyticsFields.js.map @@ -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"} \ No newline at end of file diff --git a/dist/modules/forms/index.d.ts b/dist/modules/forms/index.d.ts index 82ca824..8fbd29c 100644 --- a/dist/modules/forms/index.d.ts +++ b/dist/modules/forms/index.d.ts @@ -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'; diff --git a/dist/modules/forms/index.js b/dist/modules/forms/index.js index 956c6e1..c7f0870 100644 --- a/dist/modules/forms/index.js +++ b/dist/modules/forms/index.js @@ -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'; diff --git a/dist/modules/forms/index.js.map b/dist/modules/forms/index.js.map index 181a08d..8246bde 100644 --- a/dist/modules/forms/index.js.map +++ b/dist/modules/forms/index.js.map @@ -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"} \ No newline at end of file +{"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"} \ No newline at end of file diff --git a/dist/modules/forms/useContactForm.d.ts b/dist/modules/forms/useContactForm.d.ts index 78ef1c3..6677f03 100644 --- a/dist/modules/forms/useContactForm.d.ts +++ b/dist/modules/forms/useContactForm.d.ts @@ -22,6 +22,14 @@ type UseContactFormOptions = { messages?: Partial>; /** 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>; - isSubmitting: boolean; - isSuccess: boolean; errorMessage: string | null; - turnstileToken: string | null; - setField: (key: K, value: ContactFormValues[K]) => void; - setValues: import("react").Dispatch>; - setErrors: import("react").Dispatch>>>; - setTurnstileToken: import("react").Dispatch>; + errors: Partial>; handleSubmit: (e?: { preventDefault?: (() => void) | undefined; } | undefined) => Promise; + isSubmitting: boolean; + isSuccess: boolean; reset: () => void; + setErrors: import("react").Dispatch>>>; + setField: (key: K, value: ContactFormValues[K]) => void; + setTurnstileToken: import("react").Dispatch>; + setValues: import("react").Dispatch>; + turnstileToken: string | null; + values: ContactFormValues; }; export {}; diff --git a/dist/modules/forms/useContactForm.js b/dist/modules/forms/useContactForm.js index 1a052f2..e1c2b7a 100644 --- a/dist/modules/forms/useContactForm.js +++ b/dist/modules/forms/useContactForm.js @@ -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 diff --git a/dist/modules/forms/useContactForm.js.map b/dist/modules/forms/useContactForm.js.map index d8cf270..6d457a0 100644 --- a/dist/modules/forms/useContactForm.js.map +++ b/dist/modules/forms/useContactForm.js.map @@ -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>\nexport type SubmitAction = FormSubmitAction\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.`). */\n messages?: Partial>\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({\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({\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"} \ No newline at end of file +{"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>\nexport type SubmitAction = FormSubmitAction\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.`). */\n messages?: Partial>\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({\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({\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"} \ No newline at end of file diff --git a/dist/modules/forms/useForm.d.ts b/dist/modules/forms/useForm.d.ts index eec804d..48b4a99 100644 --- a/dist/modules/forms/useForm.d.ts +++ b/dist/modules/forms/useForm.d.ts @@ -11,23 +11,37 @@ export type FormErrors = Partial>; * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it. */ export type FormSubmitAction = (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 = (values: T) => FormErrors; type UseFormOptions> = { + /** 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; /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */ validate?: Validator; - /** 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> = { *
…
*/ export declare function useForm>(options: UseFormOptions): { - values: T; - errors: Partial>; - isSubmitting: boolean; - isSuccess: boolean; errorMessage: string | null; - turnstileToken: string | null; - setField: (key: K, value: T[K]) => void; - setValues: import("react").Dispatch>; - setErrors: import("react").Dispatch>>>; - setTurnstileToken: import("react").Dispatch>; + errors: Partial>; handleSubmit: (e?: { preventDefault?: () => void; }) => Promise; + isSubmitting: boolean; + isSuccess: boolean; reset: () => void; + setErrors: import("react").Dispatch>>>; + setField: (key: K, value: T[K]) => void; + setTurnstileToken: import("react").Dispatch>; + setValues: import("react").Dispatch>; + turnstileToken: string | null; + values: T; }; export {}; diff --git a/dist/modules/forms/useForm.js b/dist/modules/forms/useForm.js index b503015..b26f7f6 100644 --- a/dist/modules/forms/useForm.js +++ b/dist/modules/forms/useForm.js @@ -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' : '…'} /> *
…
*/ 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, diff --git a/dist/modules/forms/useForm.js.map b/dist/modules/forms/useForm.js.map index 1e68aac..85f20e5 100644 --- a/dist/modules/forms/useForm.js.map +++ b/dist/modules/forms/useForm.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/forms/useForm.ts"],"sourcesContent":["'use client'\n\nimport { useState, useCallback, useRef, useMemo } from 'react'\n\n/**\n * Error map: a field key → its error message. A field is \"in error\" iff it has\n * a key here, so `errors.email` is both the truthy flag (for a red border) AND\n * the message (to display). Empty object = valid.\n */\nexport type FormErrors = Partial>\n\n/**\n * The project's server action that calls submitForm (server-only, holds the\n * Turnstile secret). This hook is a client hook, so it can't call submitForm\n * directly — the project injects its action. The result only needs `success`\n * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.\n */\nexport type FormSubmitAction = (\n values: T,\n turnstileToken?: string,\n) => Promise<{ success: boolean; message?: string }>\n\n/** Turns the current values into an error map. Empty map = valid. */\nexport type Validator = (values: T) => FormErrors\n\ntype UseFormOptions> = {\n /** Defines the field set AND the reset state. Any shape you like. */\n initialValues: T\n submitAction: FormSubmitAction\n /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */\n validate?: Validator\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n /** Generic error message shown when the action fails/throws with no message. */\n errorFallback?: string\n /** Clear a field's error as soon as the user edits it. Default true. */\n clearErrorOnChange?: boolean\n}\n\n/**\n * Fully generic form engine: state, validation, Turnstile token, submit,\n * success/error — WITHOUT any markup. The project owns 100% of the look AND\n * the field set: there is no baked-in shape here. Replaces the identical\n * ~150 lines of form plumbing copied into every project.\n *\n * The field set comes from `initialValues`; the rules come from `validate`\n * (so dynamic/builder-driven forms just build both at runtime). For the\n * everyday contact form use the `useContactForm` preset instead — it wires\n * the standard fields and rules for you.\n *\n * const f = useForm({\n * initialValues: { email: '', message: '' },\n * submitAction, // your server action\n * validate: buildValidator({ email: [required(), email()], message: [required()] }),\n * requireTurnstile: Boolean(siteKey),\n * })\n * f.setField('email', e.target.value)}\n * className={f.errors.email ? 'border-red-500' : '…'} />\n *
…
\n */\nexport function useForm>(options: UseFormOptions) {\n const {\n initialValues,\n submitAction,\n validate,\n requireTurnstile = false,\n errorFallback = 'Something went wrong. Please try again.',\n clearErrorOnChange = true,\n } = options\n\n // Freeze the initial snapshot so `reset` is stable even though callers pass a\n // fresh object literal every render.\n const initialRef = useRef(initialValues)\n\n const [values, setValues] = useState(initialRef.current)\n const [errors, setErrors] = useState>({})\n const [isSubmitting, setIsSubmitting] = useState(false)\n const [isSuccess, setIsSuccess] = useState(false)\n const [errorMessage, setErrorMessage] = useState(null)\n const [turnstileToken, setTurnstileToken] = useState(null)\n\n const setField = useCallback(\n (key: K, value: T[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n if (clearErrorOnChange) {\n setErrors((prev) => {\n if (!prev[key]) return prev\n const next = { ...prev }\n delete next[key]\n return next\n })\n }\n },\n [clearErrorOnChange],\n )\n\n // Validate against the LATEST values via a ref, so handleSubmit stays stable\n // and never reads a stale snapshot.\n const valuesRef = useRef(values)\n valuesRef.current = values\n const validateRef = useRef(validate)\n validateRef.current = validate\n\n const handleSubmit = useCallback(\n async (e?: { preventDefault?: () => void }) => {\n e?.preventDefault?.()\n setErrorMessage(null)\n\n const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}\n setErrors(errs)\n if (Object.keys(errs).length > 0) return\n\n if (requireTurnstile && !turnstileToken) {\n setErrorMessage(errorFallback)\n return\n }\n\n setIsSubmitting(true)\n try {\n const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)\n if (result.success) {\n setIsSuccess(true)\n setTurnstileToken(null)\n } else {\n setErrorMessage(result.message || errorFallback)\n }\n } catch (err) {\n setErrorMessage(err instanceof Error ? err.message : errorFallback)\n } finally {\n setIsSubmitting(false)\n }\n },\n [requireTurnstile, turnstileToken, submitAction, errorFallback],\n )\n\n const reset = useCallback(() => {\n setValues(initialRef.current)\n setErrors({})\n setIsSuccess(false)\n setErrorMessage(null)\n setTurnstileToken(null)\n }, [])\n\n return useMemo(\n () => ({\n values,\n errors,\n isSubmitting,\n isSuccess,\n errorMessage,\n turnstileToken,\n setField,\n setValues,\n setErrors,\n setTurnstileToken,\n handleSubmit,\n reset,\n }),\n [\n values,\n errors,\n isSubmitting,\n isSuccess,\n errorMessage,\n turnstileToken,\n setField,\n handleSubmit,\n reset,\n ],\n )\n}\n"],"names":["useState","useCallback","useRef","useMemo","useForm","options","initialValues","submitAction","validate","requireTurnstile","errorFallback","clearErrorOnChange","initialRef","values","setValues","current","errors","setErrors","isSubmitting","setIsSubmitting","isSuccess","setIsSuccess","errorMessage","setErrorMessage","turnstileToken","setTurnstileToken","setField","key","value","prev","next","valuesRef","validateRef","handleSubmit","e","preventDefault","errs","Object","keys","length","result","undefined","success","message","err","Error","reset"],"mappings":"AAAA;AAEA,SAASA,QAAQ,EAAEC,WAAW,EAAEC,MAAM,EAAEC,OAAO,QAAQ,QAAO;AAqC9D;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,SAASC,QAA2CC,OAA0B;IACnF,MAAM,EACJC,aAAa,E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AAI9B,oBAAoB,CAACe,gBAAgB;YACvCD,gBAAgBb;YAChB;QACF;QAEAS,gBAAgB;QAChB,IAAI;YACF,MAAMqB,SAAS,MAAMjC,aAAawB,UAAUhB,OAAO,EAAES,kBAAkBiB;YACvE,IAAID,OAAOE,OAAO,EAAE;gBAClBrB,aAAa;gBACbI,kBAAkB;YACpB,OAAO;gBACLF,gBAAgBiB,OAAOG,OAAO,IAAIjC;YACpC;QACF,EAAE,OAAOkC,KAAK;YACZrB,gBAAgBqB,eAAeC,QAAQD,IAAID,OAAO,GAAGjC;QACvD,SAAU;YACRS,gBAAgB;QAClB;IACF,GACA;QAACV;QAAkBe;QAAgBjB;QAAcG;KAAc;IAGjE,MAAMoC,QAAQ7C,YAAY;QACxBa,UAAUF,WAAWG,OAAO;QAC5BE,UAAU,CAAC;QACXI,aAAa;QACbE,gBAAgB;QAChBE,kBAAkB;IACpB,GAAG,EAAE;IAEL,OAAOtB,QACL,IAAO,CAAA;YACLU;YACAG;YACAE;YACAE;YACAE;YACAE;YACAE;YACAZ;YACAG;YACAQ;YACAQ;YACAa;QACF,CAAA,GACA;QACEjC;QACAG;QACAE;QACAE;QACAE;QACAE;QACAE;QACAO;QACAa;KACD;AAEL"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/forms/useForm.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\n\n/**\n * Error map: a field key → its error message. A field is \"in error\" iff it has\n * a key here, so `errors.email` is both the truthy flag (for a red border) AND\n * the message (to display). Empty object = valid.\n */\nexport type FormErrors = Partial>\n\n/**\n * The project's server action that calls submitForm (server-only, holds the\n * Turnstile secret). This hook is a client hook, so it can't call submitForm\n * directly — the project injects its action. The result only needs `success`\n * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.\n */\nexport type FormSubmitAction = (\n values: T,\n turnstileToken?: string,\n) => Promise<{ message?: string; success: boolean }>\n\n/** Turns the current values into an error map. Empty map = valid. */\nexport type Validator = (values: T) => FormErrors\n\ntype UseFormOptions> = {\n /** Clear a field's error as soon as the user edits it. Default true. */\n clearErrorOnChange?: boolean\n /** Generic error message shown when the action fails/throws with no message. */\n errorFallback?: string\n /** Defines the field set AND the reset state. Any shape you like. */\n initialValues: T\n /**\n * Called once after a SUCCESSFUL submit, with the submitted values and the\n * action's result. The place to fire analytics — e.g. a GTM `form_submit`\n * event so a Meta Pixel / GA \"Lead\" tag can trigger:\n *\n * onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' })\n *\n * Runs client-side after the server action resolves; errors thrown here are\n * swallowed so a broken analytics call can't blank out a successful submit.\n */\n onSuccess?: (result: { message?: string; success: boolean }, values: T) => void\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: FormSubmitAction\n /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */\n validate?: Validator\n}\n\n/**\n * Fully generic form engine: state, validation, Turnstile token, submit,\n * success/error — WITHOUT any markup. The project owns 100% of the look AND\n * the field set: there is no baked-in shape here. Replaces the identical\n * ~150 lines of form plumbing copied into every project.\n *\n * The field set comes from `initialValues`; the rules come from `validate`\n * (so dynamic/builder-driven forms just build both at runtime). For the\n * everyday contact form use the `useContactForm` preset instead — it wires\n * the standard fields and rules for you.\n *\n * const f = useForm({\n * initialValues: { email: '', message: '' },\n * submitAction, // your server action\n * validate: buildValidator({ email: [required(), email()], message: [required()] }),\n * requireTurnstile: Boolean(siteKey),\n * })\n * f.setField('email', e.target.value)}\n * className={f.errors.email ? 'border-red-500' : '…'} />\n *
…
\n */\nexport function useForm>(options: UseFormOptions) {\n const {\n clearErrorOnChange = true,\n errorFallback = 'Something went wrong. Please try again.',\n initialValues,\n requireTurnstile = false,\n submitAction,\n validate,\n } = options\n\n // Freeze the initial snapshot so `reset` is stable even though callers pass a\n // fresh object literal every render.\n const initialRef = useRef(initialValues)\n\n const [values, setValues] = useState(initialRef.current)\n const [errors, setErrors] = useState>({})\n const [isSubmitting, setIsSubmitting] = useState(false)\n const [isSuccess, setIsSuccess] = useState(false)\n const [errorMessage, setErrorMessage] = useState(null)\n const [turnstileToken, setTurnstileToken] = useState(null)\n\n const setField = useCallback(\n (key: K, value: T[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n if (clearErrorOnChange) {\n setErrors((prev) => {\n if (!prev[key]) {return prev}\n const next = { ...prev }\n delete next[key]\n return next\n })\n }\n },\n [clearErrorOnChange],\n )\n\n // Validate against the LATEST values via a ref, so handleSubmit stays stable\n // and never reads a stale snapshot.\n const valuesRef = useRef(values)\n valuesRef.current = values\n const validateRef = useRef(validate)\n validateRef.current = validate\n const onSuccessRef = useRef(options.onSuccess)\n onSuccessRef.current = options.onSuccess\n\n const handleSubmit = useCallback(\n async (e?: { preventDefault?: () => void }) => {\n e?.preventDefault?.()\n setErrorMessage(null)\n\n const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}\n setErrors(errs)\n if (Object.keys(errs).length > 0) {return}\n\n if (requireTurnstile && !turnstileToken) {\n setErrorMessage(errorFallback)\n return\n }\n\n setIsSubmitting(true)\n try {\n const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)\n if (result.success) {\n setIsSuccess(true)\n setTurnstileToken(null)\n // Fire analytics (e.g. GTM form_submit) — never let it break the submit.\n try {\n onSuccessRef.current?.(result, valuesRef.current)\n } catch {\n /* analytics must not affect the form outcome */\n }\n } else {\n setErrorMessage(result.message || errorFallback)\n }\n } catch (err) {\n setErrorMessage(err instanceof Error ? err.message : errorFallback)\n } finally {\n setIsSubmitting(false)\n }\n },\n [requireTurnstile, turnstileToken, submitAction, errorFallback],\n )\n\n const reset = useCallback(() => {\n setValues(initialRef.current)\n setErrors({})\n setIsSuccess(false)\n setErrorMessage(null)\n setTurnstileToken(null)\n }, [])\n\n return useMemo(\n () => ({\n errorMessage,\n errors,\n handleSubmit,\n isSubmitting,\n isSuccess,\n reset,\n setErrors,\n setField,\n setTurnstileToken,\n setValues,\n turnstileToken,\n values,\n }),\n [\n values,\n errors,\n isSubmitting,\n isSuccess,\n errorMessage,\n turnstileToken,\n setField,\n handleSubmit,\n reset,\n ],\n )\n}\n"],"names":["useCallback","useMemo","useRef","useState","useForm","options","clearErrorOnChange","errorFallback","initialValues","requireTurnstile","submitAction","validate","initialRef","values","setValues","current","errors","setErrors","isSubmitting","setIsSubmitting","isSuccess","setIsSuccess","errorMessage","setErrorMessage","turnstileToken","setTurnstileToken","setField","key","value","prev","next","valuesRef","validateRef","onSuccessRef","onSuccess","handleSubmit","e","preventDefault","errs","Object","keys","length","result","undefined","success","message","err","Error","reset"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAgD9D;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,SAASC,QAA2CC,OAA0B;IACnF,MAAM,EACJC,qBAAqB,IAAI,EACzBC,gBAAgB,yCAAyC,EACzDC,aAAa,EACbC,mBAAmB,KAAK,EACxBC,YAAY,EACZC,QAAQ,EACT,GAAGN;IAEJ,8EAA8E;IAC9E,qCAAqC;IACrC,MAAMO,aAAaV,OAAOM;IAE1B,MAAM,CAACK,QAAQC,UAAU,GAAGX,SAAYS,WAAWG,OAAO;IAC1D,MAAM,CAACC,QAAQC,UAAU,GAAGd,SAAwB,CAAC;IACrD,MAAM,CAACe,cAAcC,gBAAgB,GAAGhB,SAAS;IACjD,MAAM,CAACiB,WAAWC,aAAa,GAAGlB,SAAS;IAC3C,MAAM,CAACmB,cAAcC,gBAAgB,GAAGpB,SAAwB;IAChE,MAAM,CAACqB,gBAAgBC,kBAAkB,GAAGtB,SAAwB;IAEpE,MAAMuB,WAAW1B,YACf,CAAoB2B,KAAQC;QAC1Bd,UAAU,CAACe,OAAU,CAAA;gBAAE,GAAGA,IAAI;gBAAE,CAACF,IAAI,EAAEC;YAAM,CAAA;QAC7C,IAAItB,oBAAoB;YACtBW,UAAU,CAACY;gBACT,IAAI,CAACA,IAAI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QhD,YAAY;QACxBc,UAAUF,WAAWG,OAAO;QAC5BE,UAAU,CAAC;QACXI,aAAa;QACbE,gBAAgB;QAChBE,kBAAkB;IACpB,GAAG,EAAE;IAEL,OAAOxB,QACL,IAAO,CAAA;YACLqB;YACAN;YACAmB;YACAjB;YACAE;YACA4B;YACA/B;YACAS;YACAD;YACAX;YACAU;YACAX;QACF,CAAA,GACA;QACEA;QACAG;QACAE;QACAE;QACAE;QACAE;QACAE;QACAS;QACAa;KACD;AAEL"} \ No newline at end of file diff --git a/dist/modules/hooks/preventDeleteSystemPage.js b/dist/modules/hooks/preventDeleteSystemPage.js index c365843..32f33a4 100644 --- a/dist/modules/hooks/preventDeleteSystemPage.js +++ b/dist/modules/hooks/preventDeleteSystemPage.js @@ -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); } } }; diff --git a/dist/modules/hooks/preventDeleteSystemPage.js.map b/dist/modules/hooks/preventDeleteSystemPage.js.map index 5accdc8..dd028e8 100644 --- a/dist/modules/hooks/preventDeleteSystemPage.js.map +++ b/dist/modules/hooks/preventDeleteSystemPage.js.map @@ -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\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"} \ No newline at end of file +{"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\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"} \ No newline at end of file diff --git a/dist/modules/seo/buildNoindexField.js b/dist/modules/seo/buildNoindexField.js index 113b8b9..69fb612 100644 --- a/dist/modules/seo/buildNoindexField.js +++ b/dist/modules/seo/buildNoindexField.js @@ -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)); diff --git a/dist/modules/seo/buildNoindexField.js.map b/dist/modules/seo/buildNoindexField.js.map index 83129bd..865364b 100644 --- a/dist/modules/seo/buildNoindexField.js.map +++ b/dist/modules/seo/buildNoindexField.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildNoindexField.ts"],"sourcesContent":["import type { CheckboxField, Field, FieldHook } from 'payload'\n\ntype BuildNoindexFieldArgs = {\n /** Help text under the checkbox. */\n description?: string\n /** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */\n label?: string\n /**\n * Dotted path, inside the document, that the SEO read path (metadata +\n * sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.\n * The checkbox value is mirrored here on every save, so editors toggle one\n * friendly switch and the machinery reads a stable location.\n */\n metaPath?: string\n /** Field name for the editor-facing checkbox. Default 'noindex'. */\n name?: string\n /** Extend/override the generated checkbox (position, access, etc.). */\n overrides?: Partial\n}\n\n/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */\nfunction readPath(obj: null | Record | undefined, path: string[]): unknown {\n let cur: unknown = obj\n for (const key of path) {\n if (cur == null || typeof cur !== 'object') {return undefined}\n cur = (cur as Record)[key]\n }\n return cur\n}\n\n/** Write a dotted path, creating intermediate objects as needed. */\nfunction writePath(obj: Record, path: string[], value: unknown): void {\n let cur: Record = obj\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]\n const next = cur[key]\n if (next == null || typeof next !== 'object') {cur[key] = {}}\n cur = cur[key] as Record\n }\n cur[path[path.length - 1]] = value\n}\n\n/**\n * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the\n * sitemap and metadata generators actually read). Replaces the hand-rolled\n * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`\n * glue copied into every project — no `any`, one source of truth for editors,\n * one stable read location for the engine.\n *\n * Idempotent and order-independent: if either the checkbox OR an existing\n * `meta.noindex` is set, the page ends up noindex; the two can't drift apart.\n *\n * // collections/Pages.ts\n * import { buildNoindexField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildNoindexField() ],\n */\nexport function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {\n const {\n name = 'noindex',\n description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.',\n label = 'Wyklucz z indeksowania (noindex)',\n metaPath = 'meta.noindex',\n overrides = {},\n } = args\n\n const segments = metaPath.split('.')\n\n const mirror: FieldHook = ({ data, value }) => {\n const shouldNoindex = Boolean(value ?? readPath(data as Record, segments))\n if (data && typeof data === 'object') {\n writePath(data as Record, segments, shouldNoindex)\n }\n return shouldNoindex\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'checkbox',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n defaultValue: false,\n hooks: {\n ...hooksOverrides,\n // mirror runs first, then any project-supplied beforeChange hooks.\n beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],\n },\n label,\n ...restOverrides,\n } as CheckboxField\n}\n"],"names":["readPath","obj","path","cur","key","undefined","writePath","value","i","length","next","buildNoindexField","args","name","description","label","metaPath","overrides","segments","split","mirror","data","shouldNoindex","Boolean","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","defaultValue","beforeChange"],"mappings":"AAoBA,yEAAyE,GACzE,SAASA,SAASC,GAA+C,EAAEC,IAAc;IAC/E,IAAIC,MAAeF;IACnB,KAAK,MAAMG,OAAOF,KAAM;QACtB,IAAIC,OAAO,QAAQ,OAAOA,QAAQ,UAAU;YAAC,OAAOE;QAAS;QAC7DF,MAAM,AAACA,GAA+B,CAACC,IAAI;IAC7C;IACA,OAAOD;AACT;AAEA,kEAAkE,GAClE,SAASG,UAAUL,GAA4B,EAAEC,IAAc,EAAEK,KAAc;IAC7E,IAAIJ,MAA+BF;IACnC,IAAK,IAAIO,IAAI,GAAGA,IAAIN,KAAKO,MAAM,GAAG,GAAGD,IAAK;QACxC,MAAMJ,MAAMF,IAAI,CAACM,EAAE;QACnB,MAAME,OAAOP,GAAG,CAACC,IAAI;QACrB,IAAIM,QAAQ,QAAQ,OAAOA,SAAS,UAAU;YAACP,GAAG,CAACC,IAAI,GAAG,CAAC;QAAC;QAC5DD,MAAMA,GAAG,CAACC,IAAI;IAChB;IACAD,GAAG,CAACD,IAAI,CAACA,KAAKO,MAAM,GAAG,EAAE,CAAC,GAAGF;AAC/B;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,kBAAkBC,OAA8B,CAAC,CAAC;IAChE,MAAM,EACJC,OAAO,SAAS,EAChBC,cAAc,+FAA+F,EAC7GC,QAAQ,kCAAkC,EAC1CC,WAAW,cAAc,EACzBC,YAAY,CAAC,CAAC,EACf,GAAGL;IAEJ,MAAMM,WAAWF,SAASG,KAAK,CAAC;IAEhC,MAAMC,SAAoB,CAAC,EAAEC,IAAI,EAAEd,KAAK,EAAE;QACxC,MAAMe,gBAAgBC,QAAQhB,SAASP,SAASqB,MAAiCH;QACjF,IAAIG,QAAQ,OAAOA,SAAS,UAAU;YACpCf,UAAUe,MAAiCH,UAAUI;QACvD;QACA,OAAOA;IACT;IAEA,MAAM,EAAEE,OAAOC,cAAc,EAAEC,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGX;IAE3E,OAAO;QACLJ;QACAgB,MAAM;QACNL,OAAO;YACLV;YACAgB,UAAU;YACV,GAAGL,cAAc;QACnB;QACAM,cAAc;QACdL,OAAO;YACL,GAAGC,cAAc;YACjB,mEAAmE;YACnEK,cAAc;gBAACZ;mBAAYO,gBAAgBK,gBAAgB,EAAE;aAAE;QACjE;QACAjB;QACA,GAAGa,aAAa;IAClB;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildNoindexField.ts"],"sourcesContent":["import type { CheckboxField, Field, FieldHook } from 'payload'\n\ntype BuildNoindexFieldArgs = {\n /** Help text under the checkbox. */\n description?: string\n /** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */\n label?: string\n /**\n * Dotted path, inside the document, that the SEO read path (metadata +\n * sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.\n * The checkbox value is mirrored here on every save, so editors toggle one\n * friendly switch and the machinery reads a stable location.\n */\n metaPath?: string\n /** Field name for the editor-facing checkbox. Default 'noindex'. */\n name?: string\n /** Extend/override the generated checkbox (position, access, etc.). */\n overrides?: Partial\n}\n\n/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */\nfunction readPath(obj: null | Record | undefined, path: string[]): unknown {\n let cur: unknown = obj\n for (const key of path) {\n if (cur == null || typeof cur !== 'object') {return undefined}\n cur = (cur as Record)[key]\n }\n return cur\n}\n\n/** Write a dotted path, creating intermediate objects as needed. */\nfunction writePath(obj: Record, path: string[], value: unknown): void {\n let cur: Record = obj\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]\n const next = cur[key]\n if (next == null || typeof next !== 'object') {cur[key] = {}}\n cur = cur[key] as Record\n }\n cur[path[path.length - 1]] = value\n}\n\n/**\n * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the\n * sitemap and metadata generators actually read). Replaces the hand-rolled\n * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`\n * glue copied into every project — no `any`, one source of truth for editors,\n * one stable read location for the engine.\n *\n * Idempotent and order-independent: if either the checkbox OR an existing\n * `meta.noindex` is set, the page ends up noindex; the two can't drift apart.\n *\n * // collections/Pages.ts\n * import { buildNoindexField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildNoindexField() ],\n */\nexport function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {\n const {\n name = 'noindex',\n description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.',\n label = 'Exclude from indexing (noindex)',\n metaPath = 'meta.noindex',\n overrides = {},\n } = args\n\n const segments = metaPath.split('.')\n\n const mirror: FieldHook = ({ data, value }) => {\n const shouldNoindex = Boolean(value ?? readPath(data as Record, segments))\n if (data && typeof data === 'object') {\n writePath(data as Record, segments, shouldNoindex)\n }\n return shouldNoindex\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'checkbox',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n defaultValue: false,\n hooks: {\n ...hooksOverrides,\n // mirror runs first, then any project-supplied beforeChange hooks.\n beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],\n },\n label,\n ...restOverrides,\n } as CheckboxField\n}\n"],"names":["readPath","obj","path","cur","key","undefined","writePath","value","i","length","next","buildNoindexField","args","name","description","label","metaPath","overrides","segments","split","mirror","data","shouldNoindex","Boolean","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","defaultValue","beforeChange"],"mappings":"AAoBA,yEAAyE,GACzE,SAASA,SAASC,GAA+C,EAAEC,IAAc;IAC/E,IAAIC,MAAeF;IACnB,KAAK,MAAMG,OAAOF,KAAM;QACtB,IAAIC,OAAO,QAAQ,OAAOA,QAAQ,UAAU;YAAC,OAAOE;QAAS;QAC7DF,MAAM,AAACA,GAA+B,CAACC,IAAI;IAC7C;IACA,OAAOD;AACT;AAEA,kEAAkE,GAClE,SAASG,UAAUL,GAA4B,EAAEC,IAAc,EAAEK,KAAc;IAC7E,IAAIJ,MAA+BF;IACnC,IAAK,IAAIO,IAAI,GAAGA,IAAIN,KAAKO,MAAM,GAAG,GAAGD,IAAK;QACxC,MAAMJ,MAAMF,IAAI,CAACM,EAAE;QACnB,MAAME,OAAOP,GAAG,CAACC,IAAI;QACrB,IAAIM,QAAQ,QAAQ,OAAOA,SAAS,UAAU;YAACP,GAAG,CAACC,IAAI,GAAG,CAAC;QAAC;QAC5DD,MAAMA,GAAG,CAACC,IAAI;IAChB;IACAD,GAAG,CAACD,IAAI,CAACA,KAAKO,MAAM,GAAG,EAAE,CAAC,GAAGF;AAC/B;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,kBAAkBC,OAA8B,CAAC,CAAC;IAChE,MAAM,EACJC,OAAO,SAAS,EAChBC,cAAc,0FAA0F,EACxGC,QAAQ,iCAAiC,EACzCC,WAAW,cAAc,EACzBC,YAAY,CAAC,CAAC,EACf,GAAGL;IAEJ,MAAMM,WAAWF,SAASG,KAAK,CAAC;IAEhC,MAAMC,SAAoB,CAAC,EAAEC,IAAI,EAAEd,KAAK,EAAE;QACxC,MAAMe,gBAAgBC,QAAQhB,SAASP,SAASqB,MAAiCH;QACjF,IAAIG,QAAQ,OAAOA,SAAS,UAAU;YACpCf,UAAUe,MAAiCH,UAAUI;QACvD;QACA,OAAOA;IACT;IAEA,MAAM,EAAEE,OAAOC,cAAc,EAAEC,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGX;IAE3E,OAAO;QACLJ;QACAgB,MAAM;QACNL,OAAO;YACLV;YACAgB,UAAU;YACV,GAAGL,cAAc;QACnB;QACAM,cAAc;QACdL,OAAO;YACL,GAAGC,cAAc;YACjB,mEAAmE;YACnEK,cAAc;gBAACZ;mBAAYO,gBAAgBK,gBAAgB,EAAE;aAAE;QACjE;QACAjB;QACA,GAAGa,aAAa;IAClB;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/buildSummaryField.js b/dist/modules/seo/buildSummaryField.js index 81b1875..868c1a7 100644 --- a/dist/modules/seo/buildSummaryField.js +++ b/dist/modules/seo/buildSummaryField.js @@ -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; diff --git a/dist/modules/seo/buildSummaryField.js.map b/dist/modules/seo/buildSummaryField.js.map index b092c84..0cd15f2 100644 --- a/dist/modules/seo/buildSummaryField.js.map +++ b/dist/modules/seo/buildSummaryField.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildSummaryField.ts"],"sourcesContent":["import type { Field, FieldHook, TextareaField } from 'payload'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\n\ntype BuildSummaryFieldArgs = {\n /** Auto-fill from page content when the editor leaves it empty. Default true. */\n autoFill?: boolean\n /** Help text under the field. */\n description?: string\n /** Sidebar/admin label. */\n label?: string\n /** Block layout field to derive the summary from. Default 'layout'. */\n layoutField?: string\n /** Target length for the auto-generated summary. Default 300. */\n maxLength?: number\n /** Field name. Default 'aiSummary'. */\n name?: string\n /** Extend/override the generated textarea (position, access…). */\n overrides?: Partial\n}\n\n/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */\nfunction mdToPlain(md: string): string {\n return md\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, '') // images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1') // links → their text\n .replace(/^#{1,6}\\s+/gm, '') // heading markers\n .replace(/^[>\\-*]\\s+/gm, '') // quote/list markers\n .replace(/[*_~`]/g, '') // inline emphasis/code marks\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Truncate at a word boundary, adding an ellipsis when cut. */\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) {return text}\n const slice = text.slice(0, max)\n const lastSpace = slice.lastIndexOf(' ')\n return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`\n}\n\n/**\n * A localized `aiSummary` textarea — a concise, human-written (or auto-derived)\n * description of the page, richer than the SEO meta description. It's the\n * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'`\n * to buildLlmsTxt and searchContent and they'll use it over meta.description.\n *\n * With `autoFill` (default), an empty summary is filled on save from the page's\n * own content (blocks → plain text, trimmed to ~maxLength). Editors can always\n * overwrite it — auto-fill only runs when the field is blank, never clobbers a\n * manual summary. Derived from the page's OWN content, so no hard-coded data.\n *\n * // collections/Pages.ts\n * import { buildSummaryField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildSummaryField() ]\n *\n * // then, richer AI descriptions:\n * buildLlmsTxt({ …, summaryField: 'aiSummary' })\n * createSearchRoute({ …, summaryField: 'aiSummary' })\n */\nexport function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {\n const {\n name = 'aiSummary',\n autoFill = true,\n description = 'Zwięzły opis strony dla agentów AI i llms.txt (bogatszy niż meta description). Puste → generowane automatycznie z treści.',\n label = 'Streszczenie dla AI',\n layoutField = 'layout',\n maxLength = 300,\n overrides = {},\n } = args\n\n const autofillHook: FieldHook = ({ data, value }) => {\n if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary\n if (!data || typeof data !== 'object') {return value}\n const layout = (data as Record)[layoutField]\n const md = blocksToMarkdown(layout)\n if (!md) {return value}\n const plain = mdToPlain(md)\n return plain ? truncate(plain, maxLength) : value\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'textarea',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n hooks: {\n ...hooksOverrides,\n ...(autoFill\n ? { beforeChange: [autofillHook, ...(hooksOverrides?.beforeChange ?? [])] }\n : {}),\n },\n label,\n localized: true,\n ...restOverrides,\n } as TextareaField\n}\n"],"names":["blocksToMarkdown","mdToPlain","md","replace","trim","truncate","text","max","length","slice","lastSpace","lastIndexOf","trimEnd","buildSummaryField","args","name","autoFill","description","label","layoutField","maxLength","overrides","autofillHook","data","value","layout","plain","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","beforeChange","localized"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,iCAAgC;AAmBjE,mFAAmF,GACnF,SAASC,UAAUC,EAAU;IAC3B,OAAOA,GACJC,OAAO,CAAC,yBAAyB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AAEG,OAAOC,cAAc,EAAEC,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGV;IAE3E,OAAO;QACLN;QACAiB,MAAM;QACNL,OAAO;YACLV;YACAgB,UAAU;YACV,GAAGL,cAAc;QACnB;QACAC,OAAO;YACL,GAAGC,cAAc;YACjB,GAAId,WACA;gBAAEkB,cAAc;oBAACZ;uBAAkBQ,gBAAgBI,gBAAgB,EAAE;iBAAE;YAAC,IACxE,CAAC,CAAC;QACR;QACAhB;QACAiB,WAAW;QACX,GAAGJ,aAAa;IAClB;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildSummaryField.ts"],"sourcesContent":["import type { Field, FieldHook, TextareaField } from 'payload'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\n\ntype BuildSummaryFieldArgs = {\n /** Auto-fill from page content when the editor leaves it empty. Default true. */\n autoFill?: boolean\n /** Help text under the field. */\n description?: string\n /** Sidebar/admin label. */\n label?: string\n /** Block layout field to derive the summary from. Default 'layout'. */\n layoutField?: string\n /** Target length for the auto-generated summary. Default 300. */\n maxLength?: number\n /** Field name. Default 'aiSummary'. */\n name?: string\n /** Extend/override the generated textarea (position, access…). */\n overrides?: Partial\n}\n\n/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */\nfunction mdToPlain(md: string): string {\n return md\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, '') // images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1') // links → their text\n .replace(/^#{1,6}\\s+/gm, '') // heading markers\n .replace(/^[>\\-*]\\s+/gm, '') // quote/list markers\n .replace(/[*_~`]/g, '') // inline emphasis/code marks\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Truncate at a word boundary, adding an ellipsis when cut. */\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) {return text}\n const slice = text.slice(0, max)\n const lastSpace = slice.lastIndexOf(' ')\n return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`\n}\n\n/**\n * A localized `aiSummary` textarea — a concise, human-written (or auto-derived)\n * description of the page, richer than the SEO meta description. It's the\n * preferred description for AI-facing surfaces: pass `summaryField: 'aiSummary'`\n * to buildLlmsTxt and searchContent and they'll use it over meta.description.\n *\n * With `autoFill` (default), an empty summary is filled on save from the page's\n * own content (blocks → plain text, trimmed to ~maxLength). Editors can always\n * overwrite it — auto-fill only runs when the field is blank, never clobbers a\n * manual summary. Derived from the page's OWN content, so no hard-coded data.\n *\n * // collections/Pages.ts\n * import { buildSummaryField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildSummaryField() ]\n *\n * // then, richer AI descriptions:\n * buildLlmsTxt({ …, summaryField: 'aiSummary' })\n * createSearchRoute({ …, summaryField: 'aiSummary' })\n */\nexport function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {\n const {\n name = 'aiSummary',\n autoFill = true,\n description = 'Concise page description for AI agents and llms.txt (richer than the meta description). Leave empty to auto-generate from the content.',\n label = 'AI summary',\n layoutField = 'layout',\n maxLength = 300,\n overrides = {},\n } = args\n\n const autofillHook: FieldHook = ({ data, value }) => {\n if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary\n if (!data || typeof data !== 'object') {return value}\n const layout = (data as Record)[layoutField]\n const md = blocksToMarkdown(layout)\n if (!md) {return value}\n const plain = mdToPlain(md)\n return plain ? truncate(plain, maxLength) : value\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'textarea',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n hooks: {\n ...hooksOverrides,\n ...(autoFill\n ? { beforeChange: [autofillHook, ...(hooksOverrides?.beforeChange ?? [])] }\n : {}),\n },\n label,\n localized: true,\n ...restOverrides,\n } as TextareaField\n}\n"],"names":["blocksToMarkdown","mdToPlain","md","replace","trim","truncate","text","max","length","slice","lastSpace","lastIndexOf","trimEnd","buildSummaryField","args","name","autoFill","description","label","layoutField","maxLength","overrides","autofillHook","data","value","layout","plain","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","beforeChange","localized"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,iCAAgC;AAmBjE,mFAAmF,GACnF,SAASC,UAAUC,EAAU;IAC3B,OAAOA,GACJC,OAAO,CAAC,yBAAyB,IAAI,SAAS;KAC9CA,OAAO,CAAC,0BAA0B,MAAM,qBAAqB;KAC7DA,OAAO,CAAC,gBAAgB,IAAI,kBAAkB;KAC9CA,OAAO,CAAC,gBAAgB,IAAI,qBAAqB;KACjDA,OAAO,CAAC,WAAW,IAAI,6BAA6B;KACpDA,OAAO,CAAC,QAAQ,KAChBC,IAAI;AACT;AAEA,8DAA8D,GAC9D,SAASC,SAASC,IAAY,EAAEC,GAAW;IACzC,IAAID,KAAKE,MAAM,IAAID,KAAK;QAAC,OAAOD;IAAI;IACpC,MAAMG,QAAQH,KAAKG,KAAK,CAAC,GAAGF;IAC5B,MAAMG,YAAYD,MAAME,WAAW,CAAC;IACpC,OAAO,GAAG,AAACD,CAAAA,YAAYH,MAAM,MAAME,MAAMA,KAAK,CAAC,GAAGC,aAAaD,KAAI,EAAGG,OAAO,GAAG,CAAC,CAAC;AACpF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,kBAAkBC,OAA8B,CAAC,CAAC;IAChE,MAAM,EACJC,OAAO,WAAW,EAClBC,WAAW,IAAI,EACfC,cAAc,wIAAwI,EACtJC,QAAQ,YAAY,EACpBC,cAAc,QAAQ,EACtBC,YAAY,GAAG,EACfC,YAAY,CAAC,CAAC,EACf,GAAGP;IAEJ,MAAMQ,eAA0B,CAAC,EAAEC,IAAI,EAAEC,KAAK,EAAE;QAC9C,IAAI,OAAOA,UAAU,YAAYA,MAAMpB,IAAI,IAAI;YAAC,OAAOoB;QAAK,EAAE,iCAAiC;QAC/F,IAAI,CAACD,QAAQ,OAAOA,SAAS,UAAU;YAAC,OAAOC;QAAK;QACpD,MAAMC,SAAS,AAACF,IAAgC,CAACJ,YAAY;QAC7D,MAAMjB,KAAKF,iBAAiByB;QAC5B,IAAI,CAACvB,IAAI;YAAC,OAAOsB;QAAK;QACtB,MAAME,QAAQzB,UAAUC;QACxB,OAAOwB,QAAQrB,SAASqB,OAAON,aAAaI;IAC9C;IAEA,MAAM,EAAEG,OAAOC,cAAc,EAAEC,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGV;IAE3E,OAAO;QACLN;QACAiB,MAAM;QACNL,OAAO;YACLV;YACAgB,UAAU;YACV,GAAGL,cAAc;QACnB;QACAC,OAAO;YACL,GAAGC,cAAc;YACjB,GAAId,WACA;gBAAEkB,cAAc;oBAACZ;uBAAkBQ,gBAAgBI,gBAAgB,EAAE;iBAAE;YAAC,IACxE,CAAC,CAAC;QACR;QACAhB;QACAiB,WAAW;QACX,GAAGJ,aAAa;IAClB;AACF"} \ No newline at end of file diff --git a/docs/accessibility.md b/docs/accessibility.md index da7ed3c..1c2c4a8 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -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 />
@@ -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 = { + pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', reset: 'Resetuj', /* … */ }, + de: { title: 'Barrierefreiheit', textSize: 'Textgröße', /* … */ }, +} + + +``` + +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) diff --git a/docs/analytics.md b/docs/analytics.md index 37c55d3..1b421f7 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -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 diff --git a/docs/forms.md b/docs/forms.md index a5d7af1..9518eb2 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -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 diff --git a/docs/gtm-meta-pixel.md b/docs/gtm-meta-pixel.md new file mode 100644 index 0000000..492af42 --- /dev/null +++ b/docs/gtm-meta-pixel.md @@ -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) | diff --git a/src/exports/client.ts b/src/exports/client.ts index 3cfcec2..3656e15 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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 { diff --git a/src/index.ts b/src/index.ts index c79a029..fbb6480 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { diff --git a/src/modules/accessibility/AccessibilityWidget.tsx b/src/modules/accessibility/AccessibilityWidget.tsx index ca546e1..21a3f02 100644 --- a/src/modules/accessibility/AccessibilityWidget.tsx +++ b/src/modules/accessibility/AccessibilityWidget.tsx @@ -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 = { - 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 first. * * + * + * 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 = { + * pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … }, + * de: { title: 'Barrierefreiheit', … }, + * } + * */ export function AccessibilityWidget({ classNames, diff --git a/src/modules/analytics/client.ts b/src/modules/analytics/client.ts index 791497f..f082b0e 100644 --- a/src/modules/analytics/client.ts +++ b/src/modules/analytics/client.ts @@ -1,2 +1,3 @@ 'use client' export { Analytics } from './Analytics.js' +export { pushDataLayer } from './pushDataLayer.js' diff --git a/src/modules/analytics/pushDataLayer.ts b/src/modules/analytics/pushDataLayer.ts new file mode 100644 index 0000000..1fa99c8 --- /dev/null +++ b/src/modules/analytics/pushDataLayer.ts @@ -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 = {}): void { + if (typeof window === 'undefined') return + const w = window as unknown as { dataLayer?: unknown[] } + w.dataLayer = w.dataLayer || [] + w.dataLayer.push({ event, ...params }) +} diff --git a/src/modules/forms/formAnalytics.ts b/src/modules/forms/formAnalytics.ts new file mode 100644 index 0000000..b938f5e --- /dev/null +++ b/src/modules/forms/formAnalytics.ts @@ -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>( + config: FormAnalyticsConfig, +): (result: { success: boolean }, values: T) => void { + return (_result, values) => { + const event = config?.event?.trim() + if (!event) {return} + const params: Record = {} + 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) + } +} diff --git a/src/modules/forms/formAnalyticsFields.ts b/src/modules/forms/formAnalyticsFields.ts new file mode 100644 index 0000000..f59d4d0 --- /dev/null +++ b/src/modules/forms/formAnalyticsFields.ts @@ -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)', + }, + ] +} diff --git a/src/modules/forms/index.ts b/src/modules/forms/index.ts index 965df3e..a99110e 100644 --- a/src/modules/forms/index.ts +++ b/src/modules/forms/index.ts @@ -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' diff --git a/src/modules/forms/useContactForm.ts b/src/modules/forms/useContactForm.ts index 43117ff..c85755c 100644 --- a/src/modules/forms/useContactForm.ts +++ b/src/modules/forms/useContactForm.ts @@ -30,6 +30,11 @@ type UseContactFormOptions = { messages?: Partial> /** 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, diff --git a/src/modules/forms/useForm.ts b/src/modules/forms/useForm.ts index e8559a2..2966cd1 100644 --- a/src/modules/forms/useForm.ts +++ b/src/modules/forms/useForm.ts @@ -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 = Partial> export type FormSubmitAction = ( 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 = (values: T) => FormErrors type UseFormOptions> = { + /** 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 /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */ validate?: Validator - /** 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> = { */ export function useForm>(options: UseFormOptions) { 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>(options: UseFormOptio const [errors, setErrors] = useState>({}) const [isSubmitting, setIsSubmitting] = useState(false) const [isSuccess, setIsSuccess] = useState(false) - const [errorMessage, setErrorMessage] = useState(null) - const [turnstileToken, setTurnstileToken] = useState(null) + const [errorMessage, setErrorMessage] = useState(null) + const [turnstileToken, setTurnstileToken] = useState(null) const setField = useCallback( (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>(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>(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>(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>(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, diff --git a/src/modules/hooks/preventDeleteSystemPage.ts b/src/modules/hooks/preventDeleteSystemPage.ts index 350ea47..d85fdbc 100644 --- a/src/modules/hooks/preventDeleteSystemPage.ts +++ b/src/modules/hooks/preventDeleteSystemPage.ts @@ -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, ) } diff --git a/src/modules/seo/buildNoindexField.ts b/src/modules/seo/buildNoindexField.ts index 7582b5b..d613921 100644 --- a/src/modules/seo/buildNoindexField.ts +++ b/src/modules/seo/buildNoindexField.ts @@ -57,8 +57,8 @@ function writePath(obj: Record, 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 diff --git a/src/modules/seo/buildSummaryField.ts b/src/modules/seo/buildSummaryField.ts index 6cbfd5b..b6ae4ff 100644 --- a/src/modules/seo/buildSummaryField.ts +++ b/src/modules/seo/buildSummaryField.ts @@ -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 = {},