From 01753d4eb639f575e1740becff53e42a9948f325 Mon Sep 17 00:00:00 2001 From: ner Date: Fri, 14 Aug 2026 12:39:54 +0300 Subject: [PATCH] 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) --- app/(site)/(root)/useRandomMovie.ts | 4 +- .../Header/components/Search/useSearch.ts | 3 +- components/Header/components/User/useAuth.ts | 4 +- .../Header/components/User/useLogOut.ts | 4 +- components/Person/index.tsx | 3 +- .../Player/components/Captions/index.tsx | 4 +- .../Torrents/components/Player/index.tsx | 6 +-- .../components/Actions/index.tsx | 4 +- .../components/Torrents/useTorrents.ts | 3 +- components/Preview/index.tsx | 5 +- components/Trending/index.tsx | 4 +- hooks/useInfiniteList.ts | 4 +- hooks/useShowState.ts | 4 +- lib/analytics/events.ts | 6 +-- lib/analytics/index.ts | 49 +++++++++++++++++-- lib/analytics/useTrackOnce.ts | 17 ++++--- 16 files changed, 84 insertions(+), 40 deletions(-) diff --git a/app/(site)/(root)/useRandomMovie.ts b/app/(site)/(root)/useRandomMovie.ts index 109a25c..bf147a0 100644 --- a/app/(site)/(root)/useRandomMovie.ts +++ b/app/(site)/(root)/useRandomMovie.ts @@ -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] diff --git a/components/Header/components/Search/useSearch.ts b/components/Header/components/Search/useSearch.ts index cf0def3..2df77bc 100644 --- a/components/Header/components/Search/useSearch.ts +++ b/components/Header/components/Search/useSearch.ts @@ -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 }) ); diff --git a/components/Header/components/User/useAuth.ts b/components/Header/components/User/useAuth.ts index c065a8c..918bc3a 100644 --- a/components/Header/components/User/useAuth.ts +++ b/components/Header/components/User/useAuth.ts @@ -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); diff --git a/components/Header/components/User/useLogOut.ts b/components/Header/components/User/useLogOut.ts index 438036b..29f656f 100644 --- a/components/Header/components/User/useLogOut.ts +++ b/components/Header/components/User/useLogOut.ts @@ -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]); diff --git a/components/Person/index.tsx b/components/Person/index.tsx index bd6e8dd..f4d8057 100644 --- a/components/Person/index.tsx +++ b/components/Person/index.tsx @@ -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 = ({ personId }) => { const { data: profile, isError } = useProfile({ personId }); - useTrackOnce('person_viewed', profile ? personId : undefined, () => ({ personId })); + useTrackOnce(analytics.personViewed, profile ? personId : undefined, () => ({ personId })); if (isError) return ; diff --git a/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx index 1c93f96..b6b5c31 100644 --- a/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx +++ b/components/Preview/components/Torrents/components/Player/components/Captions/index.tsx @@ -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(); } diff --git a/components/Preview/components/Torrents/components/Player/index.tsx b/components/Preview/components/Torrents/components/Player/index.tsx index e934d6a..d8fa22f 100644 --- a/components/Preview/components/Torrents/components/Player/index.tsx +++ b/components/Preview/components/Torrents/components/Player/index.tsx @@ -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 = ({ 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 = ({ 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; diff --git a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx index 432f681..35b3892 100644 --- a/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx +++ b/components/Preview/components/Torrents/components/TorrentsTable/components/Actions/index.tsx @@ -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 = ({ torrent, title, provider, show }) => { }, [pinned, magnet, key, torrent.magnet]); const pinPlayed = () => { - track('torrent_selected', { + analytics.torrentSelected({ provider, seeders: torrent.seeders, quality: torrent.quality, diff --git a/components/Preview/components/Torrents/useTorrents.ts b/components/Preview/components/Torrents/useTorrents.ts index 9ce9101..882d85b 100644 --- a/components/Preview/components/Torrents/useTorrents.ts +++ b/components/Preview/components/Torrents/useTorrents.ts @@ -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, diff --git a/components/Preview/index.tsx b/components/Preview/index.tsx index a2f3682..5058e6b 100644 --- a/components/Preview/index.tsx +++ b/components/Preview/index.tsx @@ -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 = ({ 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; diff --git a/components/Trending/index.tsx b/components/Trending/index.tsx index c7ff088..c4f30e6 100644 --- a/components/Trending/index.tsx +++ b/components/Trending/index.tsx @@ -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 = ({ 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' diff --git a/hooks/useInfiniteList.ts b/hooks/useInfiniteList.ts index 24c1950..3d8b36e 100644 --- a/hooks/useInfiniteList.ts +++ b/hooks/useInfiniteList.ts @@ -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]); diff --git a/hooks/useShowState.ts b/hooks/useShowState.ts index ae4b133..0399e06 100644 --- a/hooks/useShowState.ts +++ b/hooks/useShowState.ts @@ -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 }); diff --git a/lib/analytics/events.ts b/lib/analytics/events.ts index 0896ce9..ee7c823 100644 --- a/lib/analytics/events.ts +++ b/lib/analytics/events.ts @@ -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; - export type AnalyticsEvent = keyof AnalyticsEvents; diff --git a/lib/analytics/index.ts b/lib/analytics/index.ts index 5f8cd91..4fb512b 100644 --- a/lib/analytics/index.ts +++ b/lib/analytics/index.ts @@ -2,6 +2,23 @@ import { OPENPANEL_CLIENT_ID } from '@/env'; import type { AnalyticsEvents } from './events'; +type Payload = Record; + +type CamelCase = Name extends `${infer Head}_${infer Tail}` + ? `${Head}${Capitalize>}` + : Name; + +type Emitter = [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]: Emitter; +}; + // 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: Name, properties: AnalyticsEvents[Name]) => { - if (!ready()) return; +const eventName = (method: string) => method.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); - op()?.('track', name, properties); -}; +// 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 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 ?? {}); + }; + + 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; diff --git a/lib/analytics/useTrackOnce.ts b/lib/analytics/useTrackOnce.ts index c9c441d..a3718f1 100644 --- a/lib/analytics/useTrackOnce.ts +++ b/lib/analytics/useTrackOnce.ts @@ -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 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: Name, +const useTrackOnce = ( + emit: (properties: Properties) => void, key: string | number | null | undefined, - payload: () => AnalyticsEvents[Name] + payload: () => NoInfer ) => { const payloadRef = useRef(payload); const sentRef = useRef(null); @@ -23,8 +24,8 @@ const useTrackOnce = ( sentRef.current = key; - track(name, payloadRef.current()); - }, [name, key]); + emit(payloadRef.current()); + }, [emit, key]); }; export default useTrackOnce;