Compare commits

..

3 Commits

Author SHA1 Message Date
Peter White 49aa9bfdcf Keep open-tab updates pagination handling unchanged 2026-11-26 21:23:42 +00:00
Peter White c22c1214b7 changeset 2026-11-26 21:17:32 +00:00
Peter White d4109363d3 Tighten updates pagination eligibility to single top-level updates blocks 2026-11-26 21:16:49 +00:00
24 changed files with 319 additions and 729 deletions
-6
View File
@@ -1,6 +0,0 @@
---
"@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>`.
@@ -1,5 +0,0 @@
---
"@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.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Restrict updates pagination to single top-level Updates blocks.
+1 -1
View File
@@ -1,2 +1,2 @@
dist/
/standalone/
standalone/
+3 -41
View File
@@ -72,19 +72,6 @@ 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:
@@ -145,11 +132,6 @@ 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
@@ -180,12 +162,6 @@ import { GitBookProvider, GitBookFrame } from '@gitbook/embed/react';
]}
tools={[/* ... */]}
closeButton
onNavigate={(event) => {
if (event.tab === 'docs') {
setCurrentDocsPage(event.path);
}
}}
onClose={() => setHelpPanelOpen(false)}
/>
</GitBookProvider>
```
@@ -218,7 +194,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** | `GitBook('on', event, listener)` | `frame.on(event, listener)` | `onNavigate`, `onClose`, `onEscape` props |
| **Event listeners** | ❌ | `frame.on(event, listener)` | Via frame client |
| **Unload** | `GitBook('unload')` | ❌ | ❌ |
## Method Signatures
@@ -236,7 +212,6 @@ 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
@@ -252,30 +227,17 @@ function MyComponent() {
- `frame.postUserMessage(message: string)` → `void`
- `frame.clearChat()` → `void`
- `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void`
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). See [Events](#events)
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). Events: `close`, `escape`
### React Components
**Components:**
- `<GitBookProvider siteURL: string>` - Provider component
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props, and `onNavigate`, `onClose`, `onEscape` callbacks for the [events](#events))
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props)
**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:
@@ -1,82 +0,0 @@
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,7 +3,6 @@ import { createChannel } from 'bidc';
import type {
FrameToParentMessage,
GitBookEmbeddableConfiguration,
GitBookFrameEvents,
ParentToFrameMessage,
} from './protocol';
@@ -43,11 +42,8 @@ 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<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;
on: (event: string, listener: (...args: any[]) => void) => () => void;
};
/**
@@ -71,16 +67,9 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
channel.receive((message: FrameToParentMessage) => {
console.log('[gitbook:embed] received message', message);
switch (message.type) {
case 'close':
case 'escape':
emit(message.type);
break;
case 'navigate': {
const { type: _type, ...event } = message;
emit('navigate', event);
break;
}
if (message.type === 'close' || message.type === 'escape') {
const listeners = events.get(message.type) || [];
listeners.forEach((listener) => listener());
}
});
@@ -90,12 +79,6 @@ 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'],
@@ -119,7 +102,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
sendToFrame({ type: 'configure', settings: configuration });
},
clearChat: () => sendToFrame({ type: 'clearChat' }),
on: (event: string, listener: (...args: any[]) => void) => {
on: (event, listener) => {
const listeners = events.get(event) || [];
listeners.push(listener);
events.set(event, listeners);
+1 -36
View File
@@ -134,38 +134,6 @@ 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.
*/
@@ -176,7 +144,4 @@ export type FrameToParentMessage =
| {
/** Escape was pressed inside the frame and nothing in the frame handled it. */
type: 'escape';
}
| ({
type: 'navigate';
} & GitBookNavigateEvent);
};
-31
View File
@@ -6,21 +6,11 @@ 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>;
@@ -42,9 +32,6 @@ export function GitBookFrame(props: GitBookFrameProps) {
trademark = true,
closeButton = false,
assistantName,
onNavigate,
onClose,
onEscape,
} = props;
const frameRef = useRef<HTMLIFrameElement>(null);
@@ -62,24 +49,6 @@ 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,
@@ -1,78 +0,0 @@
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([]);
});
});
-40
View File
@@ -1,40 +0,0 @@
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,
};
}
+4 -16
View File
@@ -1,14 +1,13 @@
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;
@@ -36,11 +35,7 @@ type StandaloneCalls =
// Navigate to a page
| ['navigateToPage', string]
// Navigate to the assistant
| ['navigateToAssistant']
// Listen to an event from the embed, returns a function to stop listening
| {
[E in keyof GitBookFrameEvents]: ['on', E, GitBookFrameEvents[E]];
}[keyof GitBookFrameEvents];
| ['navigateToAssistant'];
type StandaloneConfiguration = {
/** Configure the button to open the embed */
@@ -52,7 +47,7 @@ type StandaloneConfiguration = {
};
};
export type GitBookStandalone = ((...args: StandaloneCalls) => void | (() => void)) & {
export type GitBookStandalone = ((...args: StandaloneCalls) => void) & {
q?: StandaloneCalls[];
};
@@ -61,7 +56,6 @@ 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',
@@ -158,7 +152,6 @@ 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);
@@ -167,7 +160,7 @@ function getIframe() {
return { iframe: widgetIframe, frame: _frame };
}
const GitBook = (...args: StandaloneCalls): void | (() => void) => {
const GitBook = (...args: StandaloneCalls) => {
switch (args[0]) {
case 'init': {
// `~gitbook/embed/script.js` already calls `init`, so an integrator following the docs
@@ -192,7 +185,6 @@ const GitBook = (...args: StandaloneCalls): void | (() => void) => {
widgetIframe.remove();
widgetIframe = undefined;
_frame = undefined;
frameEvents.detach();
if (wasOpen) {
getIframe();
}
@@ -202,7 +194,6 @@ const GitBook = (...args: StandaloneCalls): void | (() => void) => {
case 'unload':
_client = undefined;
_frame = undefined;
frameEvents.detach();
widgetIframe?.remove();
widgetIframe = undefined;
frameOptions = undefined;
@@ -281,9 +272,6 @@ const GitBook = (...args: StandaloneCalls): void | (() => void) => {
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]);
}
};
+1 -36
View File
@@ -15,7 +15,7 @@ import {
GitBookAPI,
SiteSocialAccountPlatform,
} from '@gitbook/api';
import type { GitBookNavigateEvent, GitBookStandalone } from '@gitbook/embed';
import type { GitBookStandalone } from '@gitbook/embed';
import { getContentTestURL, getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
import {
@@ -3560,41 +3560,6 @@ 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,5 +1,4 @@
import { EmbeddableAIChat } from './EmbeddableAIChat';
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
type EmbeddableAssistantPageProps = {
baseURL: string;
@@ -10,10 +9,5 @@ type EmbeddableAssistantPageProps = {
* Reusable page component for the embed assistant page.
*/
export async function EmbeddableAssistantPage(props: EmbeddableAssistantPageProps) {
return (
<>
<EmbeddableNavigateEvent tab="assistant" />
<EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />
</>
);
return <EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />;
}
@@ -25,9 +25,7 @@ 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';
@@ -83,11 +81,9 @@ 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"
@@ -109,7 +105,12 @@ export async function EmbeddableDocsPage(
</EmbeddableFrameHeaderMain>
<EmbeddableFrameButtons>
<EmbeddableDocsPageControlButtons
href={getEmbeddablePagePublishedPath(pageInput)}
href={context.linker
.toPathForPage({
pages: context.revision.pages,
page,
})
.replace(/~gitbook\/embed\/page\/?/, '')}
/>
</EmbeddableFrameButtons>
</EmbeddableFrameHeader>
@@ -8,7 +8,6 @@ import type { GitBookIntegrationTool } from '@gitbook/browser-types';
import type {
FrameToParentMessage,
GitBookEmbeddableConfiguration,
GitBookNavigateEvent,
ParentToFrameMessage,
} from '@gitbook/embed';
@@ -182,22 +181,6 @@ 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,4 +1,3 @@
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
import { EmbeddableSearch } from './EmbeddableSearch';
import { getSearchBaseProps } from '@/components/Search/search-props';
import type { GitBookSiteContext } from '@/lib/context';
@@ -14,13 +13,10 @@ export function EmbeddableSearchPage(props: EmbeddableSearchPageProps) {
const { context } = props;
return (
<>
<EmbeddableNavigateEvent tab="search" />
<EmbeddableSearch
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
siteTitle={context.site.title}
searchProps={getSearchBaseProps(context)}
/>
</>
<EmbeddableSearch
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
siteTitle={context.site.title}
searchProps={getSearchBaseProps(context)}
/>
);
}
@@ -1,82 +0,0 @@
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',
});
});
});
@@ -1,45 +0,0 @@
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,11 +39,10 @@ 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';
@@ -249,9 +248,12 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
if (props.updatesPage) {
const document = await getPageDocument(context, page);
if (document) {
const count = countDocumentUpdates(document);
if (count > UPDATES_PAGINATION_THRESHOLD) {
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status === 'eligible') {
const { page: pageNumber } = getUpdatesPageRange(
props.updatesPage,
eligibility.updates.length
);
title = `${title} (Page ${pageNumber})`;
if (!pageMetaLinks?.canonical) {
const url = new URL(canonical);
@@ -378,17 +380,29 @@ 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 } = paginateUpdatesDocument(fullDocument, context.revision, {
page: props.updatesPage ?? 1,
}));
({ document, pagination, eligibility } = paginateUpdatesDocument(
fullDocument,
context.revision,
{
page: props.updatesPage ?? 1,
}
));
}
if (pagination || props.updatesPage) {
if (eligibility?.status === 'skipped' || 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', {
+162 -81
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'bun:test';
import {
type DocumentBlockHeading,
type DocumentBlockParagraph,
type DocumentBlockUpdate,
type DocumentBlockUpdates,
DocumentTextColor,
type JSONDocument,
type Revision,
@@ -10,8 +14,9 @@ import {
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
import {
UPDATES_TAG_FILTER_CAP,
countDocumentUpdates,
type UpdatesPaginationEligibility,
findUpdateAnchorPage,
getUpdatesPaginationEligibility,
paginateUpdatesDocument,
parseUpdatesPageParam,
getDocumentFilterableTags,
@@ -97,63 +102,119 @@ describe('normalizeUpdatesFilterTags', () => {
});
describe('updates pagination', () => {
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
);
it('paginates a single top-level updates block and keeps the surrounding blocks', () => {
const document = createDocument([
createHeading('intro'),
createParagraph(),
createUpdatesBlock(createUpdateEntries(260)),
createParagraph(),
]);
for (const [page, start] of [
[1, 1],
[7, 121],
] as const) {
const result = paginateUpdatesDocument(document, undefined, { page });
expect(result.pagination).toMatchObject({
expect(result.pagination).toEqual({
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')],
@@ -167,8 +228,7 @@ describe('updates pagination', () => {
return ['even'];
}
return [];
}),
30
})
);
const result = paginateUpdatesDocument(document, revision, {
@@ -184,7 +244,6 @@ 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', () => {
@@ -195,8 +254,7 @@ describe('updates pagination', () => {
return ['fixes'];
}
return [];
}),
26
})
);
expect(
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
@@ -263,45 +321,68 @@ function getUpdateIds(document: JSONDocument) {
});
}
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
const entries = entryTags.map((tags, index) => ({
object: 'block' as const,
type: 'update' as const,
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',
data: {
date: '2026-05-01',
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
tags: (entryTags[index] ?? []).map((tag) => ({ kind: 'tag', tag })),
},
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: [],
},
],
isVoid: false,
nodes: [createHeading(`update-${index + 1}`)],
}));
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))
);
}
}
return { object: 'document', data: { schemaVersion: 2 }, nodes };
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: [] };
}
function createTag(slug: string, label: string): RevisionTag {
+95 -28
View File
@@ -1,6 +1,7 @@
import type {
DocumentBlock,
DocumentBlockUpdate,
DocumentBlockUpdates,
DocumentInline,
JSONDocument,
Revision,
@@ -30,6 +31,21 @@ 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';
@@ -117,38 +133,100 @@ export function getDocumentFilterableTags(
return tags;
}
export function countDocumentUpdates(document: JSONDocument): number {
return getDocumentUpdates(document).length;
/**
* 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 paginateUpdatesDocument(
document: JSONDocument,
revision: Revision | undefined,
{ page, tags }: { page: number; tags?: string[] }
): { document: JSONDocument; pagination: UpdatesPageRange | null } {
const updates = getDocumentUpdates(document);
if (updates.length <= UPDATES_PAGINATION_THRESHOLD) {
return { document, pagination: null };
): {
document: JSONDocument;
pagination: UpdatesPageRange | null;
eligibility: UpdatesPaginationEligibility;
} {
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { document, pagination: null, eligibility };
}
const matching = filterUpdates(updates, document, revision, tags);
const matching = filterUpdates(eligibility.updates, document, revision, tags);
const pagination = getUpdatesPageRange(page, matching.length);
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
const entries = matching.slice(pagination.start - 1, pagination.end);
const nodes: JSONDocument['nodes'] = [];
for (const block of document.nodes) {
if (block.type !== 'updates') {
if (block !== eligibility.block) {
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 };
return { document: { ...document, nodes }, pagination, eligibility };
}
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
@@ -175,7 +253,12 @@ export function findUpdateAnchorPage(
revision: Revision | undefined,
{ anchor, tags }: { anchor: string; tags?: string[] }
): { found: true; page: number; clearTags: boolean } | { found: false } {
const updates = getDocumentUpdates(document);
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { found: false };
}
const { updates } = eligibility;
const index = updates.findIndex((update) =>
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
);
@@ -209,22 +292,6 @@ 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,
@@ -1,47 +0,0 @@
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,6 +8,8 @@ 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.
*/
@@ -18,6 +20,7 @@ export function OpenAPIPathMultipleServers(
const { path, servers } = data;
const defaultServer = getDefaultServerURL(servers);
const { key, setKey } = useSelectState(serversStateKey, defaultServer);
const formattedPath = formatPath(path);
const items = servers
@@ -33,15 +36,14 @@ export function OpenAPIPathMultipleServers(
};
});
// 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);
// 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;
return (
<OpenAPIPathItem
copyType="button"
{...props}
value={`${withServer ? key : ''}${path}`}
value={`${withServer ? selectedServer : ''}${path}`}
context={context}
>
{withServer ? (
@@ -49,7 +51,7 @@ export function OpenAPIPathMultipleServers(
className="openapi-select openapi-select-unstyled"
items={items}
itemClassName="openapi-select-item-column"
stateKey={stateKey}
stateKey={serversStateKey}
placement="bottom start"
icon={context.icons.chevronDown}
defaultValue={defaultServer}