mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-27 10:43:32 +00:00
Emit a navigate event from the Docs Embed
The embed docs described `frame.on('navigate', ...)` but the event was never
implemented. The frame now tells the host which docs page (path, URL, title)
or tab the reader is on, and hosts can listen through `frame.on`, the new
`onNavigate`/`onClose`/`onEscape` props of `<GitBookFrame>`, and the new
`GitBook('on', ...)` call of the standalone script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -72,6 +72,19 @@ GitBook('configure', {
|
||||
|
||||
See the [Configuration](#configuration) section for all available options.
|
||||
|
||||
### Example: Listening to events
|
||||
|
||||
```javascript
|
||||
// The reader opened a page in the docs tab, or switched to the assistant or search tab
|
||||
GitBook('on', 'navigate', (event) => {
|
||||
if (event.tab === 'docs') {
|
||||
console.log('Reading', event.title, event.path, event.url);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
`GitBook('on', ...)` returns a function that removes the listener once the script has loaded. See [Events](#events).
|
||||
|
||||
## As a package from NPM
|
||||
|
||||
Install the package: `npm install @gitbook/embed` and import it in your web application:
|
||||
@@ -132,6 +145,11 @@ frame.on('close', () => {
|
||||
frame.on('escape', () => {
|
||||
closeHelpPanel();
|
||||
});
|
||||
|
||||
// The reader opened a page in the docs tab, or switched to another tab
|
||||
const unsubscribe = frame.on('navigate', (event) => {
|
||||
console.log('Navigated to:', event.tab === 'docs' ? event.path : event.tab);
|
||||
});
|
||||
```
|
||||
|
||||
## As React components
|
||||
@@ -162,6 +180,12 @@ import { GitBookProvider, GitBookFrame } from '@gitbook/embed/react';
|
||||
]}
|
||||
tools={[/* ... */]}
|
||||
closeButton
|
||||
onNavigate={(event) => {
|
||||
if (event.tab === 'docs') {
|
||||
setCurrentDocsPage(event.path);
|
||||
}
|
||||
}}
|
||||
onClose={() => setHelpPanelOpen(false)}
|
||||
/>
|
||||
</GitBookProvider>
|
||||
```
|
||||
@@ -194,7 +218,7 @@ function MyComponent() {
|
||||
| **Post message** | `GitBook('postUserMessage', message)` | `frame.postUserMessage(message)` | Via frame client |
|
||||
| **Clear chat** | `GitBook('clearChat')` | `frame.clearChat()` | Via frame client |
|
||||
| **Configure** | `GitBook('configure', settings)` | `frame.configure(settings)` | Props on `<GitBookFrame>` |
|
||||
| **Event listeners** | ❌ | `frame.on(event, listener)` | Via frame client |
|
||||
| **Event listeners** | `GitBook('on', event, listener)` | `frame.on(event, listener)` | `onNavigate`, `onClose`, `onEscape` props |
|
||||
| **Unload** | `GitBook('unload')` | ❌ | ❌ |
|
||||
|
||||
## Method Signatures
|
||||
@@ -212,6 +236,7 @@ function MyComponent() {
|
||||
- `GitBook('postUserMessage', message: string)` - Post message to chat
|
||||
- `GitBook('clearChat')` - Clear chat history
|
||||
- `GitBook('configure', settings: {...})` - Configure widget
|
||||
- `GitBook('on', event: string, listener: Function)` → `() => void` - Listen to an [event](#events); returns a function that removes the listener (once the script has loaded)
|
||||
- `GitBook('unload')` - Unload widget
|
||||
|
||||
### NPM Package
|
||||
@@ -227,17 +252,30 @@ function MyComponent() {
|
||||
- `frame.postUserMessage(message: string)` → `void`
|
||||
- `frame.clearChat()` → `void`
|
||||
- `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void`
|
||||
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). Events: `close`, `escape`
|
||||
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). See [Events](#events)
|
||||
|
||||
### React Components
|
||||
|
||||
**Components:**
|
||||
- `<GitBookProvider siteURL: string>` - Provider component
|
||||
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props)
|
||||
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props, and `onNavigate`, `onClose`, `onEscape` callbacks for the [events](#events))
|
||||
|
||||
**Hooks:**
|
||||
- `useGitBook()` → `GitBookClient` (must be used within `<GitBookProvider>`)
|
||||
|
||||
## Events
|
||||
|
||||
| Event | Listener | When |
|
||||
|-------|----------|------|
|
||||
| `navigate` | `(event: GitBookNavigateEvent) => void` | The reader opened a page in the docs tab, or switched to another tab. Also sent for the tab the embed first opens on. |
|
||||
| `close` | `() => void` | The built-in close button was clicked. |
|
||||
| `escape` | `() => void` | Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it. |
|
||||
|
||||
`GitBookNavigateEvent` is one of:
|
||||
|
||||
- `{ tab: 'docs', path: string, url: string, title: string }`: `path` is the page's path from the root of the site (e.g. `/getting-started/quickstart`) and can be passed back to `navigateToPage`; `url` is its published URL, without query parameters; `title` is the page's title.
|
||||
- `{ tab: 'assistant' }` or `{ tab: 'search' }`
|
||||
|
||||
# Configuration
|
||||
|
||||
Configuration options are available across usage methods as follows:
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { FrameToParentMessage } from './protocol';
|
||||
|
||||
// The frame talks to the iframe over postMessage; capture the receive handler to play the frame.
|
||||
let receive: (message: FrameToParentMessage) => void = () => {};
|
||||
mock.module('bidc', () => ({
|
||||
createChannel: () => ({
|
||||
send: () => {},
|
||||
receive: (handler: typeof receive) => {
|
||||
receive = handler;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { createGitBookFrame } = await import('./createGitBookFrame');
|
||||
|
||||
function createFrame() {
|
||||
return createGitBookFrame({ contentWindow: {}, allow: '' } as unknown as HTMLIFrameElement);
|
||||
}
|
||||
|
||||
describe('createGitBookFrame.on', () => {
|
||||
beforeEach(() => {
|
||||
receive = () => {};
|
||||
});
|
||||
|
||||
it('calls navigate listeners with the page the reader moved to', () => {
|
||||
const frame = createFrame();
|
||||
const events: unknown[] = [];
|
||||
frame.on('navigate', (event) => events.push(event));
|
||||
|
||||
receive({
|
||||
type: 'navigate',
|
||||
tab: 'docs',
|
||||
path: '/getting-started/quickstart',
|
||||
url: 'https://example.com/docs/getting-started/quickstart',
|
||||
title: 'Quickstart',
|
||||
});
|
||||
|
||||
expect(events).toEqual([
|
||||
{
|
||||
tab: 'docs',
|
||||
path: '/getting-started/quickstart',
|
||||
url: 'https://example.com/docs/getting-started/quickstart',
|
||||
title: 'Quickstart',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('calls navigate listeners when the reader switches to another tab', () => {
|
||||
const frame = createFrame();
|
||||
const events: unknown[] = [];
|
||||
frame.on('navigate', (event) => events.push(event));
|
||||
|
||||
receive({ type: 'navigate', tab: 'assistant' });
|
||||
|
||||
expect(events).toEqual([{ tab: 'assistant' }]);
|
||||
});
|
||||
|
||||
it('only calls the listeners of the event that was received', () => {
|
||||
const frame = createFrame();
|
||||
const calls: string[] = [];
|
||||
frame.on('close', () => calls.push('close'));
|
||||
frame.on('escape', () => calls.push('escape'));
|
||||
frame.on('navigate', () => calls.push('navigate'));
|
||||
|
||||
receive({ type: 'escape' });
|
||||
|
||||
expect(calls).toEqual(['escape']);
|
||||
});
|
||||
|
||||
it('stops calling a listener once it is unsubscribed', () => {
|
||||
const frame = createFrame();
|
||||
const calls: string[] = [];
|
||||
const unsubscribe = frame.on('navigate', () => calls.push('navigate'));
|
||||
|
||||
unsubscribe();
|
||||
receive({ type: 'navigate', tab: 'search' });
|
||||
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { createChannel } from 'bidc';
|
||||
import type {
|
||||
FrameToParentMessage,
|
||||
GitBookEmbeddableConfiguration,
|
||||
GitBookFrameEvents,
|
||||
ParentToFrameMessage,
|
||||
} from './protocol';
|
||||
|
||||
@@ -42,8 +43,11 @@ export type GitBookFrameClient = {
|
||||
*
|
||||
* - `close`: the built-in close button was clicked.
|
||||
* - `escape`: Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it.
|
||||
* - `navigate`: the reader opened a page in the docs tab, or switched to another tab.
|
||||
*/
|
||||
on: (event: string, listener: (...args: any[]) => void) => () => void;
|
||||
on<E extends keyof GitBookFrameEvents>(event: E, listener: GitBookFrameEvents[E]): () => void;
|
||||
// Kept so callers typed against the earlier `string` signature still compile.
|
||||
on(event: string, listener: (...args: any[]) => void): () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -67,9 +71,16 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
|
||||
channel.receive((message: FrameToParentMessage) => {
|
||||
console.log('[gitbook:embed] received message', message);
|
||||
if (message.type === 'close' || message.type === 'escape') {
|
||||
const listeners = events.get(message.type) || [];
|
||||
listeners.forEach((listener) => listener());
|
||||
switch (message.type) {
|
||||
case 'close':
|
||||
case 'escape':
|
||||
emit(message.type);
|
||||
break;
|
||||
case 'navigate': {
|
||||
const { type: _type, ...event } = message;
|
||||
emit('navigate', event);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -79,6 +90,12 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
};
|
||||
|
||||
const events = new Map<string, ((...args: any[]) => void)[]>();
|
||||
const emit = <E extends keyof GitBookFrameEvents>(
|
||||
event: E,
|
||||
...args: Parameters<GitBookFrameEvents[E]>
|
||||
) => {
|
||||
(events.get(event) || []).forEach((listener) => listener(...args));
|
||||
};
|
||||
|
||||
const configuration: GitBookEmbeddableConfiguration = {
|
||||
tabs: ['assistant', 'search', 'docs'],
|
||||
@@ -102,7 +119,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
sendToFrame({ type: 'configure', settings: configuration });
|
||||
},
|
||||
clearChat: () => sendToFrame({ type: 'clearChat' }),
|
||||
on: (event, listener) => {
|
||||
on: (event: string, listener: (...args: any[]) => void) => {
|
||||
const listeners = events.get(event) || [];
|
||||
listeners.push(listener);
|
||||
events.set(event, listeners);
|
||||
|
||||
@@ -134,6 +134,38 @@ export type ParentToFrameMessage =
|
||||
type: 'navigateToAssistant';
|
||||
};
|
||||
|
||||
/**
|
||||
* Where the reader is in the embed, sent with the `navigate` event.
|
||||
*/
|
||||
export type GitBookNavigateEvent =
|
||||
| {
|
||||
tab: 'docs';
|
||||
/**
|
||||
* Path of the page from the root of the site (e.g. `/getting-started/quickstart`),
|
||||
* in the form `navigateToPage` accepts.
|
||||
*/
|
||||
path: string;
|
||||
/** Published URL of the page, without query parameters. */
|
||||
url: string;
|
||||
/** Title of the page. */
|
||||
title: string;
|
||||
}
|
||||
| {
|
||||
tab: 'assistant' | 'search';
|
||||
};
|
||||
|
||||
/**
|
||||
* Events emitted by the frame, and the arguments their listeners receive.
|
||||
*/
|
||||
export type GitBookFrameEvents = {
|
||||
/** The built-in close button was clicked. */
|
||||
close: () => void;
|
||||
/** Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it. */
|
||||
escape: () => void;
|
||||
/** The reader opened a page in the docs tab, or switched to another tab. */
|
||||
navigate: (event: GitBookNavigateEvent) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Messages sent from the frame to the parent.
|
||||
*/
|
||||
@@ -144,4 +176,7 @@ export type FrameToParentMessage =
|
||||
| {
|
||||
/** Escape was pressed inside the frame and nothing in the frame handled it. */
|
||||
type: 'escape';
|
||||
};
|
||||
}
|
||||
| ({
|
||||
type: 'navigate';
|
||||
} & GitBookNavigateEvent);
|
||||
|
||||
@@ -6,11 +6,21 @@ import type {
|
||||
GetFrameURLOptions,
|
||||
GitBookEmbeddableConfiguration,
|
||||
GitBookFrameClient,
|
||||
GitBookNavigateEvent,
|
||||
} from '../client';
|
||||
import { useGitBook } from './GitBookProvider';
|
||||
|
||||
export type GitBookFrameProps = {
|
||||
className?: string;
|
||||
|
||||
/** Called when the reader opens a page in the docs tab, or switches to another tab. */
|
||||
onNavigate?: (event: GitBookNavigateEvent) => void;
|
||||
|
||||
/** Called when the built-in close button is clicked. */
|
||||
onClose?: () => void;
|
||||
|
||||
/** Called when Escape is pressed inside the frame and nothing in it (a menu, a dialog) used it. */
|
||||
onEscape?: () => void;
|
||||
} & GetFrameURLOptions &
|
||||
Partial<GitBookEmbeddableConfiguration>;
|
||||
|
||||
@@ -32,6 +42,9 @@ export function GitBookFrame(props: GitBookFrameProps) {
|
||||
trademark = true,
|
||||
closeButton = false,
|
||||
assistantName,
|
||||
onNavigate,
|
||||
onClose,
|
||||
onEscape,
|
||||
} = props;
|
||||
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
@@ -49,6 +62,24 @@ export function GitBookFrame(props: GitBookFrameProps) {
|
||||
}
|
||||
}, [gitbook]);
|
||||
|
||||
// Read through a ref so inline callbacks don't resubscribe on every render.
|
||||
const handlers = useRef({ onNavigate, onClose, onEscape });
|
||||
useEffect(() => {
|
||||
handlers.current = { onNavigate, onClose, onEscape };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!gitbookFrame) {
|
||||
return;
|
||||
}
|
||||
const unsubscribes = [
|
||||
gitbookFrame.on('navigate', (event) => handlers.current.onNavigate?.(event)),
|
||||
gitbookFrame.on('close', () => handlers.current.onClose?.()),
|
||||
gitbookFrame.on('escape', () => handlers.current.onEscape?.()),
|
||||
];
|
||||
return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||
}, [gitbookFrame]);
|
||||
|
||||
useEffect(() => {
|
||||
gitbookFrame?.configure({
|
||||
tabs,
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
type GitBookClient,
|
||||
type GitBookEmbeddableConfiguration,
|
||||
type GitBookFrameClient,
|
||||
type GitBookFrameEvents,
|
||||
createGitBook,
|
||||
} from '../client';
|
||||
import { createFrameEventRelay } from './events';
|
||||
|
||||
export type GitBook = () => void;
|
||||
|
||||
@@ -35,7 +37,9 @@ type StandaloneCalls =
|
||||
// Navigate to a page
|
||||
| ['navigateToPage', string]
|
||||
// Navigate to the assistant
|
||||
| ['navigateToAssistant'];
|
||||
| ['navigateToAssistant']
|
||||
// Listen to an event from the embed, returns a function to stop listening
|
||||
| { [E in keyof GitBookFrameEvents]: ['on', E, GitBookFrameEvents[E]] }[keyof GitBookFrameEvents];
|
||||
|
||||
type StandaloneConfiguration = {
|
||||
/** Configure the button to open the embed */
|
||||
@@ -47,7 +51,7 @@ type StandaloneConfiguration = {
|
||||
};
|
||||
};
|
||||
|
||||
export type GitBookStandalone = ((...args: StandaloneCalls) => void) & {
|
||||
export type GitBookStandalone = ((...args: StandaloneCalls) => void | (() => void)) & {
|
||||
q?: StandaloneCalls[];
|
||||
};
|
||||
|
||||
@@ -56,6 +60,7 @@ let _client: GitBookClient | undefined;
|
||||
let _frame: GitBookFrameClient | undefined;
|
||||
let frameOptions: GetFrameURLOptions | undefined;
|
||||
let frameConfigured = false;
|
||||
const frameEvents = createFrameEventRelay();
|
||||
let frameConfiguration: GitBookEmbeddableConfiguration & StandaloneConfiguration = {
|
||||
button: {
|
||||
label: 'Ask',
|
||||
@@ -152,6 +157,7 @@ function getIframe() {
|
||||
widgetWindow.classList.add('hidden');
|
||||
widgetButton.classList.remove('open');
|
||||
});
|
||||
frameEvents.attach(_frame);
|
||||
// A new frame starts from the site's own defaults, so replay whatever the host configured.
|
||||
if (frameConfigured) {
|
||||
_frame.configure(frameConfiguration);
|
||||
@@ -160,7 +166,7 @@ function getIframe() {
|
||||
return { iframe: widgetIframe, frame: _frame };
|
||||
}
|
||||
|
||||
const GitBook = (...args: StandaloneCalls) => {
|
||||
const GitBook = (...args: StandaloneCalls): void | (() => void) => {
|
||||
switch (args[0]) {
|
||||
case 'init': {
|
||||
// `~gitbook/embed/script.js` already calls `init`, so an integrator following the docs
|
||||
@@ -185,6 +191,7 @@ const GitBook = (...args: StandaloneCalls) => {
|
||||
widgetIframe.remove();
|
||||
widgetIframe = undefined;
|
||||
_frame = undefined;
|
||||
frameEvents.detach();
|
||||
if (wasOpen) {
|
||||
getIframe();
|
||||
}
|
||||
@@ -194,6 +201,7 @@ const GitBook = (...args: StandaloneCalls) => {
|
||||
case 'unload':
|
||||
_client = undefined;
|
||||
_frame = undefined;
|
||||
frameEvents.detach();
|
||||
widgetIframe?.remove();
|
||||
widgetIframe = undefined;
|
||||
frameOptions = undefined;
|
||||
@@ -272,6 +280,9 @@ const GitBook = (...args: StandaloneCalls) => {
|
||||
case 'navigateToAssistant':
|
||||
getIframe().frame.navigateToAssistant();
|
||||
break;
|
||||
case 'on':
|
||||
// Not `getIframe()`: listening shouldn't load the frame before the reader opens it.
|
||||
return frameEvents.on(args[1], args[2]);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
GitBookAPI,
|
||||
SiteSocialAccountPlatform,
|
||||
} from '@gitbook/api';
|
||||
import type { GitBookStandalone } from '@gitbook/embed';
|
||||
import type { GitBookNavigateEvent, GitBookStandalone } from '@gitbook/embed';
|
||||
|
||||
import { getContentTestURL, getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
|
||||
import {
|
||||
@@ -3560,6 +3560,41 @@ const testCases: TestsCase[] = [
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'API - navigate event',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await page.evaluate(() => {
|
||||
const GitBook = window.GitBook as unknown as GitBookStandalone;
|
||||
const host = window as unknown as {
|
||||
navigateEvents: GitBookNavigateEvent[];
|
||||
};
|
||||
host.navigateEvents = [];
|
||||
GitBook('on', 'navigate', (event) => host.navigateEvents.push(event));
|
||||
GitBook('navigateToPage', '/text-page');
|
||||
});
|
||||
const navigateEvents = () =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
(window as unknown as { navigateEvents: GitBookNavigateEvent[] })
|
||||
.navigateEvents
|
||||
);
|
||||
|
||||
await expect.poll(navigateEvents, { timeout: 20000 }).toContainEqual({
|
||||
tab: 'docs',
|
||||
path: '/text-page',
|
||||
url: expect.stringMatching(/^[^?#]+\/text-page$/),
|
||||
title: 'Text page',
|
||||
});
|
||||
|
||||
const iframe = page.frameLocator('#gitbook-widget-iframe');
|
||||
await iframe.getByTestId('embed-tab-assistant').click();
|
||||
await expect
|
||||
.poll(navigateEvents, { timeout: 20000 })
|
||||
.toContainEqual({ tab: 'assistant' });
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'API - postUserMessage',
|
||||
url: '',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EmbeddableAIChat } from './EmbeddableAIChat';
|
||||
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
|
||||
|
||||
type EmbeddableAssistantPageProps = {
|
||||
baseURL: string;
|
||||
@@ -9,5 +10,10 @@ type EmbeddableAssistantPageProps = {
|
||||
* Reusable page component for the embed assistant page.
|
||||
*/
|
||||
export async function EmbeddableAssistantPage(props: EmbeddableAssistantPageProps) {
|
||||
return <EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />;
|
||||
return (
|
||||
<>
|
||||
<EmbeddableNavigateEvent tab="assistant" />
|
||||
<EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ import {
|
||||
EmbeddableIframeButtons,
|
||||
EmbeddableIframeCloseButton,
|
||||
EmbeddableIframeTabs,
|
||||
EmbeddableNavigateEvent,
|
||||
} from './EmbeddableIframeAPI';
|
||||
import { getEmbeddableDocsNavigateEvent, getEmbeddablePagePublishedPath } from './navigate-event';
|
||||
import { type PagePathParams, getSitePageData } from '@/components/SitePage';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
@@ -48,9 +50,11 @@ export async function EmbeddableDocsPage(
|
||||
});
|
||||
|
||||
const variants = categorizeVariants(context);
|
||||
const pageInput = { linker: context.linker, pages: context.revision.pages, page };
|
||||
|
||||
return (
|
||||
<EmbeddableFrame className="site-background">
|
||||
<EmbeddableNavigateEvent {...getEmbeddableDocsNavigateEvent(pageInput)} />
|
||||
<EmbeddableFrameSidebar>
|
||||
<EmbeddableIframeTabs
|
||||
active="docs"
|
||||
@@ -72,12 +76,7 @@ export async function EmbeddableDocsPage(
|
||||
</EmbeddableFrameHeaderMain>
|
||||
<EmbeddableFrameButtons>
|
||||
<EmbeddableDocsPageControlButtons
|
||||
href={context.linker
|
||||
.toPathForPage({
|
||||
pages: context.revision.pages,
|
||||
page,
|
||||
})
|
||||
.replace(/~gitbook\/embed\/page\/?/, '')}
|
||||
href={getEmbeddablePagePublishedPath(pageInput)}
|
||||
/>
|
||||
</EmbeddableFrameButtons>
|
||||
</EmbeddableFrameHeader>
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { GitBookIntegrationTool } from '@gitbook/browser-types';
|
||||
import type {
|
||||
FrameToParentMessage,
|
||||
GitBookEmbeddableConfiguration,
|
||||
GitBookNavigateEvent,
|
||||
ParentToFrameMessage,
|
||||
} from '@gitbook/embed';
|
||||
|
||||
@@ -181,6 +182,22 @@ export function EmbeddableIframeAPI(props: { baseURL: string }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the parent window where the reader is, each time it changes.
|
||||
*/
|
||||
export function EmbeddableNavigateEvent(props: GitBookNavigateEvent) {
|
||||
// Compared by value: a server re-render passes a new object for the same page.
|
||||
const event = JSON.stringify(props);
|
||||
useEffect(() => {
|
||||
getChannel()?.send({
|
||||
type: 'navigate',
|
||||
...(JSON.parse(event) as GitBookNavigateEvent),
|
||||
} satisfies FrameToParentMessage);
|
||||
}, [event]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get the configuration from the parent window.
|
||||
*/
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
|
||||
import { EmbeddableSearch } from './EmbeddableSearch';
|
||||
import { getSearchBaseProps } from '@/components/Search/search-props';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
@@ -13,10 +14,13 @@ export function EmbeddableSearchPage(props: EmbeddableSearchPageProps) {
|
||||
const { context } = props;
|
||||
|
||||
return (
|
||||
<EmbeddableSearch
|
||||
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
|
||||
siteTitle={context.site.title}
|
||||
searchProps={getSearchBaseProps(context)}
|
||||
/>
|
||||
<>
|
||||
<EmbeddableNavigateEvent tab="search" />
|
||||
<EmbeddableSearch
|
||||
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
|
||||
siteTitle={context.site.title}
|
||||
searchProps={getSearchBaseProps(context)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import { getEmbeddableDocsNavigateEvent } from './navigate-event';
|
||||
import { getEmbeddableLinker } from '@/lib/embeddable-linker';
|
||||
import { type GitBookLinker, createLinker } from '@/lib/links';
|
||||
|
||||
const pages = [
|
||||
{ id: 'home', type: 'document', title: 'Home', path: 'home', pages: [] },
|
||||
{ id: 'slack', type: 'document', title: 'Slack', path: 'integrations/slack', pages: [] },
|
||||
] as unknown as RevisionPageDocument[];
|
||||
const [home, slack] = pages as [RevisionPageDocument, RevisionPageDocument];
|
||||
|
||||
function embedLinker(servedOn: Parameters<typeof createLinker>[0]): GitBookLinker {
|
||||
return getEmbeddableLinker(createLinker(servedOn));
|
||||
}
|
||||
|
||||
describe('getEmbeddableDocsNavigateEvent', () => {
|
||||
it('describes the page by its path from the site root and its published URL', () => {
|
||||
const linker = embedLinker({
|
||||
host: 'example.com',
|
||||
siteBasePath: '/docs/',
|
||||
spaceBasePath: '/docs/help-center/',
|
||||
});
|
||||
|
||||
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: slack })).toEqual({
|
||||
tab: 'docs',
|
||||
path: '/help-center/integrations/slack',
|
||||
url: 'https://example.com/docs/help-center/integrations/slack',
|
||||
title: 'Slack',
|
||||
});
|
||||
});
|
||||
|
||||
it('describes the first page of a space by the space root', () => {
|
||||
const linker = embedLinker({
|
||||
host: 'example.com',
|
||||
siteBasePath: '/docs/',
|
||||
spaceBasePath: '/docs/help-center/',
|
||||
});
|
||||
|
||||
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
|
||||
path: '/help-center',
|
||||
url: 'https://example.com/docs/help-center',
|
||||
});
|
||||
});
|
||||
|
||||
it('describes the home page of a single-space site as the root', () => {
|
||||
const linker = embedLinker({ host: 'example.com', siteBasePath: '/', spaceBasePath: '/' });
|
||||
|
||||
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
|
||||
path: '/',
|
||||
url: 'https://example.com/',
|
||||
});
|
||||
});
|
||||
|
||||
it('describes the home page of a site on a subdirectory as the root', () => {
|
||||
const linker = embedLinker({
|
||||
host: 'example.com',
|
||||
siteBasePath: '/docs/',
|
||||
spaceBasePath: '/docs/',
|
||||
});
|
||||
|
||||
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
|
||||
path: '/',
|
||||
url: 'https://example.com/docs',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves out query parameters and anchors', () => {
|
||||
const base = embedLinker({ host: 'example.com', siteBasePath: '/', spaceBasePath: '/' });
|
||||
const linker: GitBookLinker = {
|
||||
...base,
|
||||
toPathForPage: () => '/~gitbook/embed/page/integrations/slack?jwt_token=secret#setup',
|
||||
};
|
||||
|
||||
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: slack })).toMatchObject({
|
||||
path: '/integrations/slack',
|
||||
url: 'https://example.com/integrations/slack',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
||||
import type { GitBookNavigateEvent } from '@gitbook/embed';
|
||||
|
||||
import type { GitBookLinker } from '@/lib/links';
|
||||
import { withLeadingSlash } from '@/lib/paths';
|
||||
|
||||
type PageInput = {
|
||||
/** The embed's linker. */
|
||||
linker: GitBookLinker;
|
||||
pages: RevisionPage[];
|
||||
page: RevisionPageDocument | RevisionPageGroup;
|
||||
};
|
||||
|
||||
/**
|
||||
* Path of a page on the published site, outside the embed.
|
||||
*/
|
||||
export function getEmbeddablePagePublishedPath({ linker, pages, page }: PageInput): string {
|
||||
return linker.toPathForPage({ pages, page }).replace(/~gitbook\/embed\/page\/?/, '');
|
||||
}
|
||||
|
||||
function trimTrailingSlash(pathname: string): string {
|
||||
return pathname.replace(/(.)\/$/, '$1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Describe a docs page for the `navigate` event sent to the host of the embed.
|
||||
*/
|
||||
export function getEmbeddableDocsNavigateEvent(
|
||||
input: PageInput
|
||||
): Extract<GitBookNavigateEvent, { tab: 'docs' }> {
|
||||
const { linker, page } = input;
|
||||
// Query parameters can carry the visitor's token; the host only gets the page.
|
||||
const { pathname } = new URL(getEmbeddablePagePublishedPath(input), 'https://gitbook.local');
|
||||
// Relative before trimming: the site base path ends with a slash, so `/docs` wouldn't match it.
|
||||
const path = trimTrailingSlash(withLeadingSlash(linker.toRelativePathInSite(pathname)));
|
||||
const url = linker.toAbsoluteURL(trimTrailingSlash(pathname));
|
||||
|
||||
return {
|
||||
tab: 'docs',
|
||||
path,
|
||||
// Joining paths drops the slash of a root URL (`https://example.com`).
|
||||
url: URL.canParse(url) ? new URL(url).href : url,
|
||||
title: page.title,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user