153 lines
6.0 KiB
TypeScript
153 lines
6.0 KiB
TypeScript
'use client';
|
|
|
|
import { useCallback, useEffect, useRef } from 'react';
|
|
import { usePathname } from 'next/navigation';
|
|
import { analyticsAllowed, catalogRoute, trackCatalogClick } from '../lib/catalogAnalytics';
|
|
|
|
declare global {
|
|
interface Window {
|
|
globalPrivacyControl?: boolean;
|
|
dataLayer?: any[];
|
|
clarity?: any;
|
|
gtag?: (...args: any[]) => void;
|
|
}
|
|
}
|
|
|
|
interface AnalyticsDeferredProps {
|
|
gtmId?: string;
|
|
gaId?: string;
|
|
clarityId?: string;
|
|
}
|
|
|
|
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
|
|
const pathname = usePathname();
|
|
const loadedRef = useRef(false);
|
|
const lastPathRef = useRef<string | null>(null);
|
|
const pathnameRef = useRef(pathname);
|
|
useEffect(() => { pathnameRef.current = pathname; }, [pathname]);
|
|
|
|
const emit = useCallback((event: string, params: Record<string, string>) => {
|
|
if (!analyticsAllowed(navigator, window)) return;
|
|
if (gaId && window.gtag) window.gtag('event', event, params);
|
|
else if (gtmId && window.dataLayer) window.dataLayer.push({ event, ...params });
|
|
}, [gaId, gtmId]);
|
|
|
|
const recordView = useCallback((path: string) => {
|
|
if (lastPathRef.current === path) return;
|
|
lastPathRef.current = path;
|
|
const route = catalogRoute(path);
|
|
emit('page_view', { page_path: route, page_location: window.location.origin + route, page_referrer: '' });
|
|
if (route === '/shop/[slug]') emit('catalog_product_view', { content_type: 'product' });
|
|
if (route === '/blog/[slug]' || route === '/wiki/[slug]') emit('catalog_content_view', { content_type: route.startsWith('/blog') ? 'article' : 'wiki' });
|
|
}, [emit]);
|
|
|
|
// Track client-side page views on Next.js route transitions
|
|
useEffect(() => {
|
|
if (!pathname || !loadedRef.current) return;
|
|
recordView(pathname);
|
|
}, [pathname, recordView]);
|
|
|
|
useEffect(() => {
|
|
let loaded = false;
|
|
|
|
const loadAnalytics = () => {
|
|
if (loaded || !analyticsAllowed(navigator, window)) return;
|
|
loaded = true;
|
|
loadedRef.current = true;
|
|
|
|
// Clean up event listeners
|
|
window.removeEventListener('scroll', loadAnalytics);
|
|
window.removeEventListener('touchstart', loadAnalytics);
|
|
window.removeEventListener('mousemove', loadAnalytics);
|
|
window.removeEventListener('keydown', loadAnalytics);
|
|
|
|
// 1. Google Tag Manager
|
|
if (gtmId) {
|
|
window.dataLayer = window.dataLayer || [];
|
|
window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
|
|
const gtmScript = document.createElement('script');
|
|
gtmScript.async = true;
|
|
gtmScript.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
|
|
document.head.appendChild(gtmScript);
|
|
}
|
|
|
|
// 2. Google Analytics 4 (ensures GA4 hits fire directly even if GTM container lacks GA4 config tag)
|
|
if (gaId) {
|
|
window.dataLayer = window.dataLayer || [];
|
|
function gtag(..._args: any[]) {
|
|
// gtag.js consumes the native Arguments object, not an ES6 rest array.
|
|
// valueOf returns that same object without converting the vendor payload.
|
|
window.dataLayer?.push(arguments.valueOf());
|
|
}
|
|
window.gtag = gtag;
|
|
gtag('js', new Date());
|
|
gtag('config', gaId, { send_page_view: false, page_title: '', page_location: window.location.origin + catalogRoute(pathnameRef.current || '/'), page_referrer: '' });
|
|
|
|
// Only append gtag.js script if not already added
|
|
if (!document.querySelector(`script[src*="${gaId}"]`)) {
|
|
const gaScript = document.createElement('script');
|
|
gaScript.async = true;
|
|
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
|
|
document.head.appendChild(gaScript);
|
|
}
|
|
}
|
|
|
|
// 3. Microsoft Clarity
|
|
if (clarityId) {
|
|
(function (c: any, l: any, a: any, r: any, i: any) {
|
|
c[a] =
|
|
c[a] ||
|
|
function (...args: unknown[]) {
|
|
(c[a].q = c[a].q || []).push(args);
|
|
};
|
|
const t = l.createElement(r);
|
|
t.async = 1;
|
|
t.src = 'https://www.clarity.ms/tag/' + i;
|
|
const y = l.getElementsByTagName(r)[0];
|
|
if (y?.parentNode) y.parentNode.insertBefore(t, y);
|
|
else l.head.appendChild(t);
|
|
})(window, document, 'clarity', 'script', clarityId);
|
|
}
|
|
if (pathnameRef.current) recordView(pathnameRef.current);
|
|
};
|
|
|
|
const onClick = (event: MouseEvent) => {
|
|
if (!loadedRef.current || !analyticsAllowed(navigator, window)) return;
|
|
const anchor = event.target instanceof Element ? event.target.closest('a') : null;
|
|
if (anchor instanceof HTMLAnchorElement) trackCatalogClick(event, anchor, pathnameRef.current || '/', emit);
|
|
};
|
|
document.addEventListener('click', onClick);
|
|
|
|
// Listen to first user interaction
|
|
window.addEventListener('scroll', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('touchstart', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('mousemove', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('keydown', loadAnalytics, { passive: true, once: true });
|
|
|
|
// Fallback: idle execution after 3.5s
|
|
let idleId: number | undefined;
|
|
const timer = setTimeout(() => {
|
|
if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
|
|
idleId = window.requestIdleCallback(loadAnalytics, { timeout: 2000 });
|
|
} else {
|
|
loadAnalytics();
|
|
}
|
|
}, 3500);
|
|
|
|
return () => {
|
|
loaded = true;
|
|
loadedRef.current = false;
|
|
lastPathRef.current = null;
|
|
document.removeEventListener('click', onClick);
|
|
clearTimeout(timer);
|
|
if (idleId !== undefined) window.cancelIdleCallback(idleId);
|
|
window.removeEventListener('scroll', loadAnalytics);
|
|
window.removeEventListener('touchstart', loadAnalytics);
|
|
window.removeEventListener('mousemove', loadAnalytics);
|
|
window.removeEventListener('keydown', loadAnalytics);
|
|
};
|
|
}, [gtmId, gaId, clarityId, emit, recordView]);
|
|
|
|
return null;
|
|
}
|