Files
movie-advisor/components/Analytics/index.tsx
T
nerandClaude Opus 5 d67a0d4df6 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>
2026-08-14 12:08:16 +03:00

67 lines
1.7 KiB
TypeScript

'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;