175 lines
6.0 KiB
JavaScript
175 lines
6.0 KiB
JavaScript
'use client';
|
|
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';
|
|
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
|
|
const GTM_SCRIPT = (id)=>`https://www.googletagmanager.com/gtm.js?id=${id}`;
|
|
const GA4_SCRIPT = (id)=>`https://www.googletagmanager.com/gtag/js?id=${id}`;
|
|
/** Reads the current consent state from cookie, or defaults if none. */ function readConsent() {
|
|
if (typeof document === 'undefined') {
|
|
return DEFAULT_CONSENT;
|
|
}
|
|
const raw = document.cookie.split('; ').find((c)=>c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1];
|
|
return parseConsent(raw) ?? DEFAULT_CONSENT;
|
|
}
|
|
function injectScript(src) {
|
|
if (document.querySelector(`script[src="${src}"]`)) {
|
|
return;
|
|
}
|
|
const s = document.createElement('script');
|
|
s.src = 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)** — 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, defer = false, deferTimeoutMs = 3500, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
|
|
// Live consent state — drives the non-Google pixels.
|
|
const { state } = useConsentContext();
|
|
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({
|
|
event: 'gtm.js',
|
|
'gtm.start': Date.now()
|
|
});
|
|
injectScript(GTM_SCRIPT(gtmContainerId));
|
|
} else if (ga4MeasurementId) {
|
|
injectScript(GA4_SCRIPT(ga4MeasurementId));
|
|
gtag('js', new Date());
|
|
gtag('config', ga4MeasurementId);
|
|
}
|
|
}, [
|
|
ready,
|
|
ga4MeasurementId,
|
|
gtmContainerId
|
|
]);
|
|
// --- 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);
|
|
}
|
|
if (tiktokPixelId) {
|
|
loadTikTok(tiktokPixelId);
|
|
}
|
|
}
|
|
if (state.analytics && clarityProjectId) {
|
|
loadClarity(clarityProjectId);
|
|
}
|
|
}, [
|
|
ready,
|
|
state.marketing,
|
|
state.analytics,
|
|
metaPixelId,
|
|
linkedInPartnerId,
|
|
tiktokPixelId,
|
|
clarityProjectId
|
|
]);
|
|
return null;
|
|
}
|
|
|
|
//# sourceMappingURL=Analytics.js.map
|