feat(analytics): self-hosted openpanel with a typed event catalogue

Replaces Vercel Analytics with OpenPanel, driven entirely by env vars so the
whole layer is inert until NEXT_PUBLIC_OPENPANEL_CLIENT_ID is set.

Zero initial load cost. next/script emits a rel=preload even on lazyOnload,
which pulls the sdk during the first paint, so the component skips it: it
inlines the 416 byte official stub (window.op queues calls immediately) and
appends the real script itself on window load plus requestIdleCallback. The
built html carries no preload and no script src for the analytics host.

Events live in one typed catalogue (lib/analytics/events.ts) and track() is
keyed to it, so a wrong name or payload is a type error rather than a silent
bad row. Emitters sit in the hooks that already own the behaviour instead of
being sprinkled through components:

- useShowState covers every favourite and watchlist toggle
- useInfiniteList covers pagination for all six lists
- useTorrents covers all three providers
- Preview, Person and useSearch use a shared useTrackOnce hook

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nerandClaude Opus 5 committed 2026-08-14 12:08:16 +03:00
1 parent 0186c793f2
commit d67a0d4df6
26 files changed
+504 -89

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
'use client';
import { useEffect } from 'react';
import { getInitSnippet } from '@openpanel/web';
import { OPENPANEL_API_URL, OPENPANEL_CLIENT_ID, OPENPANEL_SCRIPT_URL } from '@/env';
const SCRIPT_ID = 'openpanel-sdk';
const SRC = OPENPANEL_SCRIPT_URL || 'https://openpanel.dev/op1.js';
const OPTIONS = {
clientId: OPENPANEL_CLIENT_ID,
apiUrl: OPENPANEL_API_URL,
trackScreenViews: true,
trackOutgoingLinks: true
};
/**
* next/script emits a `rel=preload` even on `lazyOnload`, which pulls the sdk during the
* initial load. The inline stub below is a few hundred bytes and makes `window.op` queue
* calls immediately, so the real script can wait until the page is loaded and idle.
*/
const Analytics = () => {
useEffect(() => {
if (!OPENPANEL_CLIENT_ID) return;
let cancelled = false;
const append = () => {
if (cancelled || document.getElementById(SCRIPT_ID)) return;
const script = document.createElement('script');
script.id = SCRIPT_ID;
script.src = SRC;
script.async = true;
document.body.appendChild(script);
};
const schedule = () =>
typeof window.requestIdleCallback === 'function'
? window.requestIdleCallback(append, { timeout: 5000 })
: window.setTimeout(append, 2000);
if (document.readyState === 'complete') schedule();
else window.addEventListener('load', schedule, { once: true });
return () => {
cancelled = true;
};
}, []);
if (!OPENPANEL_CLIENT_ID) return null;
return (
<script
dangerouslySetInnerHTML={{
__html: `${getInitSnippet()}window.op('init', ${JSON.stringify(OPTIONS)});`
}}
/>
);
};
export default Analytics;
@@ -2,11 +2,18 @@ import { useRef } from 'react';
import searchQuery, { SearchQueryProps } from '@/data/queries/search';
import useInfiniteList from '@/hooks/useInfiniteList';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
const useSearch = (props: SearchQueryProps) => {
const previousRef = useRef<Show[]>([]);
const infiniteQuery = useInfiniteList({ ...searchQuery(props), mode: 'default' });
const infiniteQuery = useInfiniteList({ ...searchQuery(props), mode: 'default', list: 'search' });
useTrackOnce(
'search_performed',
props.query && infiniteQuery.isFetched ? `${props.type}:${props.query}` : undefined,
() => ({ query: props.query, showType: props.type, results: infiniteQuery.shows.length })
);
if (infiniteQuery.isFetched) {
previousRef.current = infiniteQuery.shows;
@@ -5,6 +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';
const AUTH_RETRIES = 10;
@@ -24,6 +25,7 @@ const useAuth = () => {
const session = useMutation({
...sessionMutation(),
onSuccess({ session_id }) {
track('auth_completed', {});
setSession(session_id);
clearInterval(intervalRef.current);
@@ -1,11 +1,16 @@
import { useCallback } from 'react';
import { useSetSession } from '@/hooks/useSession';
import { clearIdentity, track } from '@/lib/analytics';
const useLogOut = () => {
const setSession = useSetSession();
return useCallback(() => setSession(undefined), [setSession]);
return useCallback(() => {
track('auth_signed_out', {});
clearIdentity();
setSession(undefined);
}, [setSession]);
};
export default useLogOut;
+3
View File
@@ -4,6 +4,7 @@ import { FC } from 'react';
import List from '@/components/List';
import NoResults from '@/components/NoResults';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
import { formatDate } from '@/lib/utils';
import Biography from './components/Biography';
@@ -23,6 +24,8 @@ const lifespan = ({ birthday, deathday }: Profile) => {
const Person: FC<Props> = ({ personId }) => {
const { data: profile, isError } = useProfile({ personId });
useTrackOnce('person_viewed', profile ? personId : undefined, () => ({ personId }));
if (isError) return <NoResults />;
if (!profile) return <PersonSkeleton />;
@@ -2,6 +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 { cn } from '@/lib/utils';
import PlayerMenu from '../Menu';
@@ -30,7 +31,11 @@ const CaptionsMenu = () => {
options={captions.map((track) => ({
label: track.label,
value: track.value,
onSelect: (value) => (live.current.find((option) => option.value === value) ?? track).select()
onSelect: (value) => {
track_('subtitles_selected', { language: value });
return (live.current.find((option) => option.value === value) ?? track).select();
}
}))}
>
{tracks.selectedTrack ? (
@@ -16,6 +16,8 @@ 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 useTrackOnce from '@/lib/analytics/useTrackOnce';
import { cn } from '@/lib/utils';
import Audio from './components/Audio';
@@ -76,6 +78,7 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStre
const { tracks: audioTracks, audio, setAudio, resolvedSrc, error } = useGstAudio(source?.src);
const resumeTime = useRef(0);
const startedRef = useRef<string>();
const changeAudio = (track: number) => {
resumeTime.current = player.current?.currentTime ?? 0;
@@ -86,6 +89,12 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStre
onStreamError?.(error);
}, [error, onStreamError]);
useTrackOnce('playback_failed', error && show ? `${magnet}:${error}` : undefined, () => ({
showId: show!.id,
showType: show!.type,
reason: error!
}));
const playerSrc = useMemo(
() => (source && !error ? ({ ...source, src: resolvedSrc } as VideoSrc) : []),
[source, resolvedSrc, error]
@@ -115,6 +124,10 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles, show, episodes, onStre
onProviderChange={onProviderChange}
onCanPlay={() => {
setCanPlay(true);
if (show && startedRef.current !== magnet) {
startedRef.current = magnet;
track('playback_started', { showId: show.id, showType: show.type });
}
if (resumeTime.current) {
player.current!.currentTime = resumeTime.current;
resumeTime.current = 0;
@@ -8,6 +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 { cn, detectSafari, getMagnetHash, isStandaloneApp, seasonFromEpisodes, torrentKey } from '@/lib/utils';
import usePinnedTorrents from '../../../../usePinnedTorrents';
@@ -63,7 +64,17 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pinned, magnet, key, torrent.magnet]);
const pinPlayed = () => pin(key);
const pinPlayed = () => {
track('torrent_selected', {
provider,
seeders: torrent.seeders,
quality: torrent.quality,
source: torrent.source,
codec: torrent.codec
});
pin(key);
};
const supportedForCast = prefix && !prefix.includes('{host}');
@@ -52,26 +52,31 @@ const showTorrentsModal = create(({ onResolve, ...show }: Props) => {
const isSeries = show.type === 'tv';
const tracked = { id: show.id, type: show.type };
const yts = useTorrents({
query: isSeries ? '' : show.title,
queryFn: providers.yts.queryFn,
sort,
key: providers.yts.key,
imdbID: show.imdb_id!
imdbID: show.imdb_id!,
show: tracked
});
const tpb = useTorrents({
query,
queryFn: providers.tpb.queryFn,
sort,
key: providers.tpb.key,
imdbID: show.imdb_id!
imdbID: show.imdb_id!,
show: tracked
});
const tlk = useTorrents({
query,
queryFn: providers.tlk.queryFn,
sort,
key: providers.tlk.key,
imdbID: show.imdb_id!
imdbID: show.imdb_id!,
show: tracked
});
const queries = { yts, tpb, tlk };
@@ -1,25 +1,37 @@
import { useQuery } from '@tanstack/react-query';
import { Sort } from '@/data/parsers';
import useTrackOnce from '@/lib/analytics/useTrackOnce';
const useTorrents = ({
query,
sort,
imdbID,
key,
queryFn
queryFn,
show
}: {
key: string;
query: string;
sort: Sort;
imdbID: string;
show: { id: Show['id']; type: Show['type'] };
queryFn: (params: { query: string; sort: Sort; imdbID: string }) => Promise<Torrent[]>;
}) => {
return useQuery({
const result = useQuery({
enabled: Boolean(query),
queryKey: [key, query, sort, imdbID],
queryFn: () => queryFn({ query, sort, imdbID })
});
useTrackOnce('torrents_searched', result.data ? `${key}:${query}` : undefined, () => ({
showId: show.id,
showType: show.type,
provider: key,
results: result.data?.length ?? 0
}));
return result;
};
export default useTorrents;
+11 -3
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 useTrackOnce from '@/lib/analytics/useTrackOnce';
import { cn } from '@/lib/utils';
import Actions from './components/Actions';
@@ -38,12 +39,19 @@ const Preview: FC<Props> = ({
}) => {
const { data: detailedShow } = useDetails({ showId: showId || baseShow?.id, showType: showType || baseShow?.type });
if (!baseShow && !detailedShow) return null;
const show: Show & Partial<Details> = (detailedShow || baseShow)!;
const show = (detailedShow || baseShow) as (Show & Partial<Details>) | undefined;
const isModal = Boolean(onClose);
useTrackOnce('show_viewed', show?.id, () => ({
showId: show!.id,
showType: show!.type,
title: show!.title,
surface: isModal ? 'modal' : 'page'
}));
if (!show) return null;
const Title = heading ? 'h1' : 'span';
return (
+10 -1
View File
@@ -4,6 +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 Gallery from './components/Gallery';
import { tabs as initialTabs } from './constants';
@@ -41,7 +42,15 @@ const Trending: FC<Props> = ({ showId, showType, preview }) => {
return (
(streaming.isFetched || similar.isFetched) && (
<div className='hidden md:block'>
<Nav tabs={tabs} active={active} onChange={(active) => setActive(active)} className='mb-3' />
<Nav
tabs={tabs}
active={active}
onChange={(active) => {
track('gallery_tab_changed', { tab: active.type });
setActive(active);
}}
className='mb-3'
/>
{!tab.isPending && <Gallery key={active.type} shows={tab.data || []} />}
</div>
)