tracking.ts
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { useDeferredEffect } from '../hooks/useDeferredEffect';
import { reportPageView, reportAnalyticsEvents, type PageType, type DeviceType, type AnalyticsEvent } from './analytics';
const SESSION_ID_KEY = 'analytics_session_id';
export function getSessionId(): string {
const existingId = sessionStorage.getItem(SESSION_ID_KEY);
if (existingId) {
return existingId;
}
const newId = generateSessionId();
sessionStorage.setItem(SESSION_ID_KEY, newId);
return newId;
}
function generateSessionId(): string {
const timestamp = Date.now().toString(36);
const randomPart = Math.random().toString(36).substring(2, 10);
return `${timestamp}-${randomPart}`;
}
export function getDeviceType(): DeviceType {
const width = window.innerWidth;
if (width >= 1024) {
return 'desktop';
}
if (width >= 768) {
return 'tablet';
}
return 'mobile';
}
interface TrackPageViewOptions {
loaded: boolean;
}
export function useTrackPageView(pageType: PageType, options: TrackPageViewOptions): void {
useDeferredEffect(() => {
if (!options.loaded) {
return;
}
const sessionId = getSessionId();
const deviceType = getDeviceType();
reportPageView({
page_type: pageType,
session_id: sessionId,
device_type: deviceType,
}).catch(() => {
// Silent failure - analytics errors should not affect user workflows
});
}, [pageType, options.loaded]);
}
export async function trackCustomEvent(...events: AnalyticsEvent[]): Promise<void> {
try {
await reportAnalyticsEvents(events);
} catch {
// Silent failure - analytics errors should not affect user workflows
}
}