diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index 57c7db0..625cc0f 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -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 * diff --git a/dist/exports/client.js b/dist/exports/client.js index 566c0b5..e17543e 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -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 * diff --git a/dist/exports/client.js.map b/dist/exports/client.js.map index 6c16486..2e520e9 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'\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 +{"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"} \ No newline at end of file diff --git a/dist/modules/analytics/Analytics.d.ts b/dist/modules/analytics/Analytics.d.ts index 4924bb5..2ace238 100644 --- a/dist/modules/analytics/Analytics.d.ts +++ b/dist/modules/analytics/Analytics.d.ts @@ -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 * (required — it reads live consent state). */ -export declare function Analytics(props: AnalyticsConfig): null; +export declare function Analytics(props: AnalyticsProps): null; diff --git a/dist/modules/analytics/Analytics.js b/dist/modules/analytics/Analytics.js index 0b7a710..4ac7d05 100644 --- a/dist/modules/analytics/Analytics.js +++ b/dist/modules/analytics/Analytics.js @@ -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 * (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, diff --git a/dist/modules/analytics/Analytics.js.map b/dist/modules/analytics/Analytics.js.map index f4b9aaf..de2bebe 100644 --- a/dist/modules/analytics/Analytics.js.map +++ b/dist/modules/analytics/Analytics.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/analytics/Analytics.tsx"],"sourcesContent":["'use client'\nimport { useEffect } from 'react'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { useConsentContext } from '../consent/client.js'\nimport { gtag } from '../consent/googleConsent.js'\nimport { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'\nimport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\n\ndeclare global {\n interface Window {\n dataLayer?: unknown[]\n }\n}\n\nconst GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`\nconst GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`\n\n/** Reads the current consent state from cookie, or defaults if none. */\nfunction readConsent() {\n if (typeof document === 'undefined') {return DEFAULT_CONSENT}\n const raw = document.cookie\n .split('; ')\n .find((c) => c.startsWith(`${CONSENT_COOKIE}=`))\n ?.split('=')[1]\n return parseConsent(raw) ?? DEFAULT_CONSENT\n}\n\nfunction injectScript(src: string) {\n if (document.querySelector(`script[src=\"${src}\"]`)) {return}\n const s = document.createElement('script')\n s.src = src\n s.async = true\n document.head.appendChild(s)\n}\n\n/**\n * Loads every configured analytics / marketing tag, each respecting consent:\n *\n * - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's\n * stored choice is set as the default BEFORE the tag loads, and useConsent\n * pushes an update the moment they decide. GTM wins if both IDs are set.\n * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have\n * no Consent Mode, so they load ONLY after the matching category is granted\n * (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to\n * the consent banner: accept → the tag loads immediately, no reload.\n *\n * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed\n * in as props. Renders nothing. Mount once, high in the tree, INSIDE\n * (required — it reads live consent state).\n */\nexport function Analytics(props: AnalyticsConfig) {\n const {\n clarityProjectId,\n ga4MeasurementId,\n gtmContainerId,\n linkedInPartnerId,\n metaPixelId,\n tiktokPixelId,\n } = props\n\n // Live consent state — drives the non-Google pixels.\n const { state } = useConsentContext()\n\n // --- Google: load once, Consent Mode handles gating ---\n useEffect(() => {\n if (!ga4MeasurementId && !gtmContainerId) {return}\n setDefaultConsent(readConsent())\n if (gtmContainerId) {\n window.dataLayer = window.dataLayer || []\n window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })\n injectScript(GTM_SCRIPT(gtmContainerId))\n } else if (ga4MeasurementId) {\n injectScript(GA4_SCRIPT(ga4MeasurementId))\n gtag('js', new Date())\n gtag('config', ga4MeasurementId)\n }\n }, [ga4MeasurementId, gtmContainerId])\n\n // --- Non-Google: load each when its consent category is granted ---\n // The loaders are idempotent, so re-running on state changes is safe; a tag\n // loads the first time its category flips to true and never doubles up.\n useEffect(() => {\n if (state.marketing) {\n if (metaPixelId) {loadMetaPixel(metaPixelId)}\n if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}\n if (tiktokPixelId) {loadTikTok(tiktokPixelId)}\n }\n if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}\n }, [\n state.marketing,\n state.analytics,\n metaPixelId,\n linkedInPartnerId,\n tiktokPixelId,\n clarityProjectId,\n ])\n\n return null\n}\n"],"names":["useEffect","useConsentContext","gtag","CONSENT_COOKIE","DEFAULT_CONSENT","parseConsent","setDefaultConsent","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","GTM_SCRIPT","id","GA4_SCRIPT","readConsent","document","raw","cookie","split","find","c","startsWith","injectScript","src","querySelector","s","createElement","async","head","appendChild","Analytics","props","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId","state","window","dataLayer","push","event","Date","now","marketing","analytics"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,QAAO;AAIjC,SAASC,iBAAiB,QAAQ,uBAAsB;AACxD,SAASC,IAAI,QAAQ,8BAA6B;AAClD,SAASC,cAAc,EAAEC,eAAe,EAAEC,YAAY,EAAEC,iBAAiB,QAAS,sBAAqB;AACvG,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAQlF,MAAMC,aAAa,CAACC,KAAe,CAAC,2CAA2C,EAAEA,IAAI;AACrF,MAAMC,aAAa,CAACD,KAAe,CAAC,4CAA4C,EAAEA,IAAI;AAEtF,sEAAsE,GACtE,SAASE;IACP,IAAI,OAAOC,aAAa,aAAa;QAAC,OAAOX;IAAe;IAC5D,MAAMY,MAAMD,SAASE,MAAM,CACxBC,KAAK,CA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vD,IAAIE,eAAe;gBAAC3B,WAAW2B;YAAc;QAC/C;QACA,IAAIC,MAAMQ,SAAS,IAAId,kBAAkB;YAACzB,YAAYyB;QAAiB;IACzE,GAAG;QACDM,MAAMO,SAAS;QACfP,MAAMQ,SAAS;QACfV;QACAD;QACAE;QACAL;KACD;IAED,OAAO;AACT"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/analytics/Analytics.tsx"],"sourcesContent":["'use client'\nimport { useEffect, useRef, useState } from 'react'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { useConsentContext } from '../consent/client.js'\nimport { gtag } from '../consent/googleConsent.js'\nimport { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'\nimport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\n\ndeclare global {\n interface Window {\n dataLayer?: unknown[]\n }\n}\n\nconst GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`\nconst GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`\n\n/** Reads the current consent state from cookie, or defaults if none. */\nfunction readConsent() {\n if (typeof document === 'undefined') {return DEFAULT_CONSENT}\n const raw = document.cookie\n .split('; ')\n .find((c) => c.startsWith(`${CONSENT_COOKIE}=`))\n ?.split('=')[1]\n return parseConsent(raw) ?? DEFAULT_CONSENT\n}\n\nfunction injectScript(src: string) {\n if (document.querySelector(`script[src=\"${src}\"]`)) {return}\n const s = document.createElement('script')\n s.src = src\n s.async = true\n document.head.appendChild(s)\n}\n\nexport type AnalyticsProps = {\n /**\n * Core Web Vitals mode: hold back every tag's NETWORK load until the first\n * user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the\n * window `load` event — whichever comes first. Keeps ~100+ KiB of third-party\n * JS out of the FCP/LCP window.\n *\n * Consent is unaffected: the Consent Mode default is still pushed immediately\n * (a synchronous dataLayer push, no network), and non-Google pixels still\n * require their consent category. Defer changes WHEN a tag loads, never WHETHER.\n *\n * Trade-off: visitors who leave before interacting and before the timeout are\n * not counted (slightly fewer sessions in GA). Default false.\n */\n defer?: boolean\n /** Fallback delay after window `load`, in ms. Default 3500. */\n deferTimeoutMs?: number\n} & AnalyticsConfig\n\nconst INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const\n\n/** True once third-party tags may load (immediately, or per `defer` rules). */\nfunction useDeferredReady(defer: boolean, timeoutMs: number): boolean {\n const [ready, setReady] = useState(!defer)\n\n useEffect(() => {\n if (!defer || ready) {return}\n let timer: ReturnType | undefined\n\n const fire = () => setReady(true)\n const onLoad = () => {\n timer = setTimeout(() => {\n if ('requestIdleCallback' in window) {\n window.requestIdleCallback(fire, { timeout: 1000 })\n } else {\n fire()\n }\n }, timeoutMs)\n }\n\n for (const e of INTERACTION_EVENTS) {\n window.addEventListener(e, fire, { once: true, passive: true })\n }\n if (document.readyState === 'complete') {onLoad()}\n else {window.addEventListener('load', onLoad, { once: true })}\n\n return () => {\n for (const e of INTERACTION_EVENTS) {window.removeEventListener(e, fire)}\n window.removeEventListener('load', onLoad)\n if (timer) {clearTimeout(timer)}\n }\n }, [defer, ready, timeoutMs])\n\n return ready\n}\n\n/**\n * Loads every configured analytics / marketing tag, each respecting consent:\n *\n * - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as\n * the default BEFORE the tag loads (always immediately, even with `defer`),\n * and useConsent pushes an update the moment they decide. GTM wins if both\n * IDs are set.\n * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so\n * each loads ONLY after its category is granted (marketing for\n * Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.\n * - **`defer`** (opt-in) — additionally waits for first interaction / idle\n * after load, for better LCP/INP. See AnalyticsProps.defer.\n *\n * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed\n * in as props. Renders nothing. Mount once, high in the tree, INSIDE\n * (required — it reads live consent state).\n */\nexport function Analytics(props: AnalyticsProps) {\n const {\n clarityProjectId,\n defer = false,\n deferTimeoutMs = 3500,\n ga4MeasurementId,\n gtmContainerId,\n linkedInPartnerId,\n metaPixelId,\n tiktokPixelId,\n } = props\n\n // Live consent state — drives the non-Google pixels.\n const { state } = useConsentContext()\n const ready = useDeferredReady(defer, deferTimeoutMs)\n const defaultConsentSet = useRef(false)\n\n // --- Consent Mode default: immediately, once — never deferred ---\n // No network cost, and it must precede any gtag('config') / GTM start, or\n // Google assumes \"granted\".\n useEffect(() => {\n if (defaultConsentSet.current) {return}\n if (!ga4MeasurementId && !gtmContainerId) {return}\n setDefaultConsent(readConsent())\n defaultConsentSet.current = true\n }, [ga4MeasurementId, gtmContainerId])\n\n // --- Google: load once `ready`; Consent Mode handles gating ---\n useEffect(() => {\n if (!ready) {return}\n if (!ga4MeasurementId && !gtmContainerId) {return}\n if (gtmContainerId) {\n window.dataLayer = window.dataLayer || []\n window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })\n injectScript(GTM_SCRIPT(gtmContainerId))\n } else if (ga4MeasurementId) {\n injectScript(GA4_SCRIPT(ga4MeasurementId))\n gtag('js', new Date())\n gtag('config', ga4MeasurementId)\n }\n }, [ready, ga4MeasurementId, gtmContainerId])\n\n // --- Non-Google: each when `ready` AND its consent category is granted ---\n // Loaders are idempotent, so re-running on state changes is safe; a tag loads\n // the first time both conditions hold and never doubles up.\n useEffect(() => {\n if (!ready) {return}\n if (state.marketing) {\n if (metaPixelId) {loadMetaPixel(metaPixelId)}\n if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}\n if (tiktokPixelId) {loadTikTok(tiktokPixelId)}\n }\n if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}\n }, [\n ready,\n state.marketing,\n state.analytics,\n metaPixelId,\n linkedInPartnerId,\n tiktokPixelId,\n clarityProjectId,\n ])\n\n return null\n}\n"],"names":["useEffect","useRef","useState","useConsentContext","gtag","CONSENT_COOKIE","DEFAULT_CONSENT","parseConsent","setDefaultConsent","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","GTM_SCRIPT","id","GA4_SCRIPT","readConsent","document","raw","cookie","split","find","c","startsWith","injectScript","src","querySelector","s","createElement","async","head","appendChild","INTERACTION_EVENTS","useDeferredReady","defer","timeoutMs","ready","setReady","timer","fire","onLoad","setTimeout","window","requestIdleCallback","timeout","e","addEventListener","once","passive","readyState","removeEventListener","clearTimeout","Analytics","props","clarityProjectId","deferTimeoutMs","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId","state","defaultConsentSet","current","dataLayer","push","event","Date","now","marketing","analytics"],"mappings":"AAAA;AACA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAInD,SAASC,iBAAiB,QAAQ,uBAAsB;AACxD,SAASC,IAAI,QAAQ,8BAA6B;AAClD,SAASC,cAAc,EAAEC,eAAe,EAAEC,YAAY,EAAEC,iBAAiB,QAAS,sBAAqB;AACvG,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAQlF,MAAMC,aAAa,CAACC,KAAe,CAAC,2CAA2C,EAAEA,IAAI;AACrF,MAAMC,aAAa,CAACD,KAAe,CAAC,4CAA4C,EAAEA,IAAI;AAEtF,sEAAsE,GACtE,SAASE;IACP,IAAI,OAAOC,aAAa,aAAa;QAAC,OAAOX;IAAe;IAC5D,MAAMY,MAAMD,SAASE,MAAM,CACxBC,KAAK,CAAC,MACNC,IAAI,CAAC,CAACC,IAAMA,EAAEC,UAAU,CAAC,GAAGlB,eAAe,CAAC,CAAC,IAC5Ce,MAAM,IAAI,CAAC,EAAE;IACjB,OAAOb,aAAaW,QAAQZ;AAC9B;AAEA,SAASkB,aAAaC,GAAW;IAC/B,IAAIR,SAASS,aAAa,CAAC,CAAC,YAAY,EAAED,IAAI,EAAE,CAAC,GAAG;QAAC;IAAM;IAC3D,MAAME,IAAIV,SAASW,aAAa,CAAC;IACjCD,EAAEF,G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ACAN;KACD;IAED,OAAO;AACT"} \ No newline at end of file diff --git a/dist/modules/analytics/client.d.ts b/dist/modules/analytics/client.d.ts index 4fc2620..a1429e7 100644 --- a/dist/modules/analytics/client.d.ts +++ b/dist/modules/analytics/client.d.ts @@ -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'; diff --git a/dist/modules/analytics/client.js.map b/dist/modules/analytics/client.js.map index 5b7bb7c..ad6e353 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// 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"} \ No newline at end of file +{"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"} \ No newline at end of file diff --git a/docs/analytics.md b/docs/analytics.md index 9667d00..1e2f4ba 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -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 + // domyślnie 3500 ms + +``` + +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ą. \ No newline at end of file +zostawić samo GA4, żeby wyeliminować kontener jako zmienną. \ No newline at end of file diff --git a/src/exports/client.ts b/src/exports/client.ts index 3656e15..fa0c7bc 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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 * diff --git a/src/modules/analytics/Analytics.tsx b/src/modules/analytics/Analytics.tsx index 8f866d9..8366969 100644 --- a/src/modules/analytics/Analytics.tsx +++ b/src/modules/analytics/Analytics.tsx @@ -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 | 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 * (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, diff --git a/src/modules/analytics/client.ts b/src/modules/analytics/client.ts index b57e5ff..a5e3c32 100644 --- a/src/modules/analytics/client.ts +++ b/src/modules/analytics/client.ts @@ -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'