mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-16 15:45:13 +00:00
Track site insight event when opening scalar client (#2658)
This commit is contained in:
@@ -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.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Track an event into site insights when visitor is opening the Scalar API client.
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@gitbook/api": "^0.84.0",
|
"@gitbook/api": "^0.85.0",
|
||||||
"@gitbook/cache-do": "workspace:*",
|
"@gitbook/cache-do": "workspace:*",
|
||||||
"@gitbook/emoji-codepoints": "workspace:*",
|
"@gitbook/emoji-codepoints": "workspace:*",
|
||||||
"@gitbook/icons": "workspace:*",
|
"@gitbook/icons": "workspace:*",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { DocumentBlockSwagger } from '@gitbook/api';
|
import { DocumentBlockOpenAPI } from '@gitbook/api';
|
||||||
import { Icon } from '@gitbook/icons';
|
import { Icon } from '@gitbook/icons';
|
||||||
import { OpenAPIOperation } from '@gitbook/react-openapi';
|
import { OpenAPIOperation } from '@gitbook/react-openapi';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
@@ -16,7 +16,7 @@ import './scalar.css';
|
|||||||
/**
|
/**
|
||||||
* Render an OpenAPI block.
|
* Render an OpenAPI block.
|
||||||
*/
|
*/
|
||||||
export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
|
export async function OpenAPI(props: BlockProps<DocumentBlockOpenAPI>) {
|
||||||
const { block, style } = props;
|
const { block, style } = props;
|
||||||
return (
|
return (
|
||||||
<div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}>
|
<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 { block, context } = props;
|
||||||
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
|
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import type * as api from '@gitbook/api';
|
import type * as api from '@gitbook/api';
|
||||||
|
import { OpenAPIOperationContextProvider } from '@gitbook/react-openapi';
|
||||||
import cookies from 'js-cookie';
|
import cookies from 'js-cookie';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
|
import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
|
||||||
@@ -8,6 +9,11 @@ import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
|
|||||||
import { getSession } from './sessions';
|
import { getSession } from './sessions';
|
||||||
import { getVisitorId } from './visitorId';
|
import { getVisitorId } from './visitorId';
|
||||||
|
|
||||||
|
type SiteEventName = api.SiteInsightsEvent['type'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Global context for all events in the session.
|
||||||
|
*/
|
||||||
interface InsightsEventContext {
|
interface InsightsEventContext {
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
siteId: string;
|
siteId: string;
|
||||||
@@ -17,21 +23,40 @@ interface InsightsEventContext {
|
|||||||
siteShareKey: string | undefined;
|
siteShareKey: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Context for an event on a page.
|
||||||
|
*/
|
||||||
interface InsightsEventPageContext {
|
interface InsightsEventPageContext {
|
||||||
pageId: string | null;
|
pageId: string | null;
|
||||||
revisionId: string;
|
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<
|
type TrackEventInput<EventName extends SiteEventName> = { type: EventName } & Omit<
|
||||||
Extract<api.SiteInsightsEvent, { type: EventName }>,
|
Extract<api.SiteInsightsEvent, { type: EventName }>,
|
||||||
'location' | 'session'
|
'location' | 'session'
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback to track an event.
|
||||||
|
*/
|
||||||
type TrackEventCallback = <EventName extends SiteEventName>(
|
type TrackEventCallback = <EventName extends SiteEventName>(
|
||||||
event: TrackEventInput<EventName>,
|
event: TrackEventInput<EventName>,
|
||||||
ctx?: InsightsEventPageContext,
|
ctx?: InsightsEventPageContext,
|
||||||
|
options?: InsightsEventOptions,
|
||||||
) => void;
|
) => void;
|
||||||
|
|
||||||
const InsightsContext = React.createContext<TrackEventCallback | null>(null);
|
const InsightsContext = React.createContext<TrackEventCallback | null>(null);
|
||||||
@@ -48,6 +73,7 @@ interface InsightsProviderProps extends InsightsEventContext {
|
|||||||
export function InsightsProvider(props: InsightsProviderProps) {
|
export function InsightsProvider(props: InsightsProviderProps) {
|
||||||
const { enabled, apiHost, children, ...context } = props;
|
const { enabled, apiHost, children, ...context } = props;
|
||||||
|
|
||||||
|
const visitorIdRef = React.useRef<string | null>(null);
|
||||||
const eventsRef = React.useRef<{
|
const eventsRef = React.useRef<{
|
||||||
[pathname: string]:
|
[pathname: string]:
|
||||||
| {
|
| {
|
||||||
@@ -59,9 +85,12 @@ export function InsightsProvider(props: InsightsProviderProps) {
|
|||||||
| undefined;
|
| undefined;
|
||||||
}>({});
|
}>({});
|
||||||
|
|
||||||
const flushEvents = useDebounceCallback(async (pathname: string) => {
|
const flushEventsSync = (pathname: string) => {
|
||||||
const visitorId = await getVisitorId();
|
const visitorId = visitorIdRef.current;
|
||||||
const session = await getSession();
|
if (!visitorId) {
|
||||||
|
throw new Error('Visitor ID not set');
|
||||||
|
}
|
||||||
|
const session = getSession();
|
||||||
|
|
||||||
const eventsForPathname = eventsRef.current[pathname];
|
const eventsForPathname = eventsRef.current[pathname];
|
||||||
if (!eventsForPathname || !eventsForPathname.pageContext) {
|
if (!eventsForPathname || !eventsForPathname.pageContext) {
|
||||||
@@ -86,19 +115,30 @@ export function InsightsProvider(props: InsightsProviderProps) {
|
|||||||
|
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
console.log('Sending events', events);
|
console.log('Sending events', events);
|
||||||
await sendEvents({
|
sendEvents({
|
||||||
apiHost,
|
apiHost,
|
||||||
organizationId: context.organizationId,
|
organizationId: context.organizationId,
|
||||||
siteId: context.siteId,
|
siteId: context.siteId,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
} else {
|
} 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);
|
}, 500);
|
||||||
|
|
||||||
const trackEvent = useEventCallback(
|
const trackEvent: TrackEventCallback = useEventCallback(
|
||||||
(event: TrackEventInput<SiteEventName>, ctx?: InsightsEventPageContext) => {
|
(
|
||||||
|
event: TrackEventInput<SiteEventName>,
|
||||||
|
ctx?: InsightsEventPageContext,
|
||||||
|
options?: InsightsEventOptions,
|
||||||
|
) => {
|
||||||
console.log('Logging event', event, ctx);
|
console.log('Logging event', event, ctx);
|
||||||
|
|
||||||
const pathname = window.location.pathname;
|
const pathname = window.location.pathname;
|
||||||
@@ -113,12 +153,26 @@ export function InsightsProvider(props: InsightsProviderProps) {
|
|||||||
if (eventsRef.current[pathname].pageContext !== undefined) {
|
if (eventsRef.current[pathname].pageContext !== undefined) {
|
||||||
// If the pageId is set, we know that the page_view event has been tracked
|
// If the pageId is set, we know that the page_view event has been tracked
|
||||||
// and we can flush the events
|
// 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.
|
* Post the events to the server.
|
||||||
*/
|
*/
|
||||||
async function sendEvents(args: {
|
function sendEvents(args: {
|
||||||
apiHost: string;
|
apiHost: string;
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
siteId: string;
|
siteId: string;
|
||||||
@@ -146,11 +200,12 @@ async function sendEvents(args: {
|
|||||||
const url = new URL(apiHost);
|
const url = new URL(apiHost);
|
||||||
url.pathname = `/v1/orgs/${organizationId}/sites/${siteId}/insights/events`;
|
url.pathname = `/v1/orgs/${organizationId}/sites/${siteId}/insights/events`;
|
||||||
|
|
||||||
await fetch(url, {
|
fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
|
keepalive: true,
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
events,
|
events,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ContentRef, DocumentBlockSwagger } from '@gitbook/api';
|
import { ContentRef, DocumentBlockOpenAPI } from '@gitbook/api';
|
||||||
import {
|
import {
|
||||||
OpenAPIOperationData,
|
OpenAPIOperationData,
|
||||||
fetchOpenAPIOperation,
|
fetchOpenAPIOperation,
|
||||||
@@ -16,7 +16,7 @@ import { ResolvedContentRef } from './references';
|
|||||||
* Fetch an OpenAPI specification for an operation.
|
* Fetch an OpenAPI specification for an operation.
|
||||||
*/
|
*/
|
||||||
export async function fetchOpenAPIBlock(
|
export async function fetchOpenAPIBlock(
|
||||||
block: DocumentBlockSwagger,
|
block: DocumentBlockOpenAPI,
|
||||||
resolveContentRef: (ref: ContentRef) => Promise<ResolvedContentRef | null>,
|
resolveContentRef: (ref: ContentRef) => Promise<ResolvedContentRef | null>,
|
||||||
): Promise<
|
): Promise<
|
||||||
| { data: OpenAPIOperationData | null; specUrl: string | null; error?: undefined }
|
| { data: OpenAPIOperationData | null; specUrl: string | null; error?: undefined }
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"classnames": "^2.5.1",
|
"classnames": "^2.5.1",
|
||||||
"@gitbook/api": "^0.84.0",
|
"@gitbook/api": "^0.85.0",
|
||||||
"assert-never": "^1.2.1"
|
"assert-never": "^1.2.1"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
|
|||||||
@@ -15,7 +15,8 @@
|
|||||||
"flatted": "^3.2.9",
|
"flatted": "^3.2.9",
|
||||||
"openapi-types": "^12.1.3",
|
"openapi-types": "^12.1.3",
|
||||||
"swagger2openapi": "^7.0.8",
|
"swagger2openapi": "^7.0.8",
|
||||||
"yaml": "1.10.2"
|
"yaml": "1.10.2",
|
||||||
|
"usehooks-ts": "^3.1.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/swagger2openapi": "^7.0.4",
|
"@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 { useApiClientModal } from '@scalar/api-client-react';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
|
import { useOpenAPIOperationContext } from './OpenAPIOperationContext';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Button which launches the Scalar API Client
|
* Button which launches the Scalar API Client
|
||||||
*/
|
*/
|
||||||
export function ScalarApiButton({ method, path }: { method: string; path: string }) {
|
export function ScalarApiButton({ method, path }: { method: string; path: string }) {
|
||||||
const client = useApiClientModal();
|
const client = useApiClientModal();
|
||||||
|
const { onOpenClient } = useOpenAPIOperationContext();
|
||||||
return (
|
return (
|
||||||
<div className="scalar scalar-activate">
|
<div className="scalar scalar-activate">
|
||||||
<button
|
<button
|
||||||
className="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">
|
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" fill="none">
|
||||||
<path
|
<path
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from './fetchOpenAPIOperation';
|
export * from './fetchOpenAPIOperation';
|
||||||
export * from './OpenAPIOperation';
|
export * from './OpenAPIOperation';
|
||||||
export type { OpenAPIFetcher } from './types';
|
export type { OpenAPIFetcher } from './types';
|
||||||
|
export * from './OpenAPIOperationContext';
|
||||||
|
|||||||
Reference in New Issue
Block a user