|
| 1 | +import { NextRouter } from "next/router"; |
| 2 | +import ReactGA from "react-ga4"; |
| 3 | + |
| 4 | +const GA_SESSION_ID = "ga_session_id"; |
| 5 | +const GA_MEASUREMENT_ID = "G-HZEXJ323ZF"; |
| 6 | + |
| 7 | +// Add a global flag to window object |
| 8 | +declare global { |
| 9 | + interface Window { |
| 10 | + __GA_INITIALIZED__?: boolean; |
| 11 | + gtag?: (...args: any[]) => void; // Declare gtag for direct access check |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +export const isGaInitialized = (): boolean => { |
| 16 | + return typeof window !== "undefined" && !!window.__GA_INITIALIZED__; |
| 17 | +}; |
| 18 | + |
| 19 | +function isDebugMode() { |
| 20 | + return ( |
| 21 | + typeof window !== "undefined" && |
| 22 | + window.location.search.includes("debug_mode=true") |
| 23 | + ); |
| 24 | +} |
| 25 | + |
| 26 | +function isProdEnv() { |
| 27 | + return ( |
| 28 | + typeof window !== "undefined" && |
| 29 | + window.location.href.startsWith("https://hud.pytorch.org") |
| 30 | + ); |
| 31 | +} |
| 32 | + |
| 33 | +function isGAEnabled(): boolean { |
| 34 | + if (typeof window === "undefined") return false; |
| 35 | + return isDebugMode() || isProdEnv(); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * initialize google analytics |
| 40 | + * if withUserId is set, we generate random sessionId to track action sequence for a single page flow. |
| 41 | + * Notice, we use session storage, if user create a new page tab due to navigation, it's considered new session |
| 42 | + * @param withUserId |
| 43 | + * @returns |
| 44 | + */ |
| 45 | +export const initGaAnalytics = (withSessionId = false) => { |
| 46 | + // Block in non-production deployments unless the debug_mode is set to true in url. |
| 47 | + if (!isGAEnabled()) { |
| 48 | + console.info("[GA] Skipping GA init"); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + if (isGaInitialized()) { |
| 53 | + console.log("ReactGA already initialized."); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + ReactGA.initialize(GA_MEASUREMENT_ID, { |
| 58 | + // For enabling debug mode for GA4, the primary option is `debug: true` |
| 59 | + // passed directly to ReactGA.initialize. |
| 60 | + // The `gaOptions` and `gtagOptions` are for more advanced configurations |
| 61 | + // directly passed to the underlying GA/Gtag library. |
| 62 | + // @ts-ignore |
| 63 | + debug: isDebugMode(), |
| 64 | + gaOptions: { |
| 65 | + debug_mode: isDebugMode(), |
| 66 | + }, |
| 67 | + gtagOptions: { |
| 68 | + debug_mode: isDebugMode(), |
| 69 | + cookie_domain: isDebugMode() ? "none" : "auto", |
| 70 | + }, |
| 71 | + }); |
| 72 | + |
| 73 | + window.__GA_INITIALIZED__ = true; // Set a global flag |
| 74 | + |
| 75 | + // generate random userId in session storage. |
| 76 | + if (withSessionId) { |
| 77 | + let id = sessionStorage.getItem(GA_SESSION_ID); |
| 78 | + if (!id) { |
| 79 | + id = crypto.randomUUID(); |
| 80 | + sessionStorage.setItem(GA_SESSION_ID, id); |
| 81 | + } |
| 82 | + ReactGA.set({ user_id: id }); |
| 83 | + } |
| 84 | +}; |
| 85 | + |
| 86 | +export function trackRouteEvent( |
| 87 | + router: NextRouter, |
| 88 | + eventName: string, |
| 89 | + info: Record<string, any> = {} |
| 90 | +) { |
| 91 | + if (!isGAEnabled()) { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + const payload = { |
| 96 | + ...info, |
| 97 | + url: window.location.href, |
| 98 | + windowPathname: window.location.pathname, |
| 99 | + routerPathname: router.pathname, |
| 100 | + routerPath: router.asPath, |
| 101 | + ...(isDebugMode() ? { debug_mode: true } : {}), |
| 102 | + }; |
| 103 | + |
| 104 | + ReactGA.event(eventName.toLowerCase(), payload); |
| 105 | +} |
| 106 | + |
| 107 | +/** |
| 108 | + * track event with context using QA |
| 109 | + * @param action |
| 110 | + * @param category |
| 111 | + * @param label |
| 112 | + * @param extra |
| 113 | + * @returns |
| 114 | + */ |
| 115 | +export function trackEventWithContext( |
| 116 | + action: string, |
| 117 | + category?: string, |
| 118 | + label?: string, |
| 119 | + extra?: Record<string, any> |
| 120 | +) { |
| 121 | + if (!isGAEnabled()) { |
| 122 | + return; |
| 123 | + } |
| 124 | + const payload = { |
| 125 | + category, |
| 126 | + label, |
| 127 | + event_time: new Date().toISOString(), |
| 128 | + page_title: document.title, |
| 129 | + session_id: sessionStorage.getItem(GA_SESSION_ID) ?? undefined, |
| 130 | + |
| 131 | + ...(isDebugMode() ? { debug_mode: true } : {}), |
| 132 | + }; |
| 133 | + ReactGA.event(action, payload); |
| 134 | +} |
0 commit comments