Skip to content

Commit 41a63e3

Browse files
authored
Use reusable analytics client (#2005)
1 parent a07bab7 commit 41a63e3

File tree

1 file changed

+5
-49
lines changed

1 file changed

+5
-49
lines changed

docs/.vitepress/theme/index.ts

Lines changed: 5 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -17,60 +17,16 @@ export default {
1717
}
1818
};
1919

20-
function enableAnalytics(router) {
20+
async function enableAnalytics(router) {
2121
if (typeof location === "undefined" || location.origin !== "https://observablehq.com") return;
22-
22+
const {pageLoad, routeChanged} = await import("https://events.observablehq.com/client.js");
2323
let pageLoaded;
24-
let queue: any[] | null = [];
25-
let user;
26-
2724
watch(router.route, () => {
2825
if (pageLoaded) {
29-
emit({
30-
type: "routeChanged",
31-
event_version: 2,
32-
data: {},
33-
tags: {}
34-
});
26+
routeChanged();
3527
} else {
36-
emit({
37-
type: "pageLoad",
38-
event_version: 1,
39-
data: {referrer: document.referrer.replace(/\?.*/, "")},
40-
tags: {}
41-
});
28+
pageLoad();
4229
pageLoaded = true;
4330
}
4431
});
45-
46-
fetch("https://api.observablehq.com/user", {credentials: "include"})
47-
.then((response) => (response.ok ? response.json() : null))
48-
.then(
49-
(u) => (user = u),
50-
() => (user = null)
51-
)
52-
.then(() => (sendEvents(queue), (queue = null)));
53-
54-
function emit(event) {
55-
event.time = new Date().toISOString();
56-
event.location = `${location.origin}${location.pathname}${location.search}`; // drop hash
57-
if (queue) queue.push(event);
58-
else sendEvents([event]);
59-
}
60-
61-
function sendEvents(events) {
62-
if (!events.length) return;
63-
navigator.sendBeacon(
64-
"https://events.observablehq.com/beacon-events",
65-
JSON.stringify({
66-
events: events.map((event) => ({
67-
...event,
68-
release: null,
69-
user_id: user?.id ?? null,
70-
user_agent: navigator.userAgent
71-
})),
72-
send_time: new Date().toISOString()
73-
})
74-
);
75-
}
76-
}
32+
}

0 commit comments

Comments
 (0)