90 lines
3.8 KiB
TypeScript
90 lines
3.8 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect } from "react";
|
|
import { usePathname } from "next/navigation";
|
|
|
|
type Metric = "LCP" | "INP" | "CLS" | "TTFB";
|
|
|
|
/**
|
|
* PEP-217: Web Vitals of real users with a bare PerformanceObserver — no outside scripts.
|
|
* LCP, INP and CLS are final when the page goes to the background (or is left), TTFB is known at
|
|
* once. One beacon per page view to /api/client-vitals: route without ids is cut on the server,
|
|
* mode (Продакт/Инженер) comes from the layout, the screen kind from the window width.
|
|
*/
|
|
export function WebVitals({ mode }: { mode: "product" | "engineer" }) {
|
|
const pathname = usePathname();
|
|
useEffect(() => {
|
|
if (typeof PerformanceObserver === "undefined") return;
|
|
// A soft navigation inside the app has no LCP/TTFB of its own: only the first load is measured.
|
|
if ((window as { __peppaVitals?: boolean }).__peppaVitals) return;
|
|
(window as { __peppaVitals?: boolean }).__peppaVitals = true;
|
|
const route = pathname;
|
|
let lcp = 0;
|
|
let cls = 0;
|
|
let inp = 0;
|
|
const longest: number[] = [];
|
|
const observe = (type: string, cb: (e: PerformanceEntry[]) => void, extra: object = {}) => {
|
|
try {
|
|
const o = new PerformanceObserver((l) => cb(l.getEntries()));
|
|
o.observe({ type, buffered: true, ...extra } as PerformanceObserverInit);
|
|
return o;
|
|
} catch {
|
|
return null; // the browser does not know this entry type
|
|
}
|
|
};
|
|
observe("largest-contentful-paint", (es) => {
|
|
const last = es[es.length - 1] as PerformanceEntry | undefined;
|
|
if (last) lcp = last.startTime;
|
|
});
|
|
observe("layout-shift", (es) => {
|
|
for (const e of es as Array<PerformanceEntry & { value: number; hadRecentInput: boolean }>) if (!e.hadRecentInput) cls += e.value;
|
|
});
|
|
// INP: the slowest interaction (p98 of the worst ones, simplified to the 2nd worst after 50).
|
|
observe(
|
|
"event",
|
|
(es) => {
|
|
for (const e of es as Array<PerformanceEntry & { interactionId?: number }>) {
|
|
if (!e.interactionId) continue;
|
|
longest.push(e.duration);
|
|
longest.sort((a, b) => b - a);
|
|
longest.length = Math.min(longest.length, 10);
|
|
}
|
|
inp = longest.length > 50 ? longest[1]! : (longest[0] ?? 0);
|
|
},
|
|
{ durationThreshold: 40 },
|
|
);
|
|
let sent = false;
|
|
const flush = () => {
|
|
if (sent) return;
|
|
const metrics: Array<{ metric: Metric; value: number }> = [];
|
|
const nav = performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming | undefined;
|
|
if (nav && nav.responseStart > 0) metrics.push({ metric: "TTFB", value: nav.responseStart });
|
|
if (lcp > 0) metrics.push({ metric: "LCP", value: lcp });
|
|
metrics.push({ metric: "CLS", value: cls });
|
|
if (inp > 0) metrics.push({ metric: "INP", value: inp });
|
|
if (!metrics.length) return;
|
|
sent = true;
|
|
const body = JSON.stringify({ route, device: window.innerWidth < 768 ? "narrow" : "wide", mode, metrics });
|
|
try {
|
|
if (!navigator.sendBeacon?.("/api/client-vitals", new Blob([body], { type: "application/json" }))) {
|
|
void fetch("/api/client-vitals", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {});
|
|
}
|
|
} catch {
|
|
/* measuring must never break the page */
|
|
}
|
|
};
|
|
const onHide = () => {
|
|
if (document.visibilityState === "hidden") flush();
|
|
};
|
|
document.addEventListener("visibilitychange", onHide);
|
|
window.addEventListener("pagehide", flush);
|
|
// A page left open for a long time still reports once.
|
|
const timer = setTimeout(flush, 60_000);
|
|
return () => {
|
|
// Never cleaned during soft navigation (the effect runs once per tab): nothing to undo.
|
|
void timer;
|
|
};
|
|
}, [pathname, mode]);
|
|
return null;
|
|
}
|