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
+84 -40

No files matched your search

+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;
+45 -4
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]) => {
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<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 ?? {});
};
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;