feat(analytics): instrument privacy-minimized catalog navigation

This commit is contained in:
Canina Automation committed 2026-10-28 07:59:35 +00:00
1 parent c62d9836e9
commit 13dc74807a
8 files changed
+145 -32

No files matched your search

@@ -1,10 +1,12 @@
'use client';
import { useEffect, useRef } from 'react';
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;
@@ -20,42 +22,36 @@ interface AnalyticsDeferredProps {
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
const pathname = usePathname();
const loadedRef = useRef(false);
const initialPathRef = useRef<string | null>(null);
const lastPathRef = useRef<string | null>(null);
const pathnameRef = useRef(pathname);
useEffect(() => { pathnameRef.current = pathname; }, [pathname]);
useEffect(() => {
if (!initialPathRef.current && pathname) {
initialPathRef.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;
if (pathname === initialPathRef.current) return;
// 1. Google Analytics 4 page_view event on client navigation
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
window.gtag('event', 'page_view', {
page_path: pathname,
page_location: window.location.href,
page_title: typeof document !== 'undefined' ? document.title : '',
});
}
// 2. Google Tag Manager page_view event on client navigation
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
window.dataLayer.push({
event: 'page_view',
page_path: pathname,
});
}
}, [pathname, gaId, gtmId]);
recordView(pathname);
}, [pathname, recordView]);
useEffect(() => {
let loaded = false;
const loadAnalytics = () => {
if (loaded) return;
if (loaded || !analyticsAllowed(navigator, window)) return;
loaded = true;
loadedRef.current = true;
@@ -85,7 +81,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', gaId, { page_path: window.location.pathname });
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}"]`)) {
@@ -112,8 +108,16 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
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 });
@@ -133,6 +137,8 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
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);
@@ -140,7 +146,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
window.removeEventListener('mousemove', loadAnalytics);
window.removeEventListener('keydown', loadAnalytics);
};
}, [gtmId, gaId, clarityId]);
}, [gtmId, gaId, clarityId, emit, recordView]);
return null;
}
@@ -54,14 +54,19 @@ it('tracks client-side route changes when pathname changes',()=>{
mockPathname = '/blog/test-article';
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view' && entry.page_path === '/blog/test-article');
expect(gtmPageView).toBeDefined();
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view');
expect(gtmPageView).toBeUndefined(); // direct GA is the single first-party owner
mockPathname = '/';
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
const views = window.dataLayer?.filter(entry => entry[0] === 'event' && entry[1] === 'page_view');
expect(views?.map(entry => entry[2].page_path)).toEqual(['/','/blog/[slug]','/']);
expect(views?.every(entry => !('page_title' in entry[2]) && !entry[2].page_location.includes('?'))).toBe(true);
const gaPageView = window.dataLayer?.find(entry => {
return Object.prototype.toString.call(entry) === '[object Arguments]' && entry[0] === 'event' && entry[1] === 'page_view';
});
expect(gaPageView).toBeDefined();
expect(gaPageView[2].page_path).toBe('/blog/test-article');
expect(gaPageView[2].page_path).toBe('/');
});
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{
@@ -115,6 +120,32 @@ it('cancels idle work on unmount',()=>{
expect(cancelIdleCallback).toHaveBeenCalledWith(9);
});
it('honors opt-out before loading and after initialization',()=>{
window.globalPrivacyControl=true;
const v=render(<AnalyticsDeferred gaId="G-test"/>);
fireEvent.scroll(window);
expect(document.scripts).toHaveLength(0);
delete window.globalPrivacyControl;
fireEvent.keyDown(window);
const count=window.dataLayer?.length;
window.globalPrivacyControl=true;
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
expect(window.dataLayer).toHaveLength(count!);
delete window.globalPrivacyControl;
});
it('tracks catalog views and actual enabled contact anchors without commerce events',()=>{
mockPathname='/shop/joint';
const v=render(<AnalyticsDeferred gaId="G-test"/>);
fireEvent.scroll(window);
const a=document.createElement('a');a.href='tel:private';document.body.append(a);
fireEvent.click(a);a.remove();
expect(window.dataLayer?.filter(e=>e[0]==='event').map(e=>e[1])).toEqual(['page_view','catalog_product_view','contact_intent']);
expect(window.dataLayer?.some(e=>e[0]==='config' && e[2].send_page_view===false)).toBe(true);
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
expect(window.dataLayer?.filter(e=>e[1]==='catalog_product_view')).toHaveLength(1);
});
it('unmount removes event and timeout callbacks',()=>{
const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);
v.unmount();
@@ -0,0 +1,21 @@
import {describe,it,expect,vi} from 'vitest';
import {catalogRoute, analyticsAllowed, trackCatalogClick} from '../catalogAnalytics';
describe('catalog analytics privacy and intent',()=>{
it('uses bounded public route templates without identifiers or private URLs',()=>{
expect(catalogRoute('/shop/joint')).toBe('/shop/[slug]');
expect(catalogRoute('/blog/article')).toBe('/blog/[slug]');
expect(catalogRoute('/dashboard/orders/secret')).toBe('/other');
});
it('respects browser privacy signals',()=>{expect(analyticsAllowed({doNotTrack:'1'},{})).toBe(false);expect(analyticsAllowed({}, {globalPrivacyControl:true})).toBe(false);});
it('records article to product intent without href, title, query or contact data',()=>{
const emit=vi.fn(); const a=document.createElement('a');a.href='/shop/joint?email=private#phone';a.textContent='private';
trackCatalogClick(new MouseEvent('click'),a,'/blog/article',emit);
expect(emit).toHaveBeenCalledExactlyOnceWith('internal_navigation',{source_route:'/blog/[slug]',target_route:'/shop/[slug]'});
});
it('records actual contact anchors but never contact value or external navigation',()=>{
const emit=vi.fn();const a=document.createElement('a');a.href='tel:private';trackCatalogClick(new MouseEvent('click'),a,'/shop/joint',emit);
expect(emit).toHaveBeenCalledExactlyOnceWith('contact_intent',{source_route:'/shop/[slug]',contact_type:'phone'});
emit.mockClear();a.href='https://external.test';trackCatalogClick(new MouseEvent('click'),a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();
});
it('ignores cancelled, modified, and non-primary clicks',()=>{const emit=vi.fn();const a=document.createElement('a');a.href='/shop/a';for(const event of [new MouseEvent('click',{ctrlKey:true}),new MouseEvent('click',{button:1})]) trackCatalogClick(event,a,'/blog/a',emit);const event=new MouseEvent('click',{cancelable:true});event.preventDefault();trackCatalogClick(event,a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();});
});
@@ -0,0 +1,27 @@
// Only bounded route classes leave the browser; never arbitrary paths or contact values.
export function catalogRoute(path: string): string {
if (/^\/(shop|blog|wiki)\/[^/]+\/?$/.test(path)) return `/${path.split('/')[1]}/[slug]`;
return ['/', '/shop', '/blog', '/wiki', '/catalog', '/about', '/contact', '/videos'].includes(path) ? path : '/other';
}
export function analyticsAllowed(nav: { doNotTrack?: string | null; globalPrivacyControl?: boolean }, browser: { globalPrivacyControl?: boolean }): boolean {
return nav.doNotTrack !== '1' && !nav.globalPrivacyControl && !browser.globalPrivacyControl;
}
export type CatalogEmitter = (event: string, params: Record<string, string>) => void;
export function trackCatalogClick(event: MouseEvent, anchor: HTMLAnchorElement, source: string, emit: CatalogEmitter): void {
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || anchor.hasAttribute('download')) return;
const url = new URL(anchor.href, window.location.origin);
const source_route = catalogRoute(source);
if (url.protocol === 'tel:' || url.protocol === 'mailto:') {
emit('contact_intent', { source_route, contact_type: url.protocol === 'tel:' ? 'phone' : 'email' });
return;
}
if (url.origin !== window.location.origin || !['http:', 'https:'].includes(url.protocol)) return;
const target_route = catalogRoute(url.pathname);
if (target_route === '/other' || url.pathname === source) return;
if (!['/blog/[slug]', '/wiki/[slug]', '/shop/[slug]'].includes(source_route) && target_route !== '/contact') return;
emit(target_route === '/contact' ? 'contact_intent' : 'internal_navigation', target_route === '/contact'
? { source_route, contact_type: 'contact_page' } : { source_route, target_route });
}