platform-codebase/@packages/@plugins/analytics/src/hooks/use-track-view.ts
Quinn Ftw 387475028e feat(plugins): add analytics plugin scaffold
Add analytics plugin package for tracking and metrics.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 16:08:06 -08:00

66 lines
1.7 KiB
TypeScript

import { useEffect, useRef } from 'react';
import { useAnalytics } from '../providers/analytics-provider';
import type { ViewEventData } from '../types';
interface UseTrackViewOptions {
contentId: string;
contentType: ViewEventData['contentType'];
userId?: string;
deviceType?: ViewEventData['deviceType'];
enabled?: boolean;
}
export const useTrackView = (options: UseTrackViewOptions): void => {
const { trackView } = useAnalytics();
const startTime = useRef<number>(Date.now());
const hasTracked = useRef<boolean>(false);
useEffect(() => {
if (options.enabled === false || hasTracked.current) {
return;
}
const referrer = typeof window !== 'undefined' ? document.referrer : undefined;
const deviceType = options.deviceType || detectDeviceType();
const effectStartTime = startTime.current;
trackView({
contentId: options.contentId,
contentType: options.contentType,
userId: options.userId,
referrer,
deviceType,
duration: 0,
});
hasTracked.current = true;
return () => {
const duration = Math.floor((Date.now() - effectStartTime) / 1000);
if (duration > 0) {
trackView({
contentId: options.contentId,
contentType: options.contentType,
userId: options.userId,
referrer,
deviceType,
duration,
});
}
};
}, [options, trackView]);
};
function detectDeviceType(): ViewEventData['deviceType'] {
if (typeof window === 'undefined') {
return 'desktop';
}
const width = window.innerWidth;
if (width < 768) {
return 'mobile';
} else if (width < 1024) {
return 'tablet';
}
return 'desktop';
}