|
| 1 | +import { APP_CONFIG } from "@/constants/app"; |
| 2 | +import { tools } from "@/constants/tools"; |
| 3 | +import { isTauri } from "@/utils/isTauri"; |
| 4 | +import { useEffect, useRef } from "react"; |
| 5 | +import { useLocation } from "react-router-dom"; |
| 6 | + |
| 7 | +function uuidv4() { |
| 8 | + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => { |
| 9 | + const r = (Math.random() * 16) | 0; |
| 10 | + const v = c === "x" ? r : (r & 0x3) | 0x8; |
| 11 | + return v.toString(16); |
| 12 | + }); |
| 13 | +} |
| 14 | + |
| 15 | +function getClientId(): string { |
| 16 | + try { |
| 17 | + const key = "devbox:ga_cid"; |
| 18 | + const existing = localStorage.getItem(key); |
| 19 | + if (existing) return existing; |
| 20 | + const cid = uuidv4(); |
| 21 | + localStorage.setItem(key, cid); |
| 22 | + return cid; |
| 23 | + } catch { |
| 24 | + return uuidv4(); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +declare global { |
| 29 | + interface Window { |
| 30 | + dataLayer?: any[]; |
| 31 | + gtag?: (...args: any[]) => void; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export function useAnalytics() { |
| 36 | + const location = useLocation(); |
| 37 | + const readyRef = useRef(false); |
| 38 | + const lastPathRef = useRef<string>(""); |
| 39 | + const measurementId = APP_CONFIG.GA.MEASUREMENT_ID; |
| 40 | + const FORCE_BEACON = APP_CONFIG.GA.FORCE_BEACON === "1"; |
| 41 | + const DEBUG = APP_CONFIG.GA.DEBUG === "1"; |
| 42 | + const sessionIdRef = useRef<number>(Math.floor(Date.now() / 1000)); |
| 43 | + const sessionCountRef = useRef<number>(1); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + if (!measurementId || readyRef.current) return; |
| 47 | + if (!window.dataLayer) window.dataLayer = []; |
| 48 | + window.gtag = function gtag() { |
| 49 | + window.dataLayer!.push(arguments as any); |
| 50 | + }; |
| 51 | + |
| 52 | + const script = document.createElement("script"); |
| 53 | + script.async = true; |
| 54 | + script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`; |
| 55 | + script.onload = () => { |
| 56 | + const platform = isTauri() ? "devbox_app" : "webapp"; |
| 57 | + window.gtag!("js", new Date()); |
| 58 | + window.gtag!("config", measurementId, { |
| 59 | + send_page_view: false, |
| 60 | + app_name: "Devbox", |
| 61 | + platform, |
| 62 | + }); |
| 63 | + readyRef.current = true; |
| 64 | + console.log("GA manual initialized", { measurementId, platform, FORCE_BEACON, DEBUG }); |
| 65 | + sendPageView(location.pathname, true); |
| 66 | + }; |
| 67 | + script.onerror = () => console.warn("GA script failed to load"); |
| 68 | + document.head.appendChild(script); |
| 69 | + }, [measurementId]); |
| 70 | + |
| 71 | + useEffect(() => { |
| 72 | + if (!readyRef.current) return; |
| 73 | + sendPageView(location.pathname); |
| 74 | + }, [location.pathname]); |
| 75 | + |
| 76 | + function sendPageView(path: string, initial = false) { |
| 77 | + if (!measurementId) return; |
| 78 | + if (lastPathRef.current === path && !initial) return; |
| 79 | + lastPathRef.current = path; |
| 80 | + const cid = getClientId(); |
| 81 | + let appName = tools.find(tool => tool.path === path)?.text; |
| 82 | + if (path === "/dashboard") { |
| 83 | + appName = "Dashboard"; |
| 84 | + } else if (path === "/settings") { |
| 85 | + appName = "Settings"; |
| 86 | + } |
| 87 | + |
| 88 | + const pageLocation = isTauri() ? `tauri:/${path}` : window.location.href; |
| 89 | + const params: Record<string, any> = { |
| 90 | + page_location: pageLocation, |
| 91 | + page_path: path, |
| 92 | + page_title: appName || path, |
| 93 | + sid: sessionIdRef.current, |
| 94 | + sct: sessionCountRef.current, |
| 95 | + debug_mode: DEBUG ? 1 : undefined, |
| 96 | + }; |
| 97 | + try { |
| 98 | + window.gtag && window.gtag("event", "page_view", params); |
| 99 | + console.debug("GA page_view", params); |
| 100 | + if (FORCE_BEACON) { |
| 101 | + beaconFallback(measurementId, params, cid, true); |
| 102 | + } |
| 103 | + } catch (e) { |
| 104 | + console.warn("GA gtag send failed, fallback", e); |
| 105 | + beaconFallback(measurementId, params, cid, true); |
| 106 | + } |
| 107 | + |
| 108 | + // If running under a non-http(s) custom protocol (tauri:// / asset://), CORS blocks fetch/Beacon. |
| 109 | + // Always send an image pixel which bypasses CORS preflight. |
| 110 | + if (!/^https?:/.test(window.location.protocol)) { |
| 111 | + imageFallback(measurementId, params, cid, DEBUG); |
| 112 | + } |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +function beaconFallback(id: string, params: Record<string, any>, cid: string, verbose = false) { |
| 117 | + try { |
| 118 | + const endpoint = "https://www.google-analytics.com/g/collect"; |
| 119 | + const raw: Record<string, string | undefined> = { |
| 120 | + v: "2", |
| 121 | + tid: id, |
| 122 | + cid, |
| 123 | + en: "page_view", |
| 124 | + dl: String(params.page_location || ""), |
| 125 | + dt: String(params.page_title || ""), |
| 126 | + sid: params.sid?.toString() || Math.floor(Date.now() / 1000).toString(), |
| 127 | + sct: params.sct?.toString() || "1", |
| 128 | + _dbg: params.debug_mode ? "1" : undefined, |
| 129 | + }; |
| 130 | + const filtered = Object.fromEntries( |
| 131 | + Object.entries(raw).filter(([, v]) => typeof v === "string" && v.length > 0) |
| 132 | + ) as Record<string, string>; |
| 133 | + const search = new URLSearchParams(filtered); |
| 134 | + const url = `${endpoint}?${search.toString()}`; |
| 135 | + if (navigator.sendBeacon) navigator.sendBeacon(url); |
| 136 | + else fetch(url, { method: "GET", mode: "no-cors" }).catch(() => {}); |
| 137 | + if (verbose) console.debug("GA beacon sent", url); |
| 138 | + } catch (e) { |
| 139 | + console.warn("GA beacon fallback failed", e); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +function imageFallback(id: string, params: Record<string, any>, cid: string, debug = false) { |
| 144 | + try { |
| 145 | + const endpoint = "https://www.google-analytics.com/g/collect"; |
| 146 | + const data: Record<string, string> = { |
| 147 | + v: "2", |
| 148 | + tid: id, |
| 149 | + cid, |
| 150 | + en: "page_view", |
| 151 | + dl: String(params.page_location || ""), |
| 152 | + dt: String(params.page_title || ""), |
| 153 | + sid: (params.sid || Math.floor(Date.now() / 1000)).toString(), |
| 154 | + sct: (params.sct || 1).toString(), |
| 155 | + _r: "1", |
| 156 | + _s: "1", |
| 157 | + _et: "0", |
| 158 | + }; |
| 159 | + if (debug) data._dbg = "1"; |
| 160 | + const qs = new URLSearchParams(data).toString(); |
| 161 | + const img = new Image(); |
| 162 | + img.referrerPolicy = "no-referrer"; |
| 163 | + img.src = `${endpoint}?${qs}&z=${Math.random().toString(36).slice(2)}`; |
| 164 | + if (debug) console.debug("GA image fallback sent", img.src); |
| 165 | + } catch (e) { |
| 166 | + console.warn("GA image fallback failed", e); |
| 167 | + } |
| 168 | +} |
0 commit comments