返回 CodeWhale
usage-counting.tsx
根目录 / web / components / usage-counting.tsx
1 "use client";
2
3 /**
4 * Usage counting on the website — the recorder owner and the
5 * privacy-page control.
6 *
7 * <UsageCounting> Mounted once in the locale layout. Renders
8 * nothing. Counts `page_view` on every route
9 * change (`docs_view` too on docs routes) and any
10 * element carrying `data-usage="<counter>"` when it
11 * is clicked; flushes once after a pause or on
12 * pagehide. `recordUsage()` is the import for
13 * client components (copy buttons, the error
14 * boundary).
15 * <UsagePreferenceControl> The only place on the site that shows or changes
16 * the choice. It lives on the privacy page, not in
17 * a banner: counting is on by default, every
18 * opt-out stays off, and other tabs follow through
19 * the `storage` event.
20 *
21 * Nothing renders on the server, so the page is complete and static without
22 * it; reduced motion is respected because there is no motion.
23 */
24
25 import { usePathname } from "next/navigation";
26 import { useCallback, useEffect, useState } from "react";
27 import { USAGE_COUNTING_COPY } from "@/lib/content/usage-counting";
28 import { pickText } from "@/lib/i18n/dictionaries";
29 import { funnelExit, funnelPath } from "@/lib/telemetry/funnel";
30 import {
31 PREFERENCE_STORAGE_KEY,
32 PRODUCT_COUNTER_FIELDS,
33 FUNNEL_COUNTER_FIELDS,
34 type FunnelCounter,
35 createUsageRecorder,
36 privacySignalActive,
37 type ProductCounter,
38 type UsagePreference,
39 type UsageRecorder,
40 } from "@/lib/telemetry/product-usage";
41
42 const ENDPOINT = "/api/product-telemetry";
43
44 let recorder: UsageRecorder | null = null;
45
46 function getRecorder(appVersion: string): UsageRecorder | null {
47 if (typeof window === "undefined") return null;
48 if (!recorder) {
49 let storage: Storage | null = null;
50 try {
51 storage = window.localStorage;
52 } catch {
53 storage = null;
54 }
55 if (!storage) return null;
56 recorder = createUsageRecorder({
57 surface: "website",
58 appVersion,
59 endpoint: ENDPOINT,
60 storage,
61 blocked: () => privacySignalActive(),
62 });
63 }
64 return recorder;
65 }
66
67 /** Count one interaction. A no-op while counting is turned off. */
68 export function recordUsage(counter: ProductCounter): void {
69 recorder?.record(counter);
70 }
71
72 export function recordFunnel(counter: FunnelCounter): void {
73 recorder?.recordFunnel(counter);
74 }
75
76 function isCounter(value: string | undefined): value is ProductCounter {
77 return value !== undefined && (PRODUCT_COUNTER_FIELDS as readonly string[]).includes(value);
78 }
79
80 export function UsageCounting({ appVersion }: { appVersion: string }) {
81 const pathname = usePathname();
82
83 useEffect(() => {
84 const current = getRecorder(appVersion);
85 if (!current) return;
86 const onStorage = (event: StorageEvent) => {
87 if (event.key !== null && event.key !== PREFERENCE_STORAGE_KEY) return;
88 current.sync();
89 };
90 const onClick = (event: MouseEvent) => {
91 const target = event.target instanceof Element ? event.target : null;
92 const marked = target?.closest<HTMLElement>("[data-usage]");
93 const counter = marked?.dataset.usage;
94 if (isCounter(counter)) current.record(counter);
95 const explicit = target?.closest<HTMLElement>("[data-funnel]")?.dataset.funnel;
96 const link = target?.closest<HTMLAnchorElement>("a[href]");
97 const funnel = explicit && (FUNNEL_COUNTER_FIELDS as readonly string[]).includes(explicit)
98 ? explicit as FunnelCounter : link ? funnelExit(link.href) : null;
99 if (funnel) current.recordFunnel(funnel);
100 };
101 const onPageHide = () => {
102 void current.flush();
103 };
104 window.addEventListener("storage", onStorage);
105 document.addEventListener("click", onClick);
106 window.addEventListener("pagehide", onPageHide);
107 return () => {
108 window.removeEventListener("storage", onStorage);
109 document.removeEventListener("click", onClick);
110 window.removeEventListener("pagehide", onPageHide);
111 };
112 }, [appVersion]);
113
114 // Every route change is one page view; registered docs destinations are also a docs view.
115 useEffect(() => {
116 const current = getRecorder(appVersion);
117 if (!current || !pathname) return;
118 current.record("page_view");
119 const route = funnelPath(pathname);
120 if (route.documentation) current.record("docs_view");
121 if (route.view) current.recordFunnel(route.view);
122 }, [appVersion, pathname]);
123
124 return null;
125 }
126
127 /** The privacy page's status line and opt-out control. */
128 export function UsagePreferenceControl({ locale, appVersion }: { locale: string; appVersion: string }) {
129 // `null` until mounted; `"unavailable"` when the browser offers no storage.
130 const [preference, setPreference] = useState<UsagePreference | "unavailable" | "unsaved" | "signal" | null>(null);
131 const t = (text: { en: string; zh: string }) => pickText(text, locale);
132
133 useEffect(() => {
134 if (privacySignalActive()) {
135 setPreference("signal");
136 return;
137 }
138 const current = getRecorder(appVersion);
139 if (!current) {
140 setPreference("unavailable");
141 return;
142 }
143 setPreference(current.preference());
144 const onStorage = (event: StorageEvent) => {
145 if (event.key !== null && event.key !== PREFERENCE_STORAGE_KEY) return;
146 setPreference(current.preference());
147 };
148 window.addEventListener("storage", onStorage);
149 return () => window.removeEventListener("storage", onStorage);
150 }, [appVersion]);
151
152 const toggle = useCallback(() => {
153 const current = getRecorder(appVersion);
154 if (!current) return;
155 const saved = current.preference() === "off" ? current.enable() : current.disable();
156 setPreference(saved ? current.preference() : "unsaved");
157 }, [appVersion]);
158
159 const off = preference === "off" || preference === "unsaved";
160 return (
161 <div className="usage-counting" data-state={preference ?? "loading"}>
162 <p>{t(USAGE_COUNTING_COPY.summary)}</p>
163 <p>{t(USAGE_COUNTING_COPY.choice)}</p>
164 {preference !== null && (
165 <p className="usage-counting-status" role="status">
166 {t(USAGE_COUNTING_COPY.status[preference])}
167 </p>
168 )}
169 {preference !== null && preference !== "unavailable" && preference !== "signal" && (
170 <button type="button" className="usage-counting-button" onClick={toggle} aria-pressed={!off}>
171 {off ? t(USAGE_COUNTING_COPY.turnOn) : t(USAGE_COUNTING_COPY.turnOff)}
172 </button>
173 )}
174 <p className="usage-counting-elsewhere">{t(USAGE_COUNTING_COPY.elsewhere)}</p>
175 </div>
176 );
177 }
178
178 lines Plain Text