Compare commits

...
4 Commits
Author SHA1 Message Date
radoslaw.smolinski c6f177a37d 1.7.10 2026-10-12 22:31:50 +02:00
radoslaw.smolinski 1a9c51a1fd Add fix for branding 2026-10-12 22:31:40 +02:00
radoslaw.smolinski 7f5ed75f9e 1.7.9 2026-10-12 19:47:37 +02:00
radoslaw.smolinski 4eb2b627f0 Analytics fix 2026-10-12 19:47:31 +02:00
17 changed files with 333 additions and 78 deletions
+2
View File
@@ -3,7 +3,9 @@ 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 type { AnalyticsProps } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok, } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
+1
View File
@@ -4,6 +4,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\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"}
{"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 type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport {\n loadClarity,\n loadLinkedIn,\n loadMetaPixel,\n loadTikTok,\n} 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'\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","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","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;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SACEC,WAAW,EACXC,YAAY,EACZC,aAAa,EACbC,UAAU,QACL,iCAAgC;AACvC;;;;;;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"}
+28 -8
View File
@@ -4,19 +4,39 @@ declare global {
dataLayer?: unknown[];
}
}
export type AnalyticsProps = {
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
* JS out of the FCP/LCP window.
*
* Consent is unaffected: the Consent Mode default is still pushed immediately
* (a synchronous dataLayer push, no network), and non-Google pixels still
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
*
* Trade-off: visitors who leave before interacting and before the timeout are
* not counted (slightly fewer sessions in GA). Default false.
*/
defer?: boolean;
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number;
} & AnalyticsConfig;
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export declare function Analytics(props: AnalyticsConfig): null;
export declare function Analytics(props: AnalyticsProps): null;
+94 -13
View File
@@ -1,5 +1,5 @@
'use client';
import { useEffect } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useConsentContext } from '../consent/client.js';
import { gtag } from '../consent/googleConsent.js';
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js';
@@ -22,30 +22,106 @@ function injectScript(src) {
s.async = true;
document.head.appendChild(s);
}
const INTERACTION_EVENTS = [
'scroll',
'pointerdown',
'touchstart',
'keydown'
];
/** True once third-party tags may load (immediately, or per `defer` rules). */ function useDeferredReady(defer, timeoutMs) {
const [ready, setReady] = useState(!defer);
useEffect(()=>{
if (!defer || ready) {
return;
}
let timer;
const fire = ()=>setReady(true);
const onLoad = ()=>{
timer = setTimeout(()=>{
if ('requestIdleCallback' in window) {
window.requestIdleCallback(fire, {
timeout: 1000
});
} else {
fire();
}
}, timeoutMs);
};
for (const e of INTERACTION_EVENTS){
window.addEventListener(e, fire, {
once: true,
passive: true
});
}
if (document.readyState === 'complete') {
onLoad();
} else {
window.addEventListener('load', onLoad, {
once: true
});
}
return ()=>{
for (const e of INTERACTION_EVENTS){
window.removeEventListener(e, fire);
}
window.removeEventListener('load', onLoad);
if (timer) {
clearTimeout(timer);
}
};
}, [
defer,
ready,
timeoutMs
]);
return ready;
}
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/ export function Analytics(props) {
const { clarityProjectId, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
const { clarityProjectId, defer = false, deferTimeoutMs = 3500, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext();
// --- Google: load once, Consent Mode handles gating ---
const ready = useDeferredReady(defer, deferTimeoutMs);
const defaultConsentSet = useRef(false);
// --- Consent Mode default: immediately, once — never deferred ---
// No network cost, and it must precede any gtag('config') / GTM start, or
// Google assumes "granted".
useEffect(()=>{
if (defaultConsentSet.current) {
return;
}
if (!ga4MeasurementId && !gtmContainerId) {
return;
}
setDefaultConsent(readConsent());
defaultConsentSet.current = true;
}, [
ga4MeasurementId,
gtmContainerId
]);
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(()=>{
if (!ready) {
return;
}
if (!ga4MeasurementId && !gtmContainerId) {
return;
}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
@@ -59,13 +135,17 @@ function injectScript(src) {
gtag('config', ga4MeasurementId);
}
}, [
ready,
ga4MeasurementId,
gtmContainerId
]);
// --- Non-Google: load each when its consent category is granted ---
// The loaders are idempotent, so re-running on state changes is safe; a tag
// loads the first time its category flips to true and never doubles up.
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
// the first time both conditions hold and never doubles up.
useEffect(()=>{
if (!ready) {
return;
}
if (state.marketing) {
if (metaPixelId) {
loadMetaPixel(metaPixelId);
@@ -81,6 +161,7 @@ function injectScript(src) {
loadClarity(clarityProjectId);
}
}, [
ready,
state.marketing,
state.analytics,
metaPixelId,
File diff suppressed because one or more lines are too long
+1
View File
@@ -1,3 +1,4 @@
export { Analytics } from './Analytics.js';
export type { AnalyticsProps } from './Analytics.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
export { pushDataLayer } from './pushDataLayer.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"}
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport type { AnalyticsProps } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"}
+14 -7
View File
@@ -1,3 +1,4 @@
import type { Payload } from 'payload';
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
@@ -5,13 +6,13 @@
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
* Server Components — they read the SiteSettings global at render, using the
* `payload` instance Payload itself passes to admin server components. NO
* `import('@payload-config')`: a variable-specifier import isn't traced by the
* Next bundler ("Cannot find module '@payload-config'") — same bug class as the
* old 2FA import. Everything is wrapped in try/catch: no payload prop, DB not
* ready, etc. → site name text, then null (Payload's own default) — never
* throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
@@ -19,8 +20,14 @@
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string;
/** Injected by Payload — current admin locale (object or code). */
locale?: {
code?: string;
} | string;
/** Field holding the site name. Default 'siteName'. */
nameField?: string;
/** Injected by Payload into admin server components. */
payload?: Payload;
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string;
};
+33 -13
View File
@@ -1,25 +1,45 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { getPayload } from 'payload';
async function loadBranding(settingsSlug, nameField, imageField) {
/** A localized text field may arrive as a string or a { locale: value } map. */ function pickText(value, locale) {
if (typeof value === 'string') {
return value;
}
if (value && typeof value === 'object') {
const map = value;
const preferred = locale ? map[locale] : undefined;
if (typeof preferred === 'string') {
return preferred;
}
const first = Object.values(map).find((v)=>typeof v === 'string');
return first ?? null;
}
return null;
}
async function loadBranding(props, settingsSlug, nameField, imageField) {
const { payload } = props;
if (!payload) {
return {
name: null,
url: null
};
}
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config';
const mod = await import(spec);
const payload = await getPayload({
config: mod.default
});
const locale = typeof props.locale === 'string' ? props.locale : props.locale?.code;
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 1
depth: 1,
...locale ? {
locale: locale
} : {}
});
const name = typeof settings[nameField] === 'string' ? settings[nameField] : null;
const name = pickText(settings[nameField], locale);
const image = settings[imageField];
const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null;
return {
name,
url
};
} catch {
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error);
return {
name: null,
url: null
@@ -32,7 +52,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
* falls back to `siteName` text. Sized generously for the login screen.
*/ export async function AdminLogo(props = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
@@ -59,7 +79,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
}
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
if (url) {
return /*#__PURE__*/ _jsx("img", {
alt: name ?? '',
File diff suppressed because one or more lines are too long
+23 -1
View File
@@ -80,6 +80,28 @@ export default async function LocaleLayout({ children, params }) {
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.8.0 czyta stan zgody na
żywo — poza providerem rzuci błąd kontekstu).
## Tryb Core Web Vitals — `defer` (opcjonalny)
```tsx
<Analytics {...analytics} defer /> // domyślnie 3500 ms
<Analytics {...analytics} defer deferTimeoutMs={5000} />
```
Wszystkie tagi (GA4/GTM i pixele) ładują się z sieci dopiero przy **pierwszej
interakcji** (scroll, klik, dotyk, klawisz) albo `deferTimeoutMs` po `load`,
w zależności od tego, co nastąpi pierwsze. ~100+ KiB JS wypada z okna FCP/LCP.
Defer zmienia **kiedy**, nigdy **czy**:
- domyślny stan Consent Mode nadal idzie od razu (to tylko push do dataLayer, bez
ruchu sieciowego), więc GA nigdy nie startuje bez niego;
- pixele non-Google nadal wymagają zgody na swoją kategorię.
Koszt: odwiedzający, którzy wyjdą przed interakcją i przed upływem timeoutu, nie
zostaną policzeni (trochę mniej sesji w GA). Domyślnie `defer` jest wyłączony.
**Nie kopiuj `Analytics` do projektu, żeby to zmienić.** Brakujące opcje dodajemy
w ipal-kit (core = engine).
## Jak działa Consent Mode
1. Przed załadowaniem tagu: `gtag('consent', 'default', …)` z zapisaną decyzją
@@ -137,4 +159,4 @@ czysty event, na którym tag może się odpalić, gdy zgoda jest udzielona.
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
nie tworzy. Przy debugowaniu warto tymczasowo wyczyścić GTM Container ID i
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.8",
"version": "1.7.10",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+8 -1
View File
@@ -8,8 +8,15 @@ 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'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export {
loadClarity,
loadLinkedIn,
loadMetaPixel,
loadTikTok,
} from '../modules/analytics/client.js'
/**
* Entry point: ipal-kit/client
*
+88 -14
View File
@@ -1,5 +1,5 @@
'use client'
import { useEffect } from 'react'
import { useEffect, useRef, useState } from 'react'
import type { AnalyticsConfig } from './types.js'
@@ -35,24 +35,84 @@ function injectScript(src: string) {
document.head.appendChild(s)
}
export type AnalyticsProps = {
/**
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
* JS out of the FCP/LCP window.
*
* Consent is unaffected: the Consent Mode default is still pushed immediately
* (a synchronous dataLayer push, no network), and non-Google pixels still
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
*
* Trade-off: visitors who leave before interacting and before the timeout are
* not counted (slightly fewer sessions in GA). Default false.
*/
defer?: boolean
/** Fallback delay after window `load`, in ms. Default 3500. */
deferTimeoutMs?: number
} & AnalyticsConfig
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
/** True once third-party tags may load (immediately, or per `defer` rules). */
function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
const [ready, setReady] = useState(!defer)
useEffect(() => {
if (!defer || ready) {return}
let timer: ReturnType<typeof setTimeout> | undefined
const fire = () => setReady(true)
const onLoad = () => {
timer = setTimeout(() => {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(fire, { timeout: 1000 })
} else {
fire()
}
}, timeoutMs)
}
for (const e of INTERACTION_EVENTS) {
window.addEventListener(e, fire, { once: true, passive: true })
}
if (document.readyState === 'complete') {onLoad()}
else {window.addEventListener('load', onLoad, { once: true })}
return () => {
for (const e of INTERACTION_EVENTS) {window.removeEventListener(e, fire)}
window.removeEventListener('load', onLoad)
if (timer) {clearTimeout(timer)}
}
}, [defer, ready, timeoutMs])
return ready
}
/**
* Loads every configured analytics / marketing tag, each respecting consent:
*
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
* stored choice is set as the default BEFORE the tag loads, and useConsent
* pushes an update the moment they decide. GTM wins if both IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
* no Consent Mode, so they load ONLY after the matching category is granted
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
* the consent banner: accept → the tag loads immediately, no reload.
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
* the default BEFORE the tag loads (always immediately, even with `defer`),
* and useConsent pushes an update the moment they decide. GTM wins if both
* IDs are set.
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
* each loads ONLY after its category is granted (marketing for
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
* after load, for better LCP/INP. See AnalyticsProps.defer.
*
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
* <ConsentProvider> (required — it reads live consent state).
*/
export function Analytics(props: AnalyticsConfig) {
export function Analytics(props: AnalyticsProps) {
const {
clarityProjectId,
defer = false,
deferTimeoutMs = 3500,
ga4MeasurementId,
gtmContainerId,
linkedInPartnerId,
@@ -62,11 +122,23 @@ export function Analytics(props: AnalyticsConfig) {
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
// --- Google: load once, Consent Mode handles gating ---
// --- Consent Mode default: immediately, once — never deferred ---
// No network cost, and it must precede any gtag('config') / GTM start, or
// Google assumes "granted".
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
setDefaultConsent(readConsent())
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId])
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(() => {
if (!ready) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
if (gtmContainerId) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
@@ -76,12 +148,13 @@ export function Analytics(props: AnalyticsConfig) {
gtag('js', new Date())
gtag('config', ga4MeasurementId)
}
}, [ga4MeasurementId, gtmContainerId])
}, [ready, ga4MeasurementId, gtmContainerId])
// --- Non-Google: load each when its consent category is granted ---
// The loaders are idempotent, so re-running on state changes is safe; a tag
// loads the first time its category flips to true and never doubles up.
// --- Non-Google: each when `ready` AND its consent category is granted ---
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
// the first time both conditions hold and never doubles up.
useEffect(() => {
if (!ready) {return}
if (state.marketing) {
if (metaPixelId) {loadMetaPixel(metaPixelId)}
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
@@ -89,6 +162,7 @@ export function Analytics(props: AnalyticsConfig) {
}
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
}, [
ready,
state.marketing,
state.analytics,
metaPixelId,
+1
View File
@@ -1,5 +1,6 @@
'use client'
export { Analytics } from './Analytics.js'
export type { AnalyticsProps } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
// needs them (Analytics loads them automatically, consent-gated).
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
+35 -16
View File
@@ -1,4 +1,4 @@
import { getPayload } from 'payload'
import type { Payload } from 'payload'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -7,13 +7,13 @@ import { getPayload } from 'payload'
* automatically by `ipalKit({ whiteLabel: true })` (it injects
* admin.components.graphics.Logo/Icon pointing here).
*
* Server Components — they read the SiteSettings global at render. Data access
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
* try/catch: on the login screen before the DB is ready, or a build with no DB,
* the component falls back to the site name text, then to null (Payload's own
* default) — never throws, never blocks the panel.
* Server Components — they read the SiteSettings global at render, using the
* `payload` instance Payload itself passes to admin server components. NO
* `import('@payload-config')`: a variable-specifier import isn't traced by the
* Next bundler ("Cannot find module '@payload-config'") — same bug class as the
* old 2FA import. Everything is wrapped in try/catch: no payload prop, DB not
* ready, etc. → site name text, then null (Payload's own default) — never
* throws, never blocks the panel.
*
* A0: no client brand in code. The logo/name come from the panel; if nothing is
* set, nothing is forced.
@@ -22,35 +22,54 @@ import { getPayload } from 'payload'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
nameField?: string
/** Injected by Payload into admin server components. */
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
}
type MediaLike = { url?: null | string } | null | undefined
/** A localized text field may arrive as a string or a { locale: value } map. */
function pickText(value: unknown, locale: string | undefined): null | string {
if (typeof value === 'string') {return value}
if (value && typeof value === 'object') {
const map = value as Record<string, unknown>
const preferred = locale ? map[locale] : undefined
if (typeof preferred === 'string') {return preferred}
const first = Object.values(map).find((v): v is string => typeof v === 'string')
return first ?? null
}
return null
}
async function loadBranding(
props: BrandingProps,
settingsSlug: string,
nameField: string,
imageField: string,
): Promise<{ name: null | string; url: null | string }> {
const { payload } = props
if (!payload) {return { name: null, url: null }}
try {
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
const spec = '@payload-config'
const mod = (await import(spec)) as { default: unknown }
const payload = await getPayload({ config: mod.default as never })
const locale = typeof props.locale === 'string' ? props.locale : props.locale?.code
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
...(locale ? { locale: locale as never } : {}),
})) as Record<string, unknown>
const name = typeof settings[nameField] === 'string' ? (settings[nameField]) : null
const name = pickText(settings[nameField], locale)
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
return { name, url }
} catch {
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
return { name: null, url: null }
}
}
@@ -62,7 +81,7 @@ async function loadBranding(
*/
export async function AdminLogo(props: BrandingProps = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField)
if (url) {
return (
<img
@@ -79,7 +98,7 @@ export async function AdminLogo(props: BrandingProps = {}) {
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */
export async function AdminIcon(props: BrandingProps = {}) {
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props
const { name, url } = await loadBranding(settingsSlug, nameField, imageField)
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField)
if (url) {
return (
<img