tracking.ts 1.62 KB
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
  }
}