"use client"; import { useEffect, useRef } from "react"; import { usePathname } from "next/navigation"; import { disposeTracker, flush, initTracker } from "./core"; import { startCaptures, type Captures } from "./capture"; /** * First-party analytics tracker (Phase 1), the replacement for Microsoft * Clarity (which stays mounted during the transition). * * Renders nothing. Mount once per top-level frontend layout * (`src/app/(frontend)/layout.tsx` and `src/app/login/layout.tsx`) next to * ``; one mount covers every route below it. The Payload * admin panel is intentionally NOT tracked. * * Enablement lives in `core.isAnalyticsEnabled()`: production builds always * track; development tracks only with NEXT_PUBLIC_ANALYTICS_DEV=1 (and then * mirrors every event to console.debug("[analytics]", ...)). All failures are * swallowed: analytics must never break the app. * * SPA navigation is captured twice over: a `usePathname()` effect covers App * Router navigations, and patched `history.pushState`/`replaceState` cover * any pushState that does not re-render the tree (duplicate calls for the * same path are deduped inside the capture layer). */ export function AnalyticsTracker() { const pathname = usePathname(); const capturesRef = useRef(null); useEffect(() => { initTracker(); const captures = startCaptures(); capturesRef.current = captures; // History patching: fire a synthetic event whenever app code (or a // library) pushes state without a React navigation. const originalPush = history.pushState.bind(history); const originalReplace = history.replaceState.bind(history); const emit = (fn: typeof history.pushState) => (...args: Parameters) => { fn(...args); window.dispatchEvent(new Event("ptf:analytics-route")); }; history.pushState = emit(originalPush); history.replaceState = emit(originalReplace); const onRouteEvent = () => { try { captures.handleRouteChange(window.location.pathname); flush(false); } catch { // Swallowed by contract. } }; window.addEventListener("ptf:analytics-route", onRouteEvent); return () => { window.removeEventListener("ptf:analytics-route", onRouteEvent); history.pushState = originalPush; history.replaceState = originalReplace; capturesRef.current = null; captures.stop(); disposeTracker(); }; }, []); useEffect(() => { try { capturesRef.current?.handleRouteChange(pathname); } catch { // Swallowed by contract. } }, [pathname]); return null; }