1
0
Fork 0
polaris-task-force/src/lib/client-analytics/chronicle.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

245 lines
7.1 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
import { track } from "./core";
/**
* Chronicle read tracking (Phase 1 domain instrumentation).
*
* Article-level read progress from scroll + dwell inside the article
* container. Emits custom events that complement (never replace) the
* StoryBeatStates read markers:
*
* - `chronicle.read_progress` once when an article first becomes visible
* (this is what the rollup counts as an "open"), carrying `progressPct`;
* - `chronicle.read_completed` once per mount when the reader has scrolled
* at least CHRONICLE_COMPLETION_PROGRESS of the article AND dwelled at
* least CHRONICLE_MIN_DWELL_MS while it was on screen, carrying `timeMs`
* (accumulated visible dwell up to completion).
*
* Both events carry `{ kind: "beat" | "journal", ref: <id> }`.
*/
export const CHRONICLE_COMPLETION_PROGRESS = 0.9;
export const CHRONICLE_MIN_DWELL_MS = 10_000;
const COMPLETION_CHECK_INTERVAL_MS = 2_000;
export type ChronicleKind = "beat" | "journal";
function clamp01(value: number): number {
return Math.max(0, Math.min(1, value));
}
/**
* Fraction of the article the reader has consumed: for articles taller than
* the viewport this is the classic read-progress ratio (0 when the top hits
* the fold, 1 when the bottom clears it); for shorter articles it is the
* visible fraction.
*/
function readProgress(el: HTMLElement): number {
const rect = el.getBoundingClientRect();
if (rect.height <= 0) return 0;
const vh = window.innerHeight || 1;
if (rect.height <= vh) {
const visible = Math.min(rect.bottom, vh) - Math.max(rect.top, 0);
return clamp01(visible / rect.height);
}
return clamp01(-rect.top / (rect.height - vh));
}
/** Start a read session for one article element. Returns a dispose fn. */
function startReadSession(kind: ChronicleKind, ref: string, el: HTMLElement): () => void {
let disposed = false;
let dwellMs = 0;
let visibleSince: number | null = null;
let maxProgress = 0;
let opened = false;
let completed = false;
const currentDwell = (): number => {
if (visibleSince != null && document.visibilityState === "visible") {
return dwellMs + (Date.now() - visibleSince);
}
return dwellMs;
};
const complete = (): void => {
if (completed) return;
completed = true;
track("chronicle.read_completed", { kind, ref, timeMs: Math.round(currentDwell()) });
};
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (disposed) continue;
if (entry.isIntersecting) {
if (visibleSince == null) visibleSince = Date.now();
if (!opened) {
opened = true;
maxProgress = Math.max(maxProgress, readProgress(el));
track("chronicle.read_progress", {
kind,
ref,
progressPct: Math.round(maxProgress * 100),
});
}
} else if (visibleSince != null) {
dwellMs += Date.now() - visibleSince;
visibleSince = null;
}
}
},
{ threshold: 0.35 },
);
let rafPending = false;
const onScroll = () => {
if (disposed || rafPending) return;
rafPending = true;
requestAnimationFrame(() => {
rafPending = false;
if (disposed) return;
try {
maxProgress = Math.max(maxProgress, readProgress(el));
} catch {
// Swallowed by contract.
}
});
};
const onVisibility = () => {
if (disposed) return;
if (document.visibilityState === "hidden" && visibleSince != null) {
dwellMs += Date.now() - visibleSince;
visibleSince = null;
} else if (document.visibilityState === "visible" && visibleSince == null) {
// Re-observe below; only count while the element is actually on screen.
const rect = el.getBoundingClientRect();
const vh = window.innerHeight || 1;
if (rect.bottom > 0 && rect.top < vh) visibleSince = Date.now();
}
};
observer.observe(el);
window.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", onScroll);
document.addEventListener("visibilitychange", onVisibility);
const timer = setInterval(() => {
if (disposed || completed || !opened) return;
try {
maxProgress = Math.max(maxProgress, readProgress(el));
if (maxProgress >= CHRONICLE_COMPLETION_PROGRESS && currentDwell() >= CHRONICLE_MIN_DWELL_MS) {
complete();
}
} catch {
// Swallowed by contract.
}
}, COMPLETION_CHECK_INTERVAL_MS);
return () => {
disposed = true;
observer.disconnect();
clearInterval(timer);
window.removeEventListener("scroll", onScroll);
window.removeEventListener("resize", onScroll);
document.removeEventListener("visibilitychange", onVisibility);
};
}
/**
* Wraps a single article (used for the journal reader). The wrapper div is
* layout-transparent apart from being a block box.
*/
export function ChronicleArticle({
kind,
articleId,
className,
children,
}: {
kind: ChronicleKind;
articleId: string;
className?: string;
children: React.ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
return startReadSession(kind, articleId, el);
}, [kind, articleId]);
return (
<div ref={ref} className={className}>
{children}
</div>
);
}
/**
* Tracks every descendant carrying `idAttr` (default `data-beat-id`) as a
* separate beat article. Used by the two Chronicle readers, which render many
* beats inside one scroll/paging surface and add the attribute per beat.
*/
export function ChronicleTrackedRegion({
kind = "beat",
idAttr = "data-beat-id",
className,
children,
}: {
kind?: ChronicleKind;
idAttr?: string;
className?: string;
children: React.ReactNode;
}) {
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const sessions = new Map<Element, () => void>();
const attach = (el: Element) => {
const id = el.getAttribute(idAttr);
if (!id || sessions.has(el)) return;
sessions.set(el, startReadSession(kind, id, el as HTMLElement));
};
const detach = (el: Element) => {
const dispose = sessions.get(el);
if (dispose) {
dispose();
sessions.delete(el);
}
};
root.querySelectorAll(`[${idAttr}]`).forEach(attach);
const mutator = new MutationObserver((mutations) => {
for (const mutation of mutations) {
mutation.removedNodes.forEach((node) => {
if (node instanceof Element) detach(node);
});
mutation.addedNodes.forEach((node) => {
if (!(node instanceof Element)) return;
if (node.hasAttribute(idAttr)) attach(node);
node.querySelectorAll?.(`[${idAttr}]`).forEach(attach);
});
}
});
mutator.observe(root, { childList: true, subtree: true });
return () => {
mutator.disconnect();
sessions.forEach((dispose) => dispose());
sessions.clear();
};
}, [kind, idAttr]);
return (
<div ref={rootRef} className={className}>
{children}
</div>
);
}