refactor(analytics): method per event instead of track(name, props)

analytics.showViewed({...}) reads better than track('show_viewed', {...}) and
drops the track_ alias Captions needed, where vidstack already exports track.

The methods are derived from the event catalogue with a mapped type plus a
Proxy rather than written out, so the catalogue stays the only place an event
is declared and the two cannot drift. Names stay snake_case on the wire.
Emitters are cached so a method is referentially stable and safe to pass to a
hook or use as an effect dependency.

Events with no payload are typed void and take no arguments.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nerandClaude Opus 5 committed 2026-08-14 12:39:54 +03:00
1 parent d67a0d4df6
commit 01753d4eb6
16 files changed
+83 -39

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@ import { atom, getDefaultStore, useAtom } from 'jotai';
import randomQuery from '@/data/queries/random';
import useInfiniteList from '@/hooks/useInfiniteList';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
const indexAtom = atom(0);
@@ -34,7 +34,7 @@ const useRandomMovie = ({ page }: Props) => {
fetchNextPage,
onIndexChange: useCallback(
(index: number) => {
track('random_shuffled', { index });
analytics.randomShuffled({ index });
startTransition(() => setIndex(index));
},
[setIndex]
@@ -2,6 +2,7 @@ import { useRef } from 'react';
import searchQuery, { SearchQueryProps } from '@/data/queries/search';
import useInfiniteList from '@/hooks/useInfiniteList';
import analytics from '@/lib/analytics';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
const useSearch = (props: SearchQueryProps) => {
@@ -10,7 +11,7 @@ const useSearch = (props: SearchQueryProps) => {
const infiniteQuery = useInfiniteList({ ...searchQuery(props), mode: 'default', list: 'search' });
useTrackOnce(
'search_performed',
analytics.searchPerformed,
props.query && infiniteQuery.isFetched ? `${props.type}:${props.query}` : undefined,
() => ({ query: props.query, showType: props.type, results: infiniteQuery.shows.length })
);
+2 -2
View File
@@ -5,7 +5,7 @@ import sessionMutation from '@/data/mutations/session';
import tokenMutation from '@/data/mutations/token';
import { useSetSession } from '@/hooks/useSession';
import { useToast } from '@/hooks/useToast';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
const AUTH_RETRIES = 10;
@@ -25,7 +25,7 @@ const useAuth = () => {
const session = useMutation({
...sessionMutation(),
onSuccess({ session_id }) {
track('auth_completed', {});
analytics.authCompleted();
setSession(session_id);
clearInterval(intervalRef.current);
@@ -1,13 +1,13 @@
import { useCallback } from 'react';
import { useSetSession } from '@/hooks/useSession';
import { clearIdentity, track } from '@/lib/analytics';
import analytics, { clearIdentity } from '@/lib/analytics';
const useLogOut = () => {
const setSession = useSetSession();
return useCallback(() => {
track('auth_signed_out', {});
analytics.authSignedOut();
clearIdentity();
setSession(undefined);
}, [setSession]);
+2 -1
View File
@@ -4,6 +4,7 @@ import { FC } from 'react';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import analytics from '@/lib/analytics';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
import { formatDate } from '@/lib/utils';
@@ -24,7 +25,7 @@ const lifespan = ({ birthday, deathday }: Profile) => {
const Person: FC<Props> = ({ personId }) => {
const { data: profile, isError } = useProfile({ personId });
useTrackOnce('person_viewed', profile ? personId : undefined, () => ({ personId }));
useTrackOnce(analytics.personViewed, profile ? personId : undefined, () => ({ personId }));
if (isError) return <NoResults />;
@@ -2,7 +2,7 @@ import { useMemo, useRef } from 'react';
import { CaptionOption, useCaptionOptions } from '@vidstack/react';
import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons';
import { track as track_ } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import { cn } from '@/lib/utils';
import PlayerMenu from '../Menu';
@@ -32,7 +32,7 @@ const CaptionsMenu = () => {
label: track.label,
value: track.value,
onSelect: (value) => {
track_('subtitles_selected', { language: value });
analytics.subtitlesSelected({ language: value });
return (live.current.find((option) => option.value === value) ?? track).select();
}
@@ -16,7 +16,7 @@ import { NextIcon } from '@vidstack/react/icons';
import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr';
import { useSetCanPlay } from '@/hooks/useCanPlay';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
import { cn } from '@/lib/utils';
@@ -89,7 +89,7 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStre
onStreamError?.(error);
}, [error, onStreamError]);
useTrackOnce('playback_failed', error && show ? `${magnet}:${error}` : undefined, () => ({
useTrackOnce(analytics.playbackFailed, error && show ? `${magnet}:${error}` : undefined, () => ({
showId: show!.id,
showType: show!.type,
reason: error!
@@ -126,7 +126,7 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStre
setCanPlay(true);
if (show && startedRef.current !== magnet) {
startedRef.current = magnet;
track('playback_started', { showId: show.id, showType: show.type });
analytics.playbackStarted({ showId: show.id, showType: show.type });
}
if (resumeTime.current) {
player.current!.currentTime = resumeTime.current;
@@ -8,7 +8,7 @@ import ButtonsGroup from '@/components/ui/buttons-group';
import { Quality } from '@/data/parsers/yts/models';
import { useM3UUrl } from '@/hooks/useM3UStreamUrl';
import { useStreamUrl } from '@/hooks/useStreamUrl';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import { cn, detectSafari, getMagnetHash, isStandaloneApp, seasonFromEpisodes, torrentKey } from '@/lib/utils';
import usePinnedTorrents from '../../../../usePinnedTorrents';
@@ -65,7 +65,7 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
}, [pinned, magnet, key, torrent.magnet]);
const pinPlayed = () => {
track('torrent_selected', {
analytics.torrentSelected({
provider,
seeders: torrent.seeders,
quality: torrent.quality,
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { Sort } from '@/data/parsers';
import analytics from '@/lib/analytics';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
const useTorrents = ({
@@ -24,7 +25,7 @@ const useTorrents = ({
queryFn: () => queryFn({ query, sort, imdbID })
});
useTrackOnce('torrents_searched', result.data ? `${key}:${query}` : undefined, () => ({
useTrackOnce(analytics.torrentsSearched, result.data ? `${key}:${query}` : undefined, () => ({
showId: show.id,
showType: show.type,
provider: key,
+3 -2
View File
@@ -7,6 +7,7 @@ import Poster from '@/components/Poster';
import Credits from '@/components/Preview/components/Credits';
import useDetails from '@/components/Preview/useDetails';
import { Modal } from '@/components/ui/dialog';
import analytics from '@/lib/analytics';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
import { cn } from '@/lib/utils';
@@ -43,11 +44,11 @@ const Preview: FC<Props> = ({
const isModal = Boolean(onClose);
useTrackOnce('show_viewed', show?.id, () => ({
useTrackOnce(analytics.showViewed, show?.id, () => ({
showId: show!.id,
showType: show!.type,
title: show!.title,
surface: isModal ? 'modal' : 'page'
surface: isModal ? ('modal' as const) : ('page' as const)
}));
if (!show) return null;
+2 -2
View File
@@ -4,7 +4,7 @@ import { FC, useState } from 'react';
import useSimilar from '@/components/Trending/useSimilar';
import Nav from '@/components/ui/nav';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import Gallery from './components/Gallery';
import { tabs as initialTabs } from './constants';
@@ -46,7 +46,7 @@ const Trending: FC<Props> = ({ showId, showType, preview }) => {
tabs={tabs}
active={active}
onChange={(active) => {
track('gallery_tab_changed', { tab: active.type });
analytics.galleryTabChanged({ tab: active.type });
setActive(active);
}}
className='mb-3'
+2 -2
View File
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react';
import { QueryKey, useInfiniteQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import type { ListName } from '@/lib/analytics/events';
interface Props {
@@ -51,7 +51,7 @@ const useInfiniteList = ({
const pages = data?.pages.length ?? 0;
const loadNextPage = useCallback(() => {
if (list) track('list_loaded_more', { list, page: pages + 1 });
if (list) analytics.listLoadedMore({ list, page: pages + 1 });
return fetchNextPage();
}, [list, pages, fetchNextPage]);
+2 -2
View File
@@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import statesMutation from '@/data/mutations/accountStates';
import statesQuery from '@/data/queries/accountStates';
import { KEY as USERS_SHOWS_KEY } from '@/data/queries/usersShows';
import { track } from '@/lib/analytics';
import analytics from '@/lib/analytics';
import { useFavorites, useFavoritesStateToggle, useWatchList, useWatchListStateToggle } from './useLocalUsersLists';
import { useSession } from './useSession';
@@ -52,7 +52,7 @@ export const useMutateShowState = (show: Show) => {
list: mutation.variables?.list,
isPending: session ? mutation.isPending : false,
mutate: ({ list, value }: { list: 'favorite' | 'watchlist'; value: boolean }) => {
track('library_toggled', { showId: show.id, showType: show.type, list, value });
analytics.libraryToggled({ showId: show.id, showType: show.type, list, value });
if (session) return mutation.mutate({ showId: show.id, showType: show.type, list, value });
+2 -4
View File
@@ -16,8 +16,8 @@ export type AnalyticsEvents = {
gallery_tab_changed: { tab: string };
library_toggled: ShowRef & { list: 'favorite' | 'watchlist'; value: boolean };
auth_completed: EmptyPayload;
auth_signed_out: EmptyPayload;
auth_completed: void;
auth_signed_out: void;
torrents_searched: ShowRef & { provider: string; results: number };
torrent_selected: { provider: string; seeders: number; quality?: string; source?: string; codec?: string };
@@ -26,6 +26,4 @@ export type AnalyticsEvents = {
subtitles_selected: { language: string };
};
export type EmptyPayload = Record<string, never>;
export type AnalyticsEvent = keyof AnalyticsEvents;
+44 -3
View File
@@ -2,6 +2,23 @@ import { OPENPANEL_CLIENT_ID } from '@/env';
import type { AnalyticsEvents } from './events';
type Payload = Record<string, unknown>;
type CamelCase<Name extends string> = Name extends `${infer Head}_${infer Tail}`
? `${Head}${Capitalize<CamelCase<Tail>>}`
: Name;
type Emitter<Properties> = [Properties] extends [void] ? () => void : (properties: Properties) => void;
/**
* One method per entry in the event catalogue, derived from it rather than written out, so the
* catalogue stays the single place an event is declared. `show_viewed` becomes
* `analytics.showViewed(...)` and keeps its snake_case name on the wire.
*/
type Analytics = {
[Name in keyof AnalyticsEvents as CamelCase<Name & string>]: Emitter<AnalyticsEvents[Name]>;
};
// The sdk declares `window.op` itself, so this reads it without redeclaring the global.
// It is defined by the inline stub in components/Analytics and queues calls until the real
// script loads, so events fired before then are kept rather than dropped.
@@ -9,11 +26,33 @@ const op = () => (window as unknown as { op?: (method: string, ...args: unknown[
const ready = () => Boolean(OPENPANEL_CLIENT_ID) && typeof window !== 'undefined';
export const track = <Name extends keyof AnalyticsEvents>(name: Name, properties: AnalyticsEvents[Name]) => {
const eventName = (method: string) => method.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
// Emitters are cached so `analytics.showViewed` is referentially stable and safe to pass to a
// hook or use as an effect dependency.
const emitters = new Map<string, (properties?: Payload) => void>();
const analytics = new Proxy({} as Analytics, {
get: (_, method) => {
if (typeof method !== 'string') return undefined;
let emitter = emitters.get(method);
if (!emitter) {
const name = eventName(method);
emitter = (properties?: Payload) => {
if (!ready()) return;
op()?.('track', name, properties);
};
op()?.('track', name, properties ?? {});
};
emitters.set(method, emitter);
}
return emitter;
}
});
export const identify = (profileId: string) => {
if (!ready()) return;
@@ -28,3 +67,5 @@ export const clearIdentity = () => {
};
export type { AnalyticsEvents, ListName } from './events';
export default analytics;
+9 -8
View File
@@ -1,17 +1,18 @@
import { useEffect, useRef } from 'react';
import type { AnalyticsEvents } from './events';
import { track } from '.';
// Stands in for TypeScript 5.4's NoInfer. Without it the payload widens literal unions such as
// `'page' | 'modal'` to `string` instead of being checked against the emitter's type.
type NoInfer<Type> = [Type][Type extends unknown ? 0 : never];
/**
* Fires an event once per distinct `key`, skipping while it is nullish. Keeps view style
* Fires an emitter once per distinct `key`, skipping while it is nullish. Keeps view style
* events (a show opened, a search resolved) to a single line at the call site instead of an
* effect plus a ref in every component that needs one.
*/
const useTrackOnce = <Name extends keyof AnalyticsEvents>(
name: Name,
const useTrackOnce = <Properties>(
emit: (properties: Properties) => void,
key: string | number | null | undefined,
payload: () => AnalyticsEvents[Name]
payload: () => NoInfer<Properties>
) => {
const payloadRef = useRef(payload);
const sentRef = useRef<string | number | null>(null);
@@ -23,8 +24,8 @@ const useTrackOnce = <Name extends keyof AnalyticsEvents>(
sentRef.current = key;
track(name, payloadRef.current());
}, [name, key]);
emit(payloadRef.current());
}, [emit, key]);
};
export default useTrackOnce;