mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-27 02:32:16 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 36cde8779f | |||
| b1cfef2862 |
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"@gitbook/embed": minor
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Emit a `navigate` event from the Docs Embed when the reader opens a page or switches tab, with the page's path, URL and title. Listen to it, and to `close` and `escape`, with `GitBook('on', ...)` in the standalone script or the `onNavigate`, `onClose` and `onEscape` props of `<GitBookFrame>`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gitbook/react-openapi": patch
|
||||
---
|
||||
|
||||
Keep the selected server separate for each OpenAPI spec, so a server from a previously visited API page no longer shows or gets copied on another spec's endpoints.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Restrict updates pagination to single top-level Updates blocks.
|
||||
@@ -1,2 +1,2 @@
|
||||
dist/
|
||||
standalone/
|
||||
/standalone/
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type { GitBookFrameClient, GitBookFrameEvents } from '../client';
|
||||
import { createFrameEventRelay } from './events';
|
||||
|
||||
type Listeners = { [E in keyof GitBookFrameEvents]?: GitBookFrameEvents[E][] };
|
||||
|
||||
/** A frame client that only records listeners, so a test can emit events from the frame. */
|
||||
function createFakeFrame() {
|
||||
const listeners: Listeners = {};
|
||||
const frame = {
|
||||
on: (event: keyof GitBookFrameEvents, listener: (...args: any[]) => void) => {
|
||||
(listeners[event] ??= []).push(listener);
|
||||
return () => {
|
||||
listeners[event] = listeners[event]?.filter((l) => l !== listener) as any;
|
||||
};
|
||||
},
|
||||
} as unknown as GitBookFrameClient;
|
||||
const emit = (event: keyof GitBookFrameEvents, ...args: any[]) =>
|
||||
listeners[event]?.forEach((listener) => (listener as any)(...args));
|
||||
return { frame, emit };
|
||||
}
|
||||
|
||||
describe('createFrameEventRelay', () => {
|
||||
it('forwards events from the attached frame to listeners registered before it existed', () => {
|
||||
const relay = createFrameEventRelay();
|
||||
const events: unknown[] = [];
|
||||
relay.on('navigate', (event) => events.push(event));
|
||||
|
||||
const { frame, emit } = createFakeFrame();
|
||||
relay.attach(frame);
|
||||
emit('navigate', { tab: 'search' });
|
||||
|
||||
expect(events).toEqual([{ tab: 'search' }]);
|
||||
});
|
||||
|
||||
it('keeps listeners when the frame is replaced, and ignores the old frame', () => {
|
||||
const relay = createFrameEventRelay();
|
||||
const events: unknown[] = [];
|
||||
relay.on('navigate', (event) => events.push(event));
|
||||
|
||||
const first = createFakeFrame();
|
||||
relay.attach(first.frame);
|
||||
const second = createFakeFrame();
|
||||
relay.attach(second.frame);
|
||||
|
||||
first.emit('navigate', { tab: 'search' });
|
||||
second.emit('navigate', { tab: 'assistant' });
|
||||
|
||||
expect(events).toEqual([{ tab: 'assistant' }]);
|
||||
});
|
||||
|
||||
it('stops calling a listener once it is unsubscribed', () => {
|
||||
const relay = createFrameEventRelay();
|
||||
const calls: string[] = [];
|
||||
const unsubscribe = relay.on('close', () => calls.push('close'));
|
||||
|
||||
const { frame, emit } = createFakeFrame();
|
||||
relay.attach(frame);
|
||||
unsubscribe();
|
||||
emit('close');
|
||||
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it('stops forwarding once detached', () => {
|
||||
const relay = createFrameEventRelay();
|
||||
const calls: string[] = [];
|
||||
relay.on('escape', () => calls.push('escape'));
|
||||
|
||||
const { frame, emit } = createFakeFrame();
|
||||
relay.attach(frame);
|
||||
relay.detach();
|
||||
emit('escape');
|
||||
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { GitBookFrameClient, GitBookFrameEvents } from '../client';
|
||||
|
||||
const FRAME_EVENTS: (keyof GitBookFrameEvents)[] = ['close', 'escape', 'navigate'];
|
||||
|
||||
/**
|
||||
* Hold the host's listeners outside any one frame: the widget rebuilds its iframe on a new `init`
|
||||
* and only creates it once opened, but `GitBook('on', …)` can be called at any time.
|
||||
*/
|
||||
export function createFrameEventRelay() {
|
||||
const listeners = new Map<keyof GitBookFrameEvents, Set<(...args: any[]) => void>>();
|
||||
let detachFrame: (() => void) | undefined;
|
||||
|
||||
const detach = () => {
|
||||
detachFrame?.();
|
||||
detachFrame = undefined;
|
||||
};
|
||||
|
||||
return {
|
||||
on<E extends keyof GitBookFrameEvents>(event: E, listener: GitBookFrameEvents[E]) {
|
||||
const set = listeners.get(event) ?? new Set();
|
||||
set.add(listener);
|
||||
listeners.set(event, set);
|
||||
return () => {
|
||||
set.delete(listener);
|
||||
};
|
||||
},
|
||||
|
||||
attach(frame: GitBookFrameClient) {
|
||||
detach();
|
||||
const unsubscribes = FRAME_EVENTS.map((event) =>
|
||||
frame.on(event, (...args: any[]) => {
|
||||
listeners.get(event)?.forEach((listener) => listener(...args));
|
||||
})
|
||||
);
|
||||
detachFrame = () => unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||
},
|
||||
|
||||
detach,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import './style.css';
|
||||
|
||||
import {
|
||||
type CreateGitBookOptions,
|
||||
type GetFrameURLOptions,
|
||||
type GitBookClient,
|
||||
type GitBookEmbeddableConfiguration,
|
||||
type GitBookFrameClient,
|
||||
type GitBookFrameEvents,
|
||||
createGitBook,
|
||||
} from '../client';
|
||||
import { createFrameEventRelay } from './events';
|
||||
|
||||
export type GitBook = () => void;
|
||||
|
||||
@@ -35,7 +36,11 @@ 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 +52,7 @@ type StandaloneConfiguration = {
|
||||
};
|
||||
};
|
||||
|
||||
export type GitBookStandalone = ((...args: StandaloneCalls) => void) & {
|
||||
export type GitBookStandalone = ((...args: StandaloneCalls) => void | (() => void)) & {
|
||||
q?: StandaloneCalls[];
|
||||
};
|
||||
|
||||
@@ -56,6 +61,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 +158,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 +167,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 +192,7 @@ const GitBook = (...args: StandaloneCalls) => {
|
||||
widgetIframe.remove();
|
||||
widgetIframe = undefined;
|
||||
_frame = undefined;
|
||||
frameEvents.detach();
|
||||
if (wasOpen) {
|
||||
getIframe();
|
||||
}
|
||||
@@ -194,6 +202,7 @@ const GitBook = (...args: StandaloneCalls) => {
|
||||
case 'unload':
|
||||
_client = undefined;
|
||||
_frame = undefined;
|
||||
frameEvents.detach();
|
||||
widgetIframe?.remove();
|
||||
widgetIframe = undefined;
|
||||
frameOptions = undefined;
|
||||
@@ -272,6 +281,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} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,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';
|
||||
|
||||
@@ -81,9 +83,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"
|
||||
@@ -105,12 +109,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,
|
||||
};
|
||||
}
|
||||
@@ -39,10 +39,11 @@ import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
|
||||
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import {
|
||||
countDocumentUpdates,
|
||||
generateUpdatesFilterCSS,
|
||||
getUpdatesPageRange,
|
||||
getUpdatesPaginationEligibility,
|
||||
paginateUpdatesDocument,
|
||||
UPDATES_PAGINATION_THRESHOLD,
|
||||
getDocumentFilterableTags,
|
||||
updatesFilterStyleHref,
|
||||
} from '@/lib/updates';
|
||||
@@ -248,12 +249,9 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
|
||||
if (props.updatesPage) {
|
||||
const document = await getPageDocument(context, page);
|
||||
if (document) {
|
||||
const eligibility = getUpdatesPaginationEligibility(document);
|
||||
if (eligibility.status === 'eligible') {
|
||||
const { page: pageNumber } = getUpdatesPageRange(
|
||||
props.updatesPage,
|
||||
eligibility.updates.length
|
||||
);
|
||||
const count = countDocumentUpdates(document);
|
||||
if (count > UPDATES_PAGINATION_THRESHOLD) {
|
||||
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
|
||||
title = `${title} (Page ${pageNumber})`;
|
||||
if (!pageMetaLinks?.canonical) {
|
||||
const url = new URL(canonical);
|
||||
@@ -380,29 +378,17 @@ export async function getSitePageData(props: SitePageProps) {
|
||||
let filterableTags: RevisionTag[] = [];
|
||||
let document = fullDocument;
|
||||
let pagination = null;
|
||||
let eligibility = null;
|
||||
if (fullDocument) {
|
||||
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
|
||||
({ document, pagination, eligibility } = paginateUpdatesDocument(
|
||||
fullDocument,
|
||||
context.revision,
|
||||
{
|
||||
page: props.updatesPage ?? 1,
|
||||
}
|
||||
));
|
||||
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
|
||||
page: props.updatesPage ?? 1,
|
||||
}));
|
||||
}
|
||||
|
||||
if (eligibility?.status === 'skipped' || pagination || props.updatesPage) {
|
||||
if (pagination || props.updatesPage) {
|
||||
const logger = getLogger().subLogger('updatesPagination', {
|
||||
labels: { siteId: context.site.id, pageId: page.id },
|
||||
});
|
||||
if (eligibility?.status === 'skipped') {
|
||||
logger.info('Skipped updates pagination', {
|
||||
reason: eligibility.reason,
|
||||
totalUpdates: eligibility.totalUpdates,
|
||||
updatesBlocks: eligibility.updatesBlocks,
|
||||
});
|
||||
}
|
||||
if (props.updatesPage && (!pagination || pagination.isClamped)) {
|
||||
const targetPage = pagination?.page ?? 1;
|
||||
logger.info('Redirected out-of-range updates page', {
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import {
|
||||
type DocumentBlockHeading,
|
||||
type DocumentBlockParagraph,
|
||||
type DocumentBlockUpdate,
|
||||
type DocumentBlockUpdates,
|
||||
DocumentTextColor,
|
||||
type JSONDocument,
|
||||
type Revision,
|
||||
@@ -14,9 +10,8 @@ import {
|
||||
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
|
||||
import {
|
||||
UPDATES_TAG_FILTER_CAP,
|
||||
type UpdatesPaginationEligibility,
|
||||
countDocumentUpdates,
|
||||
findUpdateAnchorPage,
|
||||
getUpdatesPaginationEligibility,
|
||||
paginateUpdatesDocument,
|
||||
parseUpdatesPageParam,
|
||||
getDocumentFilterableTags,
|
||||
@@ -102,119 +97,63 @@ describe('normalizeUpdatesFilterTags', () => {
|
||||
});
|
||||
|
||||
describe('updates pagination', () => {
|
||||
it('paginates a single top-level updates block and keeps the surrounding blocks', () => {
|
||||
const document = createDocument([
|
||||
createHeading('intro'),
|
||||
createParagraph(),
|
||||
createUpdatesBlock(createUpdateEntries(260)),
|
||||
createParagraph(),
|
||||
]);
|
||||
it('keeps a 50-entry document intact and paginates 51 entries across two blocks', () => {
|
||||
const short = createUpdatesDocument(Array.from({ length: 50 }, () => []));
|
||||
expect(paginateUpdatesDocument(short, undefined, { page: 2 })).toEqual({
|
||||
document: short,
|
||||
pagination: null,
|
||||
});
|
||||
expect(paginateUpdatesDocument(short, undefined, { page: 2 }).document).toBe(short);
|
||||
|
||||
const long = createUpdatesDocument(
|
||||
Array.from({ length: 51 }, () => []),
|
||||
25
|
||||
);
|
||||
expect(countDocumentUpdates(long)).toBe(51);
|
||||
for (const [page, start, end, blockTypes] of [
|
||||
[1, 1, 20, ['updates', 'paragraph']],
|
||||
[2, 21, 40, ['updates', 'paragraph', 'updates']],
|
||||
[3, 41, 51, ['paragraph', 'updates']],
|
||||
] as const) {
|
||||
const result = paginateUpdatesDocument(long, undefined, { page });
|
||||
expect(result.pagination).toEqual({
|
||||
page,
|
||||
totalPages: 3,
|
||||
totalItems: 51,
|
||||
pageSize: 20,
|
||||
start,
|
||||
end,
|
||||
isClamped: false,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(
|
||||
Array.from({ length: end - start + 1 }, (_, i) => `update-${start + i}`)
|
||||
);
|
||||
expect(result.document.nodes.map((block) => block.type)).toEqual([...blockTypes]);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the first and seventh slices of a 260-entry changelog to 20 entries each', () => {
|
||||
const document = createUpdatesDocument(
|
||||
Array.from({ length: 260 }, () => []),
|
||||
135
|
||||
);
|
||||
for (const [page, start] of [
|
||||
[1, 1],
|
||||
[7, 121],
|
||||
] as const) {
|
||||
const result = paginateUpdatesDocument(document, undefined, { page });
|
||||
expect(result.pagination).toEqual({
|
||||
expect(result.pagination).toMatchObject({
|
||||
page,
|
||||
totalPages: 13,
|
||||
totalItems: 260,
|
||||
pageSize: 20,
|
||||
start,
|
||||
end: start + 19,
|
||||
isClamped: false,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(
|
||||
Array.from({ length: 20 }, (_, i) => `update-${start + i}`)
|
||||
);
|
||||
expect(result.document.nodes.map((block) => block.type)).toEqual([
|
||||
'heading-1',
|
||||
'paragraph',
|
||||
'updates',
|
||||
'paragraph',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps 50 entries intact and paginates 51', () => {
|
||||
const short = createDocument([createUpdatesBlock(createUpdateEntries(50))]);
|
||||
expect(getUpdatesPaginationEligibility(short)).toEqual({ status: 'below-threshold' });
|
||||
const shortResult = paginateUpdatesDocument(short, undefined, { page: 2 });
|
||||
expect(shortResult.pagination).toBeNull();
|
||||
expect(shortResult.document).toBe(short);
|
||||
|
||||
const long = createDocument([createUpdatesBlock(createUpdateEntries(51))]);
|
||||
const eligibility = getUpdatesPaginationEligibility(long);
|
||||
expect(eligibility.status).toBe('eligible');
|
||||
if (eligibility.status === 'eligible') {
|
||||
expect(eligibility.updates).toHaveLength(51);
|
||||
}
|
||||
const result = paginateUpdatesDocument(long, undefined, { page: 3 });
|
||||
expect(result.pagination).toMatchObject({ page: 3, totalPages: 3, start: 41, end: 51 });
|
||||
expect(getUpdateIds(result.document)).toEqual(
|
||||
Array.from({ length: 11 }, (_, i) => `update-${41 + i}`)
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[25, 26],
|
||||
[60, 10],
|
||||
])('does not paginate two top-level updates blocks of %i and %i entries', (first, second) => {
|
||||
const entries = createUpdateEntries(first + second);
|
||||
const document = createDocument([
|
||||
createUpdatesBlock(entries.slice(0, first)),
|
||||
createParagraph(),
|
||||
createUpdatesBlock(entries.slice(first)),
|
||||
]);
|
||||
expectNotPaginated(document, {
|
||||
status: 'skipped',
|
||||
reason: 'multiple-updates-blocks',
|
||||
totalUpdates: first + second,
|
||||
updatesBlocks: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not paginate when another updates block is nested inside a container', () => {
|
||||
const entries = createUpdateEntries(62);
|
||||
const document = createDocument([
|
||||
createUpdatesBlock(entries.slice(0, 60)),
|
||||
wrapInIf(createUpdatesBlock(entries.slice(60))),
|
||||
]);
|
||||
expectNotPaginated(document, {
|
||||
status: 'skipped',
|
||||
reason: 'nested-updates-block',
|
||||
totalUpdates: 62,
|
||||
updatesBlocks: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not paginate an updates block that is only nested', () => {
|
||||
const document = createDocument([wrapInIf(createUpdatesBlock(createUpdateEntries(60)))]);
|
||||
expectNotPaginated(document, { status: 'below-threshold' });
|
||||
});
|
||||
|
||||
it('does not paginate an updates block with non-update entries', () => {
|
||||
const entries = createUpdateEntries(60);
|
||||
const document = createDocument([
|
||||
createUpdatesBlock([
|
||||
...entries.slice(0, 30),
|
||||
{
|
||||
object: 'block',
|
||||
type: 'if',
|
||||
data: { expression: 'visitor.claims.beta' },
|
||||
isVoid: false,
|
||||
nodes: entries.slice(30, 32),
|
||||
},
|
||||
...entries.slice(32),
|
||||
]),
|
||||
]);
|
||||
expectNotPaginated(document, {
|
||||
status: 'skipped',
|
||||
reason: 'non-update-entries',
|
||||
totalUpdates: 59,
|
||||
updatesBlocks: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by any selected tag before calculating page bounds and clamps to the last match', () => {
|
||||
const revision = {
|
||||
tags: [createTag('odd', 'Odd'), createTag('even', 'Even')],
|
||||
@@ -228,7 +167,8 @@ describe('updates pagination', () => {
|
||||
return ['even'];
|
||||
}
|
||||
return [];
|
||||
})
|
||||
}),
|
||||
30
|
||||
);
|
||||
|
||||
const result = paginateUpdatesDocument(document, revision, {
|
||||
@@ -244,6 +184,7 @@ describe('updates pagination', () => {
|
||||
isClamped: true,
|
||||
});
|
||||
expect(getUpdateIds(result.document)).toEqual(['update-61']);
|
||||
expect(countDocumentUpdates(document)).toBe(61);
|
||||
});
|
||||
|
||||
it('finds a nested anchor on the filtered page or clears a filter that excludes it', () => {
|
||||
@@ -254,7 +195,8 @@ describe('updates pagination', () => {
|
||||
return ['fixes'];
|
||||
}
|
||||
return [];
|
||||
})
|
||||
}),
|
||||
26
|
||||
);
|
||||
expect(
|
||||
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
|
||||
@@ -321,68 +263,45 @@ function getUpdateIds(document: JSONDocument) {
|
||||
});
|
||||
}
|
||||
|
||||
function expectNotPaginated(document: JSONDocument, eligibility: UpdatesPaginationEligibility) {
|
||||
expect(getUpdatesPaginationEligibility(document)).toEqual(eligibility);
|
||||
const result = paginateUpdatesDocument(document, undefined, { page: 2 });
|
||||
expect(result).toEqual({
|
||||
document,
|
||||
pagination: null,
|
||||
eligibility,
|
||||
});
|
||||
expect(result.document).toBe(document);
|
||||
expect(findUpdateAnchorPage(document, undefined, { anchor: 'update-1' })).toEqual({
|
||||
found: false,
|
||||
});
|
||||
}
|
||||
|
||||
function createUpdatesDocument(entryTags: string[][]): JSONDocument {
|
||||
return createDocument([createUpdatesBlock(createUpdateEntries(entryTags.length, entryTags))]);
|
||||
}
|
||||
|
||||
function createDocument(nodes: JSONDocument['nodes']): JSONDocument {
|
||||
return { object: 'document', data: { schemaVersion: 2 }, nodes };
|
||||
}
|
||||
|
||||
function createUpdateEntries(count: number, entryTags: string[][] = []): DocumentBlockUpdate[] {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
object: 'block',
|
||||
type: 'update',
|
||||
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
|
||||
const entries = entryTags.map((tags, index) => ({
|
||||
object: 'block' as const,
|
||||
type: 'update' as const,
|
||||
data: {
|
||||
date: '2026-05-01',
|
||||
tags: (entryTags[index] ?? []).map((tag) => ({ kind: 'tag', tag })),
|
||||
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
|
||||
},
|
||||
isVoid: false,
|
||||
nodes: [createHeading(`update-${index + 1}`)],
|
||||
isVoid: false as const,
|
||||
nodes: [
|
||||
{
|
||||
object: 'block' as const,
|
||||
type: 'heading-1' as const,
|
||||
meta: { id: `update-${index + 1}` },
|
||||
data: {},
|
||||
isVoid: false as const,
|
||||
nodes: [],
|
||||
},
|
||||
],
|
||||
}));
|
||||
}
|
||||
const updates = (nodes: typeof entries) => ({
|
||||
object: 'block' as const,
|
||||
type: 'updates' as const,
|
||||
data: { format: 'full' as const },
|
||||
isVoid: false as const,
|
||||
nodes,
|
||||
});
|
||||
const nodes: JSONDocument['nodes'] = [updates(entries)];
|
||||
if (splitAt !== undefined) {
|
||||
nodes.splice(
|
||||
0,
|
||||
1,
|
||||
updates(entries.slice(0, splitAt)),
|
||||
{ object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] },
|
||||
updates(entries.slice(splitAt))
|
||||
);
|
||||
}
|
||||
|
||||
function createUpdatesBlock(nodes: DocumentBlockUpdates['nodes']): DocumentBlockUpdates {
|
||||
return { object: 'block', type: 'updates', data: { format: 'full' }, isVoid: false, nodes };
|
||||
}
|
||||
|
||||
function wrapInIf(block: DocumentBlockUpdates): JSONDocument['nodes'][number] {
|
||||
return {
|
||||
object: 'block',
|
||||
type: 'if',
|
||||
data: { expression: 'visitor.claims.beta' },
|
||||
isVoid: false,
|
||||
nodes: [block],
|
||||
};
|
||||
}
|
||||
|
||||
function createHeading(id: string): DocumentBlockHeading {
|
||||
return {
|
||||
object: 'block',
|
||||
type: 'heading-1',
|
||||
meta: { id },
|
||||
data: {},
|
||||
isVoid: false,
|
||||
nodes: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createParagraph(): DocumentBlockParagraph {
|
||||
return { object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] };
|
||||
return { object: 'document', data: { schemaVersion: 2 }, nodes };
|
||||
}
|
||||
|
||||
function createTag(slug: string, label: string): RevisionTag {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DocumentBlock,
|
||||
DocumentBlockUpdate,
|
||||
DocumentBlockUpdates,
|
||||
DocumentInline,
|
||||
JSONDocument,
|
||||
Revision,
|
||||
@@ -31,21 +30,6 @@ export type UpdatesPageRange = {
|
||||
isClamped: boolean;
|
||||
};
|
||||
|
||||
export type UpdatesPaginationSkipReason =
|
||||
| 'multiple-updates-blocks'
|
||||
| 'nested-updates-block'
|
||||
| 'non-update-entries';
|
||||
|
||||
export type UpdatesPaginationEligibility =
|
||||
| { status: 'eligible'; block: DocumentBlockUpdates; updates: DocumentBlockUpdate[] }
|
||||
| { status: 'below-threshold' }
|
||||
| {
|
||||
status: 'skipped';
|
||||
reason: UpdatesPaginationSkipReason;
|
||||
totalUpdates: number;
|
||||
updatesBlocks: number;
|
||||
};
|
||||
|
||||
/** Attribute on `<html>` with the active filter's tag slugs, space-separated (e.g. `"a b"`). */
|
||||
export const UPDATES_TAG_FILTER_ATTR = 'data-updates-tag-filter';
|
||||
|
||||
@@ -133,100 +117,38 @@ export function getDocumentFilterableTags(
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination only slices a document with a single top-level `updates` block made of more than
|
||||
* `UPDATES_PAGINATION_THRESHOLD` direct `update` entries.
|
||||
*/
|
||||
export function getUpdatesPaginationEligibility(
|
||||
document: JSONDocument
|
||||
): UpdatesPaginationEligibility {
|
||||
let topLevelBlock: DocumentBlockUpdates | undefined;
|
||||
let topLevelBlockCount = 0;
|
||||
let totalUpdates = 0;
|
||||
|
||||
for (const block of document.nodes) {
|
||||
if (block.type !== 'updates') {
|
||||
continue;
|
||||
}
|
||||
topLevelBlock ??= block;
|
||||
topLevelBlockCount++;
|
||||
totalUpdates += block.nodes.length;
|
||||
}
|
||||
|
||||
if (!topLevelBlock || totalUpdates <= UPDATES_PAGINATION_THRESHOLD) {
|
||||
return { status: 'below-threshold' };
|
||||
}
|
||||
|
||||
if (topLevelBlockCount > 1) {
|
||||
return {
|
||||
status: 'skipped',
|
||||
reason: 'multiple-updates-blocks',
|
||||
totalUpdates,
|
||||
updatesBlocks: topLevelBlockCount,
|
||||
};
|
||||
}
|
||||
|
||||
const updates: DocumentBlockUpdate[] = [];
|
||||
for (const entry of topLevelBlock.nodes) {
|
||||
if (entry.type !== 'update') {
|
||||
return {
|
||||
status: 'skipped',
|
||||
reason: 'non-update-entries',
|
||||
totalUpdates,
|
||||
updatesBlocks: 1,
|
||||
};
|
||||
}
|
||||
updates.push(entry);
|
||||
}
|
||||
|
||||
const allUpdatesBlocks = getBlocksByType(document, 'updates');
|
||||
if (allUpdatesBlocks.length > 1) {
|
||||
let allUpdatesCount = 0;
|
||||
for (const updatesBlock of allUpdatesBlocks) {
|
||||
allUpdatesCount += updatesBlock.nodes.length;
|
||||
}
|
||||
return {
|
||||
status: 'skipped',
|
||||
reason: 'nested-updates-block',
|
||||
totalUpdates: allUpdatesCount,
|
||||
updatesBlocks: allUpdatesBlocks.length,
|
||||
};
|
||||
}
|
||||
|
||||
return { status: 'eligible', block: topLevelBlock, updates };
|
||||
export function countDocumentUpdates(document: JSONDocument): number {
|
||||
return getDocumentUpdates(document).length;
|
||||
}
|
||||
|
||||
export function paginateUpdatesDocument(
|
||||
document: JSONDocument,
|
||||
revision: Revision | undefined,
|
||||
{ page, tags }: { page: number; tags?: string[] }
|
||||
): {
|
||||
document: JSONDocument;
|
||||
pagination: UpdatesPageRange | null;
|
||||
eligibility: UpdatesPaginationEligibility;
|
||||
} {
|
||||
const eligibility = getUpdatesPaginationEligibility(document);
|
||||
if (eligibility.status !== 'eligible') {
|
||||
return { document, pagination: null, eligibility };
|
||||
): { document: JSONDocument; pagination: UpdatesPageRange | null } {
|
||||
const updates = getDocumentUpdates(document);
|
||||
if (updates.length <= UPDATES_PAGINATION_THRESHOLD) {
|
||||
return { document, pagination: null };
|
||||
}
|
||||
|
||||
const matching = filterUpdates(eligibility.updates, document, revision, tags);
|
||||
const matching = filterUpdates(updates, document, revision, tags);
|
||||
const pagination = getUpdatesPageRange(page, matching.length);
|
||||
const entries = matching.slice(pagination.start - 1, pagination.end);
|
||||
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
|
||||
const nodes: JSONDocument['nodes'] = [];
|
||||
|
||||
for (const block of document.nodes) {
|
||||
if (block !== eligibility.block) {
|
||||
if (block.type !== 'updates') {
|
||||
nodes.push(block);
|
||||
continue;
|
||||
}
|
||||
|
||||
const entries = block.nodes.filter((entry) => entry.type === 'update' && slice.has(entry));
|
||||
if (entries.length > 0) {
|
||||
nodes.push({ ...block, nodes: entries });
|
||||
}
|
||||
}
|
||||
|
||||
return { document: { ...document, nodes }, pagination, eligibility };
|
||||
return { document: { ...document, nodes }, pagination };
|
||||
}
|
||||
|
||||
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
|
||||
@@ -253,12 +175,7 @@ export function findUpdateAnchorPage(
|
||||
revision: Revision | undefined,
|
||||
{ anchor, tags }: { anchor: string; tags?: string[] }
|
||||
): { found: true; page: number; clearTags: boolean } | { found: false } {
|
||||
const eligibility = getUpdatesPaginationEligibility(document);
|
||||
if (eligibility.status !== 'eligible') {
|
||||
return { found: false };
|
||||
}
|
||||
|
||||
const { updates } = eligibility;
|
||||
const updates = getDocumentUpdates(document);
|
||||
const index = updates.findIndex((update) =>
|
||||
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
|
||||
);
|
||||
@@ -292,6 +209,22 @@ function matchesUpdateAnchor(node: DocumentBlock | DocumentInline, anchor: strin
|
||||
return false;
|
||||
}
|
||||
|
||||
function getDocumentUpdates(document: JSONDocument): DocumentBlockUpdate[] {
|
||||
const updates: DocumentBlockUpdate[] = [];
|
||||
for (const block of document.nodes) {
|
||||
if (block.type !== 'updates') {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const entry of block.nodes) {
|
||||
if (entry.type === 'update') {
|
||||
updates.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
function filterUpdates(
|
||||
updates: DocumentBlockUpdate[],
|
||||
document: JSONDocument,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { renderToReadableStream } from 'react-dom/server';
|
||||
|
||||
import type { OpenAPIClientContext } from './context';
|
||||
import { OpenAPIPathMultipleServers } from './OpenAPIPathMultipleServers';
|
||||
import { translations } from './translations';
|
||||
import type { OpenAPIOperationData } from './types';
|
||||
|
||||
const context: OpenAPIClientContext = {
|
||||
translation: translations.en,
|
||||
icons: {
|
||||
chevronDown: null,
|
||||
chevronRight: null,
|
||||
plus: null,
|
||||
copy: null,
|
||||
check: null,
|
||||
lock: null,
|
||||
mcp: null,
|
||||
hashtag: null,
|
||||
},
|
||||
scalarRuntimeURL: '',
|
||||
$$isClientContext$$: true,
|
||||
};
|
||||
|
||||
async function renderPath(servers: string[]) {
|
||||
const data: OpenAPIOperationData = {
|
||||
path: '/v1/devices',
|
||||
method: 'get',
|
||||
servers: servers.map((url) => ({ url })),
|
||||
operation: { responses: {} },
|
||||
securities: [],
|
||||
};
|
||||
const stream = await renderToReadableStream(
|
||||
<OpenAPIPathMultipleServers data={data} context={context} />
|
||||
);
|
||||
return new Response(stream).text();
|
||||
}
|
||||
|
||||
describe('OpenAPIPathMultipleServers', () => {
|
||||
it('starts on its own default server after another spec that lists the same server', async () => {
|
||||
await renderPath(['https://trader.example.com', 'https://sandbox.example.com']);
|
||||
const html = await renderPath(['https://assets.example.com', 'https://trader.example.com']);
|
||||
|
||||
expect(html).toContain('https://assets.example.com');
|
||||
expect(html).not.toContain('https://trader.example.com');
|
||||
});
|
||||
});
|
||||
@@ -8,8 +8,6 @@ import type { OpenAPIServerWithCustomProperties } from './types';
|
||||
import { getDefaultServerURL, interpolateServerURL } from './util/server';
|
||||
import { createStateKey } from './utils';
|
||||
|
||||
export const serversStateKey = createStateKey('servers');
|
||||
|
||||
/**
|
||||
* Display the path of an operation.
|
||||
*/
|
||||
@@ -20,7 +18,6 @@ export function OpenAPIPathMultipleServers(
|
||||
const { path, servers } = data;
|
||||
|
||||
const defaultServer = getDefaultServerURL(servers);
|
||||
const { key, setKey } = useSelectState(serversStateKey, defaultServer);
|
||||
const formattedPath = formatPath(path);
|
||||
|
||||
const items = servers
|
||||
@@ -36,14 +33,15 @@ export function OpenAPIPathMultipleServers(
|
||||
};
|
||||
});
|
||||
|
||||
// The store outlives client-side navigation, so it can hold a server from another spec.
|
||||
const selectedServer = items.find((item) => item.key === key)?.key ?? defaultServer;
|
||||
// The store outlives client-side navigation: one key per server list keeps another spec's choice out.
|
||||
const stateKey = createStateKey('servers', items.map((item) => item.key).join(' '));
|
||||
const { key, setKey } = useSelectState(stateKey, defaultServer);
|
||||
|
||||
return (
|
||||
<OpenAPIPathItem
|
||||
copyType="button"
|
||||
{...props}
|
||||
value={`${withServer ? selectedServer : ''}${path}`}
|
||||
value={`${withServer ? key : ''}${path}`}
|
||||
context={context}
|
||||
>
|
||||
{withServer ? (
|
||||
@@ -51,7 +49,7 @@ export function OpenAPIPathMultipleServers(
|
||||
className="openapi-select openapi-select-unstyled"
|
||||
items={items}
|
||||
itemClassName="openapi-select-item-column"
|
||||
stateKey={serversStateKey}
|
||||
stateKey={stateKey}
|
||||
placement="bottom start"
|
||||
icon={context.icons.chevronDown}
|
||||
defaultValue={defaultServer}
|
||||
|
||||
Reference in New Issue
Block a user