1
0
Fork 0
polaris-task-force/src/lib/client-analytics/AnalyticsTracker.tsx
Z8MB1E 268d4bb117 feat(analytics): add first-party analytics collector, SDK, rollups, and admin dashboard
Phase 1 of replacing Microsoft Clarity with first-party usage analytics:
- Plain Postgres tables via shared DDL module (src/lib/analytics/schema.ts)
  executed by both the add_analytics_tables migration and the test bootstrap;
  test-db.ts drops them around drizzle push (composite-PK introspector bug)
- /api/collect beacon collector with IP/UA enrichment, retroactive login
  attribution, bot blocklist, per-IP rate limiting, strict validation
- Client SDK (src/lib/client-analytics): SPA pageviews, clicks, scroll depth,
  focus, data-track visibility, heartbeats; NEXT_PUBLIC_ANALYTICS_DEV=1 dev
  gate with console mirror; mounted beside Clarity in the two frontend layouts
- Hourly rollup + daily retention bins (payload analytics-rollup/-purge)
- Chronicle read progress/completion, wiki new-clicked/created, minigame
  route mapping custom events
- admin:analytics:manage permission (+ roles enum migration) and the
  /admin/analytics Payload view with six recharts-backed report panels
2026-10-14 12:12:53 -04:00

79 lines
2.6 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { disposeTracker, flush, initTracker } from "./core";
import { startCaptures, type Captures } from "./capture";
/**
* First-party analytics tracker (Phase 1), the replacement for Microsoft
* Clarity (which stays mounted during the transition).
*
* Renders nothing. Mount once per top-level frontend layout
* (`src/app/(frontend)/layout.tsx` and `src/app/login/layout.tsx`) next to
* `<ClarityAnalytics />`; one mount covers every route below it. The Payload
* admin panel is intentionally NOT tracked.
*
* Enablement lives in `core.isAnalyticsEnabled()`: production builds always
* track; development tracks only with NEXT_PUBLIC_ANALYTICS_DEV=1 (and then
* mirrors every event to console.debug("[analytics]", ...)). All failures are
* swallowed: analytics must never break the app.
*
* SPA navigation is captured twice over: a `usePathname()` effect covers App
* Router navigations, and patched `history.pushState`/`replaceState` cover
* any pushState that does not re-render the tree (duplicate calls for the
* same path are deduped inside the capture layer).
*/
export function AnalyticsTracker() {
const pathname = usePathname();
const capturesRef = useRef<Captures | null>(null);
useEffect(() => {
initTracker();
const captures = startCaptures();
capturesRef.current = captures;
// History patching: fire a synthetic event whenever app code (or a
// library) pushes state without a React navigation.
const originalPush = history.pushState.bind(history);
const originalReplace = history.replaceState.bind(history);
const emit =
(fn: typeof history.pushState) =>
(...args: Parameters<typeof history.pushState>) => {
fn(...args);
window.dispatchEvent(new Event("ptf:analytics-route"));
};
history.pushState = emit(originalPush);
history.replaceState = emit(originalReplace);
const onRouteEvent = () => {
try {
captures.handleRouteChange(window.location.pathname);
flush(false);
} catch {
// Swallowed by contract.
}
};
window.addEventListener("ptf:analytics-route", onRouteEvent);
return () => {
window.removeEventListener("ptf:analytics-route", onRouteEvent);
history.pushState = originalPush;
history.replaceState = originalReplace;
capturesRef.current = null;
captures.stop();
disposeTracker();
};
}, []);
useEffect(() => {
try {
capturesRef.current?.handleRouteChange(pathname);
} catch {
// Swallowed by contract.
}
}, [pathname]);
return null;
}