Compare commits

...

4 Commits

Author SHA1 Message Date
Scott Cazan ae0a94609b fix api call 2024-12-20 09:41:17 +01:00
Scott Cazan dcc029c114 check for multi-id mode 2024-12-20 09:36:49 +01:00
Scott Cazan bd4b54c1bb cleanup unnecessary function and data 2024-12-20 09:28:25 +01:00
Scott Cazan 51d84c0169 add siteSpaceId to page view event 2024-12-20 09:26:17 +01:00
2 changed files with 16 additions and 36 deletions
@@ -149,7 +149,6 @@ export function PageBody(props: {
{shouldTrackPageViews() ? (
<TrackPageView
sitePointer={pointer}
spaceId={space.id}
pageId={page.id}
apiHost={api().client.endpoint}
/>
@@ -1,6 +1,6 @@
'use client';
import type { RequestSiteTrackPageView, RequestSpaceTrackPageView } from '@gitbook/api';
import type { RequestSiteTrackPageView } from '@gitbook/api';
import cookies from 'js-cookie';
import * as React from 'react';
@@ -13,36 +13,17 @@ import { SiteContentPointer } from '@/lib/api';
export function TrackPageView(props: {
apiHost: string;
sitePointer: SiteContentPointer;
spaceId: string;
pageId: string | undefined;
}) {
const { apiHost, sitePointer, spaceId, pageId } = props;
const { apiHost, sitePointer, pageId } = props;
React.useEffect(() => {
trackPageView({ apiHost, sitePointer, spaceId, pageId });
}, [apiHost, spaceId, pageId, sitePointer]);
trackPageView({ apiHost, sitePointer, pageId });
}, [apiHost, pageId, sitePointer]);
return null;
}
async function sendSpaceTrackPageViewRequest(args: {
apiHost: string;
spaceId: string;
body: RequestSpaceTrackPageView;
}) {
const { apiHost, spaceId, body } = args;
const url = new URL(apiHost);
url.pathname = `/v1/spaces/${spaceId}/insights/track_view`;
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
async function sendSiteTrackPageViewRequest(args: {
apiHost: string;
sitePointer: SiteContentPointer;
@@ -71,10 +52,9 @@ let latestPageId: string | undefined | null = null;
async function trackPageView(args: {
apiHost: string;
sitePointer: SiteContentPointer;
spaceId: string;
pageId: string | undefined;
}) {
const { apiHost, sitePointer, pageId, spaceId } = args;
const { apiHost, sitePointer, pageId } = args;
if (pageId === latestPageId) {
// The hook can be called multiple times, we only want to track once.
return;
@@ -96,16 +76,17 @@ async function trackPageView(args: {
};
try {
sitePointer
? await sendSiteTrackPageViewRequest({
apiHost,
sitePointer,
body: {
...sharedTrackedProps,
spaceId,
},
})
: await sendSpaceTrackPageViewRequest({ apiHost, spaceId, body: sharedTrackedProps });
// siteSpaceId is only undefined in mult-id mode (site previews) so we skip the tracking for those
if (sitePointer.siteSpaceId) {
await sendSiteTrackPageViewRequest({
apiHost,
sitePointer,
body: {
...sharedTrackedProps,
siteSpaceId: sitePointer.siteSpaceId,
},
});
}
} catch (error) {
console.error('Failed to track page view', error);
}