@temps-sdk/react-analytics 0.0.1-beta.2 → 0.0.1-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,348 @@
1
+ "use client";
2
+ import { useEffect, useRef, useCallback, useState } from "react";
3
+ import { record } from "rrweb";
4
+ import { pack } from "@rrweb/packer";
5
+ import { sendAnalytics, sendAnalyticsReliable, getRequestId } from "./utils";
6
+ export const SESSION_RECORDER_ENDPOINT = "session-replay";
7
+ function generateSessionId() {
8
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
9
+ return crypto.randomUUID();
10
+ }
11
+ return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
12
+ }
13
+ function generateVisitorId() {
14
+ // Try to get a persistent visitor ID from localStorage
15
+ if (typeof localStorage !== "undefined") {
16
+ let visitorId = localStorage.getItem("temps_visitor_id");
17
+ if (!visitorId) {
18
+ visitorId = `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
19
+ localStorage.setItem("temps_visitor_id", visitorId);
20
+ }
21
+ return visitorId;
22
+ }
23
+ return `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
24
+ }
25
+ function getSessionMetadata(domain) {
26
+ if (typeof window === "undefined")
27
+ return {};
28
+ const screen = window.screen || {};
29
+ const navigator = window.navigator || {};
30
+ return {
31
+ visitor_id: generateVisitorId(),
32
+ domain: domain || window.location.hostname,
33
+ request_path: window.location.pathname,
34
+ request_query: window.location.search,
35
+ referrer: document.referrer,
36
+ user_agent: navigator.userAgent,
37
+ screen_width: screen.width,
38
+ screen_height: screen.height,
39
+ viewport_width: window.innerWidth,
40
+ viewport_height: window.innerHeight,
41
+ device_pixel_ratio: window.devicePixelRatio || 1,
42
+ language: navigator.language,
43
+ platform: navigator.platform,
44
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
45
+ started_at: new Date().toISOString(),
46
+ };
47
+ }
48
+ export function SessionRecorder({ basePath = "/_temps", domain, enabled = false, excludedPaths = [], sessionSampleRate = 1.0, maskAllInputs = true, maskTextSelector = "[data-mask]", blockClass = "rr-block", ignoreClass = "rr-ignore", maskTextClass = "rr-mask", recordCanvas = false, collectFonts = false, slimDOMOptions = {
49
+ script: false,
50
+ comment: false,
51
+ headFavicon: false,
52
+ headWhitespace: false,
53
+ headMetaSocial: false,
54
+ headMetaRobots: false,
55
+ headMetaHttpEquiv: false,
56
+ headMetaVerification: false,
57
+ headMetaDescKeywords: false
58
+ }, batchSize = 100, flushInterval = 5000, }) {
59
+ const stopFnRef = useRef(null);
60
+ const eventsRef = useRef([]);
61
+ const sessionIdRef = useRef("");
62
+ const sessionInitializedRef = useRef(false);
63
+ const flushTimeoutRef = useRef(null);
64
+ const initRetryCountRef = useRef(0);
65
+ const maxInitRetries = 3;
66
+ const [isInitializing, setIsInitializing] = useState(false);
67
+ const shouldRecord = useCallback(() => {
68
+ if (!enabled)
69
+ return false;
70
+ if (typeof window === "undefined")
71
+ return false;
72
+ // Check if current path should be excluded
73
+ const currentPath = window.location.pathname;
74
+ const isExcluded = excludedPaths.some(path => {
75
+ // Support wildcards in path patterns
76
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
77
+ return regex.test(currentPath);
78
+ });
79
+ if (isExcluded)
80
+ return false;
81
+ // Apply sampling rate
82
+ if (sessionSampleRate < 1.0) {
83
+ const random = Math.random();
84
+ if (random > sessionSampleRate)
85
+ return false;
86
+ }
87
+ return true;
88
+ }, [enabled, excludedPaths, sessionSampleRate]);
89
+ const initializeSession = useCallback(async () => {
90
+ if (sessionInitializedRef.current || isInitializing)
91
+ return sessionInitializedRef.current;
92
+ // Check if we've exceeded retry limit
93
+ if (initRetryCountRef.current >= maxInitRetries) {
94
+ console.error("[SessionRecorder] Exceeded maximum initialization retries");
95
+ return false;
96
+ }
97
+ setIsInitializing(true);
98
+ initRetryCountRef.current++;
99
+ const sessionId = generateSessionId();
100
+ sessionIdRef.current = sessionId;
101
+ try {
102
+ const metadata = {
103
+ session_id: sessionId,
104
+ ...getSessionMetadata(domain),
105
+ };
106
+ const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
107
+ method: "POST",
108
+ headers: {
109
+ "Content-Type": "application/json",
110
+ },
111
+ body: JSON.stringify(metadata),
112
+ });
113
+ if (response.status === 201) {
114
+ sessionInitializedRef.current = true;
115
+ initRetryCountRef.current = 0; // Reset retry count on success
116
+ // Store session ID in localStorage for reference
117
+ if (typeof localStorage !== "undefined") {
118
+ localStorage.setItem("currentRecordingSessionId", sessionId);
119
+ }
120
+ console.log("[SessionRecorder] Session initialized successfully:", sessionId);
121
+ return true;
122
+ }
123
+ else {
124
+ console.error("[SessionRecorder] Failed to initialize session:", response.status);
125
+ sessionIdRef.current = ""; // Clear invalid session ID
126
+ return false;
127
+ }
128
+ }
129
+ catch (error) {
130
+ console.error("[SessionRecorder] Failed to initialize session:", error);
131
+ sessionIdRef.current = ""; // Clear invalid session ID
132
+ return false;
133
+ }
134
+ finally {
135
+ setIsInitializing(false);
136
+ }
137
+ }, [basePath, domain, isInitializing]);
138
+ const sendEvents = useCallback(async (isReliable = false) => {
139
+ if (!sessionInitializedRef.current) {
140
+ console.warn("[SessionRecorder] Cannot send events - session not initialized");
141
+ return;
142
+ }
143
+ const events = eventsRef.current;
144
+ if (events.length === 0)
145
+ return;
146
+ const eventsToSend = [...events];
147
+ eventsRef.current = [];
148
+ try {
149
+ // Pack the events for more efficient transmission
150
+ const packedEvents = pack(eventsToSend);
151
+ // Base64 encode the packed string for safe JSON transmission
152
+ const encodedEvents = btoa(packedEvents);
153
+ const payload = {
154
+ session_id: sessionIdRef.current,
155
+ events: encodedEvents,
156
+ };
157
+ const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
158
+ if (isReliable) {
159
+ // Use sendBeacon for reliable sending on page unload
160
+ if (navigator.sendBeacon) {
161
+ const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
162
+ const sent = navigator.sendBeacon(url, blob);
163
+ if (!sent) {
164
+ // Fallback to fetch with keepalive
165
+ await fetch(url, {
166
+ method: "POST",
167
+ headers: { "Content-Type": "application/json" },
168
+ body: JSON.stringify(payload),
169
+ keepalive: true,
170
+ });
171
+ }
172
+ }
173
+ else {
174
+ // Fallback to fetch with keepalive
175
+ await fetch(url, {
176
+ method: "POST",
177
+ headers: { "Content-Type": "application/json" },
178
+ body: JSON.stringify(payload),
179
+ keepalive: true,
180
+ });
181
+ }
182
+ }
183
+ else {
184
+ const response = await fetch(url, {
185
+ method: "POST",
186
+ headers: { "Content-Type": "application/json" },
187
+ body: JSON.stringify(payload),
188
+ });
189
+ if (response.status === 404) {
190
+ // Session not found, mark as not initialized but don't auto-reinitialize
191
+ console.error("[SessionRecorder] Session not found on server, stopping recording");
192
+ sessionInitializedRef.current = false;
193
+ sessionIdRef.current = "";
194
+ // Clear the session from localStorage
195
+ if (typeof localStorage !== "undefined") {
196
+ localStorage.removeItem("currentRecordingSessionId");
197
+ }
198
+ // Stop recording to prevent further errors
199
+ if (stopFnRef.current) {
200
+ stopFnRef.current();
201
+ stopFnRef.current = null;
202
+ }
203
+ // Don't restore events - they're lost
204
+ }
205
+ else if (!response.ok) {
206
+ console.error("[SessionRecorder] Failed to send events:", response.status);
207
+ // Restore events on failure
208
+ eventsRef.current.unshift(...eventsToSend);
209
+ }
210
+ }
211
+ }
212
+ catch (error) {
213
+ console.error("[SessionRecorder] Failed to send session events:", error);
214
+ // Restore events on failure
215
+ eventsRef.current.unshift(...eventsToSend);
216
+ }
217
+ }, [basePath, initializeSession]);
218
+ const scheduleFlush = useCallback(() => {
219
+ if (flushTimeoutRef.current) {
220
+ clearTimeout(flushTimeoutRef.current);
221
+ }
222
+ flushTimeoutRef.current = setTimeout(() => {
223
+ sendEvents(false);
224
+ }, flushInterval);
225
+ }, [sendEvents, flushInterval]);
226
+ const startRecording = useCallback(async () => {
227
+ if (stopFnRef.current)
228
+ return; // Already recording
229
+ if (!shouldRecord())
230
+ return;
231
+ // Reset retry counter for new recording session
232
+ if (!sessionInitializedRef.current) {
233
+ initRetryCountRef.current = 0;
234
+ }
235
+ // Initialize session first
236
+ const initialized = await initializeSession();
237
+ if (!initialized) {
238
+ console.error("[SessionRecorder] Failed to initialize session, not starting recording");
239
+ return;
240
+ }
241
+ eventsRef.current = [];
242
+ const stopFn = record({
243
+ emit(event) {
244
+ eventsRef.current.push(event);
245
+ // Batch send when we reach the batch size
246
+ if (eventsRef.current.length >= batchSize) {
247
+ sendEvents(false);
248
+ scheduleFlush();
249
+ }
250
+ },
251
+ sampling: {
252
+ scroll: 150,
253
+ media: 800,
254
+ input: "last"
255
+ },
256
+ recordCanvas,
257
+ collectFonts,
258
+ maskAllInputs,
259
+ maskTextSelector,
260
+ blockClass,
261
+ ignoreClass,
262
+ maskTextClass,
263
+ slimDOMOptions,
264
+ });
265
+ if (stopFn) {
266
+ stopFnRef.current = stopFn;
267
+ }
268
+ // Start the flush interval
269
+ scheduleFlush();
270
+ }, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
271
+ const stopRecording = useCallback(() => {
272
+ if (stopFnRef.current) {
273
+ stopFnRef.current();
274
+ stopFnRef.current = null;
275
+ // Clear flush timeout
276
+ if (flushTimeoutRef.current) {
277
+ clearTimeout(flushTimeoutRef.current);
278
+ flushTimeoutRef.current = null;
279
+ }
280
+ // Send any remaining events reliably
281
+ sendEvents(true);
282
+ // Clear session state
283
+ sessionInitializedRef.current = false;
284
+ sessionIdRef.current = "";
285
+ // Clear session ID from localStorage
286
+ if (typeof localStorage !== "undefined") {
287
+ localStorage.removeItem("currentRecordingSessionId");
288
+ }
289
+ }
290
+ }, [sendEvents]);
291
+ // Effect to handle recording lifecycle
292
+ useEffect(() => {
293
+ if (!shouldRecord()) {
294
+ stopRecording();
295
+ return;
296
+ }
297
+ startRecording();
298
+ // Handle page unload
299
+ const handleUnload = () => {
300
+ sendEvents(true);
301
+ };
302
+ window.addEventListener("beforeunload", handleUnload);
303
+ window.addEventListener("pagehide", handleUnload);
304
+ return () => {
305
+ stopRecording();
306
+ window.removeEventListener("beforeunload", handleUnload);
307
+ window.removeEventListener("pagehide", handleUnload);
308
+ };
309
+ }, [shouldRecord, startRecording, stopRecording, sendEvents]);
310
+ // Monitor location changes to stop/start recording based on excluded paths
311
+ useEffect(() => {
312
+ const checkPathAndToggleRecording = () => {
313
+ if (!enabled) {
314
+ stopRecording();
315
+ return;
316
+ }
317
+ const currentPath = window.location.pathname;
318
+ const isExcluded = excludedPaths.some(path => {
319
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
320
+ return regex.test(currentPath);
321
+ });
322
+ if (isExcluded && stopFnRef.current) {
323
+ stopRecording();
324
+ }
325
+ else if (!isExcluded && !stopFnRef.current) {
326
+ startRecording();
327
+ }
328
+ };
329
+ // Listen for route changes
330
+ const originalPushState = window.history.pushState;
331
+ const originalReplaceState = window.history.replaceState;
332
+ window.history.pushState = function (...args) {
333
+ originalPushState.apply(window.history, args);
334
+ checkPathAndToggleRecording();
335
+ };
336
+ window.history.replaceState = function (...args) {
337
+ originalReplaceState.apply(window.history, args);
338
+ checkPathAndToggleRecording();
339
+ };
340
+ window.addEventListener("popstate", checkPathAndToggleRecording);
341
+ return () => {
342
+ window.history.pushState = originalPushState;
343
+ window.history.replaceState = originalReplaceState;
344
+ window.removeEventListener("popstate", checkPathAndToggleRecording);
345
+ };
346
+ }, [enabled, excludedPaths, startRecording, stopRecording]);
347
+ return null;
348
+ }
package/dist/index.d.ts CHANGED
@@ -3,4 +3,10 @@ export * from "./Provider";
3
3
  export * from "./useAnalytics";
4
4
  export * from "./useTrackEvent";
5
5
  export * from "./useTrackPageview";
6
+ export * from "./usePageLeave";
7
+ export * from "./useSpeedAnalytics";
8
+ export * from "./useEngagementTracking";
9
+ export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
10
+ export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
11
+ export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
6
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -4,3 +4,9 @@ export * from "./Provider";
4
4
  export * from "./useAnalytics";
5
5
  export * from "./useTrackEvent";
6
6
  export * from "./useTrackPageview";
7
+ export * from "./usePageLeave";
8
+ export * from "./useSpeedAnalytics";
9
+ export * from "./useEngagementTracking";
10
+ export { EngagementTracker } from "./EngagementTracker";
11
+ export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
12
+ export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
package/dist/types.d.ts CHANGED
@@ -10,12 +10,14 @@ export interface AnalyticsEventBase {
10
10
  event_data?: Record<string, JsonValue>;
11
11
  }
12
12
  export interface AnalyticsClientOptions {
13
- /** Base endpoint path. Defaults to `/api/_temps`. */
13
+ /** Base endpoint path. Defaults to `/_temps`. */
14
14
  basePath?: string;
15
15
  /** Set to true to disable analytics (e.g., for tests). */
16
16
  disabled?: boolean;
17
17
  /** Ignore localhost/test env automatically. Defaults to true. */
18
18
  ignoreLocalhost?: boolean;
19
+ /** Custom domain to use for analytics. Defaults to window.location.hostname. */
20
+ domain?: string;
19
21
  }
20
22
  export interface AnalyticsContextValue {
21
23
  /** Send a custom event. */
@@ -30,7 +32,62 @@ export interface AnalyticsContextValue {
30
32
  export interface TempsAnalyticsProviderProps extends AnalyticsClientOptions {
31
33
  /** Auto track pageviews on route changes. Defaults to true. */
32
34
  autoTrackPageviews?: boolean;
35
+ /** Auto track page leave events. Defaults to true. */
36
+ autoTrackPageLeave?: boolean;
37
+ /** Custom event name for page leave events. Defaults to "page_leave". */
38
+ pageLeaveEventName?: string;
39
+ /** Auto track speed analytics (Web Vitals). Defaults to true. */
40
+ autoTrackSpeedAnalytics?: boolean;
41
+ /** Auto track engagement with heartbeats. Defaults to true. */
42
+ autoTrackEngagement?: boolean;
43
+ /** Heartbeat interval in milliseconds. Defaults to 30000 (30 seconds). */
44
+ heartbeatInterval?: number;
45
+ /** Inactivity timeout in milliseconds. Defaults to 30000 (30 seconds). */
46
+ inactivityTimeout?: number;
47
+ /** Engagement threshold in milliseconds to consider session engaged. Defaults to 10000 (10 seconds). */
48
+ engagementThreshold?: number;
49
+ /** Enable session recording. Defaults to false. */
50
+ enableSessionRecording?: boolean;
51
+ /** Session recording configuration. */
52
+ sessionRecordingConfig?: {
53
+ /** Paths to exclude from recording. */
54
+ excludedPaths?: string[];
55
+ /** Sample rate for recording sessions (0.0 to 1.0). Defaults to 1.0. */
56
+ sessionSampleRate?: number;
57
+ /** Mask all inputs. Defaults to true. */
58
+ maskAllInputs?: boolean;
59
+ /** CSS selector for masking text. Defaults to "[data-mask]". */
60
+ maskTextSelector?: string;
61
+ /** CSS class to block from recording. Defaults to "rr-block". */
62
+ blockClass?: string;
63
+ /** CSS class to ignore from recording. Defaults to "rr-ignore". */
64
+ ignoreClass?: string;
65
+ /** CSS class to mask text. Defaults to "rr-mask". */
66
+ maskTextClass?: string;
67
+ /** Record canvas elements. Defaults to false. */
68
+ recordCanvas?: boolean;
69
+ /** Collect fonts. Defaults to false. */
70
+ collectFonts?: boolean;
71
+ /** Number of events to batch before sending. Defaults to 100. */
72
+ batchSize?: number;
73
+ /** Interval in ms to flush events. Defaults to 5000. */
74
+ flushInterval?: number;
75
+ };
33
76
  /** Children to render inside the provider. */
34
77
  children: React.ReactNode;
35
78
  }
79
+ export interface WebVitalMetric {
80
+ value: number;
81
+ rating: "good" | "needs-improvement" | "poor";
82
+ }
83
+ export interface SpeedMetric {
84
+ ttfb?: number | null;
85
+ lcp?: number | null;
86
+ fid?: number | null;
87
+ fcp?: number | null;
88
+ cls?: number | null;
89
+ inp?: number | null;
90
+ path?: string | null;
91
+ query?: string | null;
92
+ }
36
93
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnF,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC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AAI,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB"}
@@ -0,0 +1,34 @@
1
+ import { type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
2
+ export interface UseEngagementTrackingOptions extends Omit<EngagementTrackerOptions, "basePath" | "domain"> {
3
+ /** Whether to enable engagement tracking. Defaults to true. */
4
+ enabled?: boolean;
5
+ /** Callback when engagement data is updated via heartbeat */
6
+ onEngagementUpdate?: (data: EngagementData) => void;
7
+ /** Callback when page leave is triggered */
8
+ onPageLeave?: (data: EngagementData) => void;
9
+ }
10
+ /**
11
+ * Hook to manually control engagement tracking for specific components or pages.
12
+ * This is useful when you want fine-grained control over engagement tracking
13
+ * or need to track engagement for specific sections of your app.
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * function ArticlePage() {
18
+ * const { engagementData } = useEngagementTracking({
19
+ * heartbeatInterval: 15000, // Send heartbeat every 15 seconds
20
+ * engagementThreshold: 5000, // Consider engaged after 5 seconds
21
+ * onEngagementUpdate: (data) => {
22
+ * console.log('Engagement updated:', data);
23
+ * }
24
+ * });
25
+ *
26
+ * return <article>...</article>;
27
+ * }
28
+ * ```
29
+ */
30
+ export declare function useEngagementTracking(options?: UseEngagementTrackingOptions): {
31
+ engagementData: EngagementData;
32
+ isTracking: boolean;
33
+ };
34
+ //# sourceMappingURL=useEngagementTracking.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useEngagementTracking.d.ts","sourceRoot":"","sources":["../src/useEngagementTracking.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5G,MAAM,WAAW,4BAA6B,SAAQ,IAAI,CAAC,wBAAwB,EAAE,UAAU,GAAG,QAAQ,CAAC;IACzG,+DAA+D;IAC/D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,6DAA6D;IAC7D,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACpD,4CAA4C;IAC5C,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,GAAE,4BAAiC;;;EAkD/E"}
@@ -0,0 +1,65 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ import { EngagementTracker } from "./EngagementTracker";
4
+ import { useTempsAnalytics } from "./Provider";
5
+ /**
6
+ * Hook to manually control engagement tracking for specific components or pages.
7
+ * This is useful when you want fine-grained control over engagement tracking
8
+ * or need to track engagement for specific sections of your app.
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * function ArticlePage() {
13
+ * const { engagementData } = useEngagementTracking({
14
+ * heartbeatInterval: 15000, // Send heartbeat every 15 seconds
15
+ * engagementThreshold: 5000, // Consider engaged after 5 seconds
16
+ * onEngagementUpdate: (data) => {
17
+ * console.log('Engagement updated:', data);
18
+ * }
19
+ * });
20
+ *
21
+ * return <article>...</article>;
22
+ * }
23
+ * ```
24
+ */
25
+ export function useEngagementTracking(options = {}) {
26
+ const analytics = useTempsAnalytics();
27
+ const trackerRef = useRef(null);
28
+ const engagementDataRef = useRef({
29
+ engagement_time_seconds: 0,
30
+ total_time_seconds: 0,
31
+ heartbeat_count: 0,
32
+ is_engaged: false,
33
+ is_visible: true,
34
+ time_since_last_activity: 0,
35
+ });
36
+ const { enabled = true, onEngagementUpdate, onPageLeave, ...trackerOptions } = options;
37
+ useEffect(() => {
38
+ if (!enabled || !analytics.enabled) {
39
+ return;
40
+ }
41
+ // Create tracker instance
42
+ trackerRef.current = new EngagementTracker({
43
+ ...trackerOptions,
44
+ onHeartbeat: (data) => {
45
+ engagementDataRef.current = data;
46
+ onEngagementUpdate?.(data);
47
+ },
48
+ onPageLeave: (data) => {
49
+ engagementDataRef.current = data;
50
+ onPageLeave?.(data);
51
+ },
52
+ });
53
+ // Cleanup on unmount
54
+ return () => {
55
+ if (trackerRef.current) {
56
+ trackerRef.current.destroy();
57
+ trackerRef.current = null;
58
+ }
59
+ };
60
+ }, [enabled, analytics.enabled]);
61
+ return {
62
+ engagementData: engagementDataRef.current,
63
+ isTracking: Boolean(trackerRef.current),
64
+ };
65
+ }
@@ -0,0 +1,13 @@
1
+ import type { JsonValue } from "./types";
2
+ export interface UsePageLeaveOptions {
3
+ /** Custom event name. Defaults to "page_leave" */
4
+ eventName?: string;
5
+ /** Additional data to send with the page leave event */
6
+ eventData?: Record<string, JsonValue>;
7
+ /** Whether to enable page leave tracking. Defaults to true */
8
+ enabled?: boolean;
9
+ }
10
+ export declare function usePageLeave(options?: UsePageLeaveOptions): {
11
+ triggerPageLeave: () => Promise<void> | undefined;
12
+ };
13
+ //# sourceMappingURL=usePageLeave.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePageLeave.d.ts","sourceRoot":"","sources":["../src/usePageLeave.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,MAAM,WAAW,mBAAmB;IAClC,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACtC,8DAA8D;IAC9D,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB;;EA2E7D"}
@@ -0,0 +1,65 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ import { useTempsAnalytics } from "./Provider";
4
+ import { sendAnalyticsReliable } from "./utils";
5
+ export function usePageLeave(options = {}) {
6
+ const { eventName = "page_leave", eventData = {}, enabled = true } = options;
7
+ const { enabled: analyticsEnabled, trackEvent } = useTempsAnalytics();
8
+ const hasTrackedRef = useRef(false);
9
+ const startTimeRef = useRef();
10
+ useEffect(() => {
11
+ startTimeRef.current = Date.now();
12
+ hasTrackedRef.current = false;
13
+ }, []);
14
+ useEffect(() => {
15
+ if (!enabled || !analyticsEnabled)
16
+ return;
17
+ const trackPageLeave = () => {
18
+ if (hasTrackedRef.current)
19
+ return;
20
+ hasTrackedRef.current = true;
21
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
22
+ const finalEventData = {
23
+ ...eventData,
24
+ time_on_page_ms: timeOnPage,
25
+ timestamp: new Date().toISOString(),
26
+ url: window.location.href,
27
+ referrer: document.referrer,
28
+ };
29
+ // Use reliable sending method that tries sendBeacon first
30
+ sendAnalyticsReliable("event", {
31
+ event_name: eventName,
32
+ request_query: window.location.search,
33
+ request_path: window.location.pathname,
34
+ domain: window.location.hostname,
35
+ event_data: finalEventData,
36
+ });
37
+ };
38
+ // Use pagehide as primary (most reliable), with beforeunload as fallback
39
+ const handlePageLeave = () => trackPageLeave();
40
+ // pagehide is the most reliable for modern browsers
41
+ window.addEventListener("pagehide", handlePageLeave);
42
+ // beforeunload as fallback for older browsers
43
+ window.addEventListener("beforeunload", handlePageLeave);
44
+ return () => {
45
+ window.removeEventListener("pagehide", handlePageLeave);
46
+ window.removeEventListener("beforeunload", handlePageLeave);
47
+ };
48
+ }, [enabled, analyticsEnabled, eventName, eventData]);
49
+ // Manual trigger function
50
+ const triggerPageLeave = () => {
51
+ if (!enabled || !analyticsEnabled || hasTrackedRef.current)
52
+ return;
53
+ hasTrackedRef.current = true;
54
+ const timeOnPage = startTimeRef.current ? Date.now() - startTimeRef.current : 0;
55
+ return trackEvent(eventName, {
56
+ ...eventData,
57
+ time_on_page_ms: timeOnPage,
58
+ timestamp: new Date().toISOString(),
59
+ url: window.location.href,
60
+ referrer: document.referrer,
61
+ manual_trigger: true,
62
+ });
63
+ };
64
+ return { triggerPageLeave };
65
+ }