Track site insight event when opening scalar client (#2658)

This commit is contained in:
Samy Pessé
2024-12-21 15:57:10 +01:00
committed by GitHub
parent fc7b16f6a7
commit e4e2f524d4
12 changed files with 138 additions and 22 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Add an optional client context to get a callback called when the Scalar client is opened for a block.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Track an event into site insights when visitor is opening the Scalar API client.
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
},
"dependencies": {
"@gitbook/api": "^0.84.0",
"@gitbook/api": "^0.85.0",
"@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*",
@@ -1,4 +1,4 @@
import { DocumentBlockSwagger } from '@gitbook/api';
import { DocumentBlockOpenAPI } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { OpenAPIOperation } from '@gitbook/react-openapi';
import React from 'react';
@@ -16,7 +16,7 @@ import './scalar.css';
/**
* Render an OpenAPI block.
*/
export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
export async function OpenAPI(props: BlockProps<DocumentBlockOpenAPI>) {
const { block, style } = props;
return (
<div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}>
@@ -27,7 +27,7 @@ export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
);
}
async function OpenAPIBody(props: BlockProps<DocumentBlockSwagger>) {
async function OpenAPIBody(props: BlockProps<DocumentBlockOpenAPI>) {
const { block, context } = props;
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
@@ -1,6 +1,7 @@
'use client';
import type * as api from '@gitbook/api';
import { OpenAPIOperationContextProvider } from '@gitbook/react-openapi';
import cookies from 'js-cookie';
import * as React from 'react';
import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
@@ -8,6 +9,11 @@ import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
import { getSession } from './sessions';
import { getVisitorId } from './visitorId';
type SiteEventName = api.SiteInsightsEvent['type'];
/**
* Global context for all events in the session.
*/
interface InsightsEventContext {
organizationId: string;
siteId: string;
@@ -17,21 +23,40 @@ interface InsightsEventContext {
siteShareKey: string | undefined;
}
/**
* Context for an event on a page.
*/
interface InsightsEventPageContext {
pageId: string | null;
revisionId: string;
}
type SiteEventName = api.SiteInsightsEvent['type'];
/**
* Options when tracking an event.
*/
interface InsightsEventOptions {
/**
* If true, the event will be sent immediately.
* Passes true for events that could cause a page unload.
*/
immediate?: boolean;
}
/**
* Input data for an event.
*/
type TrackEventInput<EventName extends SiteEventName> = { type: EventName } & Omit<
Extract<api.SiteInsightsEvent, { type: EventName }>,
'location' | 'session'
>;
/**
* Callback to track an event.
*/
type TrackEventCallback = <EventName extends SiteEventName>(
event: TrackEventInput<EventName>,
ctx?: InsightsEventPageContext,
options?: InsightsEventOptions,
) => void;
const InsightsContext = React.createContext<TrackEventCallback | null>(null);
@@ -48,6 +73,7 @@ interface InsightsProviderProps extends InsightsEventContext {
export function InsightsProvider(props: InsightsProviderProps) {
const { enabled, apiHost, children, ...context } = props;
const visitorIdRef = React.useRef<string | null>(null);
const eventsRef = React.useRef<{
[pathname: string]:
| {
@@ -59,9 +85,12 @@ export function InsightsProvider(props: InsightsProviderProps) {
| undefined;
}>({});
const flushEvents = useDebounceCallback(async (pathname: string) => {
const visitorId = await getVisitorId();
const session = await getSession();
const flushEventsSync = (pathname: string) => {
const visitorId = visitorIdRef.current;
if (!visitorId) {
throw new Error('Visitor ID not set');
}
const session = getSession();
const eventsForPathname = eventsRef.current[pathname];
if (!eventsForPathname || !eventsForPathname.pageContext) {
@@ -86,19 +115,30 @@ export function InsightsProvider(props: InsightsProviderProps) {
if (enabled) {
console.log('Sending events', events);
await sendEvents({
sendEvents({
apiHost,
organizationId: context.organizationId,
siteId: context.siteId,
events,
});
} else {
console.log('Events not sent', events);
console.log('Skipping sending events', events);
}
};
const flushBatchedEvents = useDebounceCallback(async (pathname: string) => {
const visitorId = visitorIdRef.current ?? (await getVisitorId());
visitorIdRef.current = visitorId;
flushEventsSync(pathname);
}, 500);
const trackEvent = useEventCallback(
(event: TrackEventInput<SiteEventName>, ctx?: InsightsEventPageContext) => {
const trackEvent: TrackEventCallback = useEventCallback(
(
event: TrackEventInput<SiteEventName>,
ctx?: InsightsEventPageContext,
options?: InsightsEventOptions,
) => {
console.log('Logging event', event, ctx);
const pathname = window.location.pathname;
@@ -113,12 +153,26 @@ export function InsightsProvider(props: InsightsProviderProps) {
if (eventsRef.current[pathname].pageContext !== undefined) {
// If the pageId is set, we know that the page_view event has been tracked
// and we can flush the events
flushEvents(pathname);
if (options?.immediate && visitorIdRef.current) {
flushEventsSync(pathname);
} else {
flushBatchedEvents(pathname);
}
}
},
);
return <InsightsContext.Provider value={trackEvent}>{props.children}</InsightsContext.Provider>;
return (
<InsightsContext.Provider value={trackEvent}>
<OpenAPIOperationContextProvider
onOpenClient={(operation) => {
trackEvent({ type: 'api_client_open', operation });
}}
>
{props.children}
</OpenAPIOperationContextProvider>
</InsightsContext.Provider>
);
}
/**
@@ -136,7 +190,7 @@ export function useTrackEvent(): TrackEventCallback {
/**
* Post the events to the server.
*/
async function sendEvents(args: {
function sendEvents(args: {
apiHost: string;
organizationId: string;
siteId: string;
@@ -146,11 +200,12 @@ async function sendEvents(args: {
const url = new URL(apiHost);
url.pathname = `/v1/orgs/${organizationId}/sites/${siteId}/insights/events`;
await fetch(url, {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
keepalive: true,
body: JSON.stringify({
events,
}),
+2 -2
View File
@@ -1,4 +1,4 @@
import { ContentRef, DocumentBlockSwagger } from '@gitbook/api';
import { ContentRef, DocumentBlockOpenAPI } from '@gitbook/api';
import {
OpenAPIOperationData,
fetchOpenAPIOperation,
@@ -16,7 +16,7 @@ import { ResolvedContentRef } from './references';
* Fetch an OpenAPI specification for an operation.
*/
export async function fetchOpenAPIBlock(
block: DocumentBlockSwagger,
block: DocumentBlockOpenAPI,
resolveContentRef: (ref: ContentRef) => Promise<ResolvedContentRef | null>,
): Promise<
| { data: OpenAPIOperationData | null; specUrl: string | null; error?: undefined }
+1 -1
View File
@@ -10,7 +10,7 @@
},
"dependencies": {
"classnames": "^2.5.1",
"@gitbook/api": "^0.84.0",
"@gitbook/api": "^0.85.0",
"assert-never": "^1.2.1"
},
"peerDependencies": {
+2 -1
View File
@@ -15,7 +15,8 @@
"flatted": "^3.2.9",
"openapi-types": "^12.1.3",
"swagger2openapi": "^7.0.8",
"yaml": "1.10.2"
"yaml": "1.10.2",
"usehooks-ts": "^3.1.0"
},
"devDependencies": {
"@types/swagger2openapi": "^7.0.4",
@@ -0,0 +1,44 @@
'use client';
import * as React from 'react';
import { useEventCallback } from 'usehooks-ts';
interface OpenAPIOperationPointer {
path: string;
method: string;
}
interface OpenAPIOperationContextValue {
onOpenClient: (pointer: OpenAPIOperationPointer) => void;
}
const OpenAPIOperationContext = React.createContext<OpenAPIOperationContextValue>({
onOpenClient: () => {},
});
/**
* Provider for the OpenAPIOperationContext.
*/
export function OpenAPIOperationContextProvider(
props: React.PropsWithChildren<Partial<OpenAPIOperationContextValue>>,
) {
const { children } = props;
const onOpenClient = useEventCallback((pointer: OpenAPIOperationPointer) => {
props.onOpenClient?.(pointer);
});
const value = React.useMemo(() => ({ onOpenClient }), [onOpenClient]);
return (
<OpenAPIOperationContext.Provider value={value}>
{children}
</OpenAPIOperationContext.Provider>
);
}
/**
* Hook to access the OpenAPIOperationContext.
*/
export function useOpenAPIOperationContext() {
return React.useContext(OpenAPIOperationContext);
}
@@ -3,17 +3,22 @@
import { useApiClientModal } from '@scalar/api-client-react';
import React from 'react';
import { useOpenAPIOperationContext } from './OpenAPIOperationContext';
/**
* Button which launches the Scalar API Client
*/
export function ScalarApiButton({ method, path }: { method: string; path: string }) {
const client = useApiClientModal();
const { onOpenClient } = useOpenAPIOperationContext();
return (
<div className="scalar scalar-activate">
<button
className="scalar-activate-button"
onClick={() => client?.open({ method, path, _source: 'gitbook' })}
onClick={() => {
client?.open({ method, path, _source: 'gitbook' });
onOpenClient({ method, path });
}}
>
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" fill="none">
<path
+1
View File
@@ -1,3 +1,4 @@
export * from './fetchOpenAPIOperation';
export * from './OpenAPIOperation';
export type { OpenAPIFetcher } from './types';
export * from './OpenAPIOperationContext';