Skip to content

Commit

Permalink
Use reusable analytics client (#2005)
Browse files Browse the repository at this point in the history
  • Loading branch information
visnup authored Feb 26, 2024
1 parent a07bab7 commit 41a63e3
Showing 1 changed file with 5 additions and 49 deletions.
54 changes: 5 additions & 49 deletions docs/.vitepress/theme/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,60 +17,16 @@ export default {
}
};

function enableAnalytics(router) {
async function enableAnalytics(router) {
if (typeof location === "undefined" || location.origin !== "https://observablehq.com") return;

const {pageLoad, routeChanged} = await import("https://events.observablehq.com/client.js");
let pageLoaded;
let queue: any[] | null = [];
let user;

watch(router.route, () => {
if (pageLoaded) {
emit({
type: "routeChanged",
event_version: 2,
data: {},
tags: {}
});
routeChanged();
} else {
emit({
type: "pageLoad",
event_version: 1,
data: {referrer: document.referrer.replace(/\?.*/, "")},
tags: {}
});
pageLoad();
pageLoaded = true;
}
});

fetch("https://api.observablehq.com/user", {credentials: "include"})
.then((response) => (response.ok ? response.json() : null))
.then(
(u) => (user = u),
() => (user = null)
)
.then(() => (sendEvents(queue), (queue = null)));

function emit(event) {
event.time = new Date().toISOString();
event.location = `${location.origin}${location.pathname}${location.search}`; // drop hash
if (queue) queue.push(event);
else sendEvents([event]);
}

function sendEvents(events) {
if (!events.length) return;
navigator.sendBeacon(
"https://events.observablehq.com/beacon-events",
JSON.stringify({
events: events.map((event) => ({
...event,
release: null,
user_id: user?.id ?? null,
user_agent: navigator.userAgent
})),
send_time: new Date().toISOString()
})
);
}
}
}

0 comments on commit 41a63e3

Please sign in to comment.