176 lines
6.1 KiB
TypeScript
176 lines
6.1 KiB
TypeScript
'use client'
|
|
import { useEffect, useRef, useState } from 'react'
|
|
|
|
import type { AnalyticsConfig } from './types.js'
|
|
|
|
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'
|
|
|
|
declare global {
|
|
interface Window {
|
|
dataLayer?: unknown[]
|
|
}
|
|
}
|
|
|
|
const GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`
|
|
const GA4_SCRIPT = (id: string) => `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: string) {
|
|
if (document.querySelector(`script[src="${src}"]`)) {return}
|
|
const s = document.createElement('script')
|
|
s.src = src
|
|
s.async = true
|
|
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)** — 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: AnalyticsProps) {
|
|
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
|
|
}
|