Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
type LogEventFn = (eventName: string, metadata?: Record<string, unknown>) => void;
declare global {
  interface Window {
    __lsa: LogEventFn;
  }
  const __lsa: LogEventFn;
}
 
const logEvent: LogEventFn = (eventName, metadata = {}) => {
  // Don't send if collect_analytics is falsey
  if (!(window as any).APP_SETTINGS?.collect_analytics) return;
 
  const payload = {
    ...metadata,
    event: eventName,
    url: window.location.href,
  };
 
  // Use requestIdleCallback to send the event after the main thread is free
  window.requestIdleCallback(() => {
    const params = new URLSearchParams({ __: JSON.stringify(payload) });
    const url = `/__lsa/?${params}`;
    // Use sendBeacon if available for better reliability during page unload
    try {
      if (navigator.sendBeacon) {
        navigator.sendBeacon(url);
      } else {
        // Fallback handling
        const img = new Image();
        img.src = url;
      }
    } catch {
      // Ignore errors here
    }
  });
};
 
export const registerAnalytics = () => {
  window.__lsa = logEvent;
};
 
// Usage examples:
// __lsa("data_import.view");
// __lsa("template.select", { template_type: "object_detection", template_id: "od_1" });
// __lsa("doc.click", { href: "https://labelstud.io/docs/guide/setup" });