import React from 'react'; import { useMatches } from 'react-router-dom'; import { analyticsService } from './AnalyticsService'; import { useIsAnalyticsEnabled } from './conditional-checks'; import type { EventPropertiesMap, TrackEvents } from './gen/analytics-types'; import { CHECKPOINT_INTERVAL_MS, journeyCollector } from './JourneyCollector'; export const useTrackAnalyticsEvent = (): (( event: E, properties: Omit, ) => void) => { const { isAnalyticsEnabled } = useIsAnalyticsEnabled(); return React.useCallback( (event: E, properties: Omit) => { if (isAnalyticsEnabled) { void analyticsService.track(event, properties); } }, [isAnalyticsEnabled], ); }; /** Records the privacy-safe route pattern supplied by the active route. */ export const useJourneyTracker = (): void => { const matches = useMatches(); const { isAnalyticsEnabled } = useIsAnalyticsEnabled(); const pattern = ( matches[matches.length - 1]?.handle as { routePattern?: string } | undefined )?.routePattern ?? '/unknown'; React.useEffect(() => { if (isAnalyticsEnabled) { journeyCollector.recordStep(pattern); } }, [pattern, isAnalyticsEnabled]); React.useEffect(() => { if (!isAnalyticsEnabled) { return; } const id = setInterval(() => { if (journeyCollector.isEligibleForCheckpoint()) { journeyCollector.flush(); } }, CHECKPOINT_INTERVAL_MS); return () => clearInterval(id); }, [isAnalyticsEnabled]); };