Compare commits

..

3 Commits

Author SHA1 Message Date
Steven H a9f9ba6269 Address review feedback on llms.txt splitting
- Link split-out sections to the llms.txt of the listed language variant
- Link groups to their own llms.txt so every list line is a link
- Render the full index first so files under the limit stay whole
- Split with a priority queue so large sites split in linear time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:04:37 +00:00
Steven H eb6d3f85bb changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:35:14 +00:00
Steven H 6d056cdd76 Split llms.txt into scoped indexes past 100k characters
Large sites produced llms.txt files that agents truncate or skip. Once the
index exceeds 100,000 characters, the parts that save the most space are
replaced by links to their own llms.txt, served at the section, site space
or page path as the llms.txt spec allows. Pages also point to their
llms.txt with a describedby link header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:35:14 +00:00
181 changed files with 4366 additions and 6611 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep links in generated Markdown usable outside the source page.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer Assistant questions with medium reasoning instead of low, matching AI search.
-6
View File
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
-6
View File
@@ -1,6 +0,0 @@
---
"gitbook": minor
"@gitbook/react-openapi": minor
---
Replace the Scalar API client behind "Test it" with a lightweight Try it panel.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
@@ -1,5 +0,0 @@
---
"@gitbook/react-openapi": patch
---
Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": minor
---
Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Respect disabled change request previews on published sites.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Split llms.txt into per-section and per-page indexes when it exceeds 100,000 characters, and point pages to their llms.txt with a `describedby` link header.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show loading rows shaped like search results while search waits for the server.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Stop caching site search results in the framework cache, so every search reaches the API.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show one server-ordered search list and open its top result on Enter.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render small cards in a responsive four-column grid and carousel.
-28
View File
@@ -51,31 +51,3 @@ jobs:
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
linear-release:
name: Track the production release in Linear
needs: [deploy-v2-vercel, deploy-v2-cloudflare]
runs-on: ubuntu-latest
timeout-minutes: 10
# Release tracking must never fail a deployment that already succeeded.
continue-on-error: true
permissions:
contents: read
env:
LINEAR_ACCESS_KEY: ${{ secrets.PRODUCTION_LINEAR_RELEASE_ACCESS_KEY }}
steps:
- name: Skip release tracking without an access key
if: env.LINEAR_ACCESS_KEY == ''
run: echo "::warning::No Linear pipeline access key is configured, skipped tracking the release."
- name: Checkout
if: env.LINEAR_ACCESS_KEY != ''
uses: actions/checkout@v4
with:
# The Linear CLI scans commit metadata since the last release, so it needs history but no blobs.
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Sync the release to Linear
if: env.LINEAR_ACCESS_KEY != ''
uses: linear/linear-release-action@dd4fc407f860b9460d2cf0b3fb1edd8985cf443f # v0.18.2
with:
access_key: ${{ env.LINEAR_ACCESS_KEY }}
-20
View File
@@ -59,26 +59,6 @@ Run a specific test file:
cd packages/gitbook && bun test src/lib/cache.test.ts
```
## Changes customers see on their live site
Published sites are our customers' product. If a change alters how their content looks or behaves without them changing anything, it needs a comms decision before it merges.
It counts if it ships on by default and any of these are true:
- It changes structure or navigation: outline/"On this page", sidebar, TOC, headings, breadcrumbs, pagination, header or footer.
- Something new appears on every page (or every page of a type), or something existing disappears or moves.
- Layout or typography shifts enough that a customer would notice in a screenshot.
- URLs, anchors, redirects, SEO/meta tags or search/Ask behaviour change.
- A default changes for existing sites.
It does not count when:
- It's behind a flag, a site setting or opt-in that stays off for existing sites until comms go out.
- It's a bug fix that restores the intended behaviour.
- It only affects the editor/app, not published content.
When it counts:
1. Warn the engineer before the PR is opened: "This changes customers' live sites. Have the support and sales leads agreed the rollout and announcement?"
2. Suggest a flag or staged rollout if there isn't one, so it can ship dark and be turned on after the notice goes out.
## Bumping Next.js or OpenNext
Type checks and unit tests miss runtime regressions: OpenNext 4.1.15 changed the composable cache key format, and every `'use cache'` call silently missed for days. Before committing a bump of `next`, `@opennextjs/aws` or `@opennextjs/cloudflare`, run both runtimes locally from `packages/gitbook`:
+601 -11
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -48,7 +48,8 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.210.0",
"@gitbook/api": "0.208.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"assert-never": "^1.4.0",
+1 -8
View File
@@ -127,11 +127,6 @@ frame.configure({
frame.on('close', () => {
console.log('Frame closed');
});
// Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it
frame.on('escape', () => {
closeHelpPanel();
});
```
## As React components
@@ -227,7 +222,7 @@ 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)
### React Components
@@ -399,8 +394,6 @@ Available in: Standalone script, NPM package, React components
Suggested questions displayed in the [Assistant](https://gitbook.com/docs/publishing-documentation/gitbook-ai-assistant) welcome screen.
Omit `suggestions` when creating the embed or pass an empty array to use the site's suggested questions. If the site has no suggested questions, the Assistant shows generic questions. Later `configure` calls keep the current setting unless you pass `suggestions`. To restore the site's questions, remove the React prop or pass `{ suggestions: [] }` or `{ suggestions: undefined }` to `configure`.
- **Type**: `string[]`
```javascript
@@ -38,10 +38,7 @@ export type GitBookFrameClient = {
configure: (settings: Partial<GitBookEmbeddableConfiguration>) => void;
/**
* Register an event listener and get back a function that removes it.
*
* - `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.
* Register an event listener.
*/
on: (event: string, listener: (...args: any[]) => void) => () => void;
};
@@ -67,9 +64,11 @@ 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());
if (message.type === 'close') {
const listeners = events.get('close') || [];
if (listeners) {
listeners.forEach((listener) => listener());
}
}
});
@@ -84,7 +83,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
tabs: ['assistant', 'search', 'docs'],
actions: [],
greeting: { title: '', subtitle: '' },
suggestions: undefined,
suggestions: [],
tools: [],
trademark: true,
};
@@ -109,7 +108,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
return () => {
events.set(
event,
(events.get(event) || []).filter((l) => l !== listener)
listeners.filter((l) => l !== listener)
);
};
},
+5 -10
View File
@@ -94,8 +94,8 @@ export type GitBookEmbeddableConfiguration = {
*/
assistantName?: string;
/** Welcome questions. Omit or pass [] to inherit the site's questions. */
suggestions?: string[] | undefined;
/** Suggestions of questions to be displayed in the welcome page. */
suggestions: string[];
/** Tools to be provided to the assistant. */
tools: GitBookToolDefinition[];
@@ -137,11 +137,6 @@ export type ParentToFrameMessage =
/**
* Messages sent from the frame to the parent.
*/
export type FrameToParentMessage =
| {
type: 'close';
}
| {
/** Escape was pressed inside the frame and nothing in the frame handled it. */
type: 'escape';
};
export type FrameToParentMessage = {
type: 'close';
};
+1 -1
View File
@@ -24,7 +24,7 @@ export function GitBookFrame(props: GitBookFrameProps) {
visitor,
actions = [],
greeting,
suggestions,
suggestions = [],
tools = [],
tabs = ['assistant', 'search', 'docs'],
defaultTab,
+1
View File
@@ -63,6 +63,7 @@ let frameConfiguration: GitBookEmbeddableConfiguration & StandaloneConfiguration
},
actions: [],
greeting: { title: '', subtitle: '' },
suggestions: [],
tools: [],
tabs: ['assistant', 'search', 'docs'],
trademark: true,
+12 -866
View File
@@ -1,4 +1,4 @@
import { type Page, type Request, type Route, expect, test } from '@playwright/test';
import { type Page, expect } from '@playwright/test';
import jwt from 'jsonwebtoken';
import {
@@ -12,12 +12,11 @@ import {
CustomizationIconsStyle,
CustomizationPageActionType,
CustomizationSidebarListStyle,
GitBookAPI,
SiteSocialAccountPlatform,
} from '@gitbook/api';
import type { GitBookStandalone } from '@gitbook/embed';
import { getContentTestURL, getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
import { getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
import {
type Test,
type TestsCase,
@@ -42,15 +41,16 @@ import {
import { VISITOR_TOKEN_COOKIE } from '@/lib/visitors';
// Kept as deterministic as possible to reduce visual flakiness: no preamble, a
// single fixed search, and a concise answer. The model is never perfectly
// deterministic, so `overrideAIResponse` still normalizes the rendered content
// below — this prompt just narrows the variance.
// single fixed search, a concise answer, and a fixed number of follow-ups. The
// model is never perfectly deterministic, so `overrideAIResponse` still
// normalizes the rendered content below — this prompt just narrows the variance.
const AI_PROMPT = [
"You're being invoked by the GitBook CI/CD pipeline for automated visual testing.",
'Follow these instructions exactly and do not deviate:',
'1. Do not write any preamble, commentary, or reasoning before acting.',
'2. Perform a single search for exactly "Lorem ipsum".',
'3. Reply with only the first sentence of the first page you find, and nothing else.',
'4. Always end by proposing exactly 3 follow-up suggestions.',
].join('\n');
// `InsightsProvider` debounces its flushes by 1.5s.
@@ -74,62 +74,6 @@ function trackInsightsEvents(page: Page, type: string) {
return collected;
}
/**
* Hold the page's search requests until the test answers them, and find a held one by query.
*/
async function holdSearchRequests(page: Page) {
// Without a pass every search goes through the route, whether or not the site's flag gives one.
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
const held: Route[] = [];
await page.route('**/~gitbook/search', (route) => {
held.push(route);
});
return async (query: string) => {
await expect
.poll(() => held.some((route) => route.request().postDataJSON().query === query))
.toBe(true);
const index = held.findIndex((route) => route.request().postDataJSON().query === query);
const [route] = held.splice(index, 1);
if (!route) {
throw new Error(`No held search for "${query}"`);
}
return route;
};
}
/**
* Answer a held search request with the server's own answer, and return its top result.
*/
async function answerSearch(route: Route) {
const response = await route.fetch();
const [topResult]: { title: string; href: string }[] = await response.json();
await route.fulfill({ response });
if (!topResult) {
throw new Error('The search answer has no results');
}
return topResult;
}
/**
* Build a page result for a search answer given by the test.
*/
function searchPageResult(route: Route, siteSpaceId: string, title: string, path: string) {
const sitePath = new URL(route.request().url()).pathname.replace('~gitbook/search', '');
return {
type: 'page',
id: `space/${title}`,
pageId: title,
spaceId: 'space',
siteSpaceId,
title,
description: '',
href: `${sitePath}${path}`,
score: 1,
rank: 1,
};
}
const overrideAIInitialState = () => {
const greeting = document.querySelector('[data-testid="ai-chat-greeting-title"]');
if (greeting) {
@@ -214,29 +158,6 @@ const searchTestCases: Test[] = [
await expect(page.getByTestId('search-input')).toBeFocused();
},
},
{
name: 'Search - Loading rows cannot be activated',
url: getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
}),
screenshot: false,
run: async (page) => {
await waitForCookiesDialog(page);
const heldSearch = await holdSearchRequests(page);
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('gitbook');
await heldSearch('gitbook');
const searchPopup = page.getByTestId('search-popover');
await expect(searchPopup.locator('[aria-busy="true"]').first()).toBeVisible();
await expect(searchPopup.getByTestId('search-page-result')).toHaveCount(0);
await expect(searchPopup.getByRole('link')).toHaveCount(0);
},
},
{
name: 'Search - Keyboard focus exits to the next page control',
url: getCustomizationURL({
@@ -288,48 +209,6 @@ const searchTestCases: Test[] = [
await expect(searchInput).toHaveValue('getting started');
},
},
{
name: 'Search - Retry after a failed search sends the query once',
url: getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
header: {
preset: CustomizationHeaderPreset.None,
},
}),
screenshot: false,
run: async (page) => {
await waitForCookiesDialog(page);
// Keep the search on the failing route whether or not the site gives search passes.
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
let failing = true;
await page.route('**/~gitbook/search', (route) =>
failing ? route.fulfill({ status: 500 }) : route.continue()
);
const sentQueries: string[] = [];
page.on('request', (request) => {
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
sentQueries.push(request.postDataJSON().query);
}
});
const searchInput = page.getByTestId('search-input').locator('visible=true');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('gitbook');
const retry = page.getByRole('button', { name: 'Try again' }).locator('visible=true');
await expect(retry).toBeVisible();
failing = false;
sentQueries.length = 0;
await retry.click();
await expect(searchInput).toHaveValue('gitbook');
await expect(page.getByTestId('search-results').locator('visible=true')).toBeVisible();
await page.waitForTimeout(1000);
expect(sentQueries).toEqual(['gitbook']);
},
},
{
name: 'Search - AI Mode: None - URL query (Initial)',
url: `${getCustomizationURL({
@@ -407,68 +286,6 @@ const searchTestCases: Test[] = [
expect(top).toBeLessThanOrEqual(150);
},
},
{
name: 'Search - Enter while results load opens the top result of the last query',
url: `blocks/lists${getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
})}`,
screenshot: false,
run: async (page) => {
await waitForCookiesDialog(page);
const heldSearch = await holdSearchRequests(page);
const startPath = new URL(page.url()).pathname;
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('gitbook');
const firstSearch = await heldSearch('gitbook');
await searchInput.selectText();
await searchInput.pressSequentially('files');
const lastSearch = await heldSearch('files');
await page.keyboard.press('Enter');
await answerSearch(firstSearch).catch(() => {});
await page.waitForTimeout(1000);
await expect(page.getByTestId('search-popover')).toBeVisible();
await expect(searchInput).toBeFocused();
expect(new URL(page.url()).pathname).toBe(startPath);
const topResult = await answerSearch(lastSearch);
await expect(
page.getByRole('heading', { level: 1, name: topResult.title, exact: true })
).toBeVisible({ timeout: 20000 });
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
},
},
{
name: 'Search - Enter opens the result under the mouse',
url: `blocks/lists${getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
})}`,
screenshot: false,
run: async (page) => {
await waitForCookiesDialog(page);
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
await searchInput.pressSequentially('gitbook');
const searchPopup = page.getByTestId('search-popover');
const hovered = searchPopup.getByTestId('search-page-result').nth(1);
await hovered.hover();
await expect(hovered).toHaveClass(/is-active/);
await expect(searchPopup.locator('[role="option"].is-active')).toHaveCount(1);
const href = await hovered.getAttribute('href');
await page.keyboard.press('Enter');
await expect
.poll(() => new URL(page.url()).pathname, { timeout: 20000 })
.toBe(new URL(href ?? '', page.url()).pathname);
},
},
{
name: 'Ask - AI Mode: Assistant - Complete flow',
url: getCustomizationURL({
@@ -489,9 +306,10 @@ const searchTestCases: Test[] = [
await expect(page.getByTestId('ai-chat')).toBeVisible();
await expect(page.getByTestId('ai-chat-message-user').first()).toHaveText(AI_PROMPT);
await expect(page.getByTestId('ai-chat-message-assistant').first()).toBeVisible();
// Wait for the stream, follow-up phase included, to finish before screenshotting.
// Follow-ups aren't asserted: the API can return none for this prompt.
// Wait for the full response (incl. follow-up suggestions) to settle before
// asserting/screenshotting, rather than racing a fixed suggestion count.
await waitForAIChatResponse(page);
await expect(page.getByTestId('ai-chat-followup-suggestion').first()).toBeVisible();
},
// Re-applied per viewport so the replacement survives resize-driven re-renders.
normalizeBeforeScreenshot: (page) => page.evaluate(overrideAIResponse),
@@ -559,553 +377,16 @@ const searchTestCases: Test[] = [
await expect(page.getByTestId('ai-chat')).toBeVisible();
await expect(page.getByTestId('ai-chat-message-user').first()).toHaveText(AI_PROMPT);
await expect(page.getByTestId('ai-chat-message-assistant').first()).toBeVisible();
// Wait for the stream, follow-up phase included, to finish before screenshotting.
// Follow-ups aren't asserted: the API can return none for this prompt.
// Wait for the full response (incl. follow-up suggestions) to settle before
// asserting/screenshotting, rather than racing a fixed suggestion count.
await waitForAIChatResponse(page);
await expect(page.getByTestId('ai-chat-followup-suggestion').first()).toBeVisible();
},
// Re-applied per viewport so the replacement survives resize-driven re-renders.
normalizeBeforeScreenshot: (page) => page.evaluate(overrideAIResponse),
},
];
const SEARCH_API_URL = /\/v1\/orgs\/[^/]+\/sites\/[^/]+\/search$/;
const SEARCH_PASS_RECORD = {
type: 'record',
id: 'search-pass-record',
title: 'Answered by the search API',
description: 'A search made with a search pass',
url: 'https://example.com/search-pass',
score: 1,
};
/**
* Answer the page's search pass requests as the API does when passes are switched on.
*/
async function giveSearchPasses(page: Page, lifetimesMs: number[] = []) {
let passes = 0;
await page.route('**/~gitbook/search-pass', async (route) => {
passes += 1;
await route.fulfill({
json: {
token: `test-search-pass-${passes}`,
expiresIn: lifetimesMs.shift() ?? 300_000,
},
});
});
}
/**
* Answer each search API call with the next status, and with a record when it succeeds.
*/
async function answerSearchAPI(page: Page, statuses: number[] = []) {
const calls: Request[] = [];
await page.route(SEARCH_API_URL, async (route) => {
calls.push(route.request());
const status = statuses.shift() ?? 200;
await route.fulfill({
status,
headers: { 'access-control-allow-origin': '*' },
json: status === 200 ? { items: [SEARCH_PASS_RECORD] } : { error: { code: status } },
});
});
return calls;
}
/**
* Collect the searches the page sends to the site's search route.
*/
function trackRouteSearches(page: Page) {
const searches: Request[] = [];
page.on('request', (request) => {
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
searches.push(request);
}
});
return searches;
}
/**
* Open search and wait for the page to receive its search pass.
*/
async function openSearchWithPass(page: Page) {
const passReply = page.waitForResponse('**/~gitbook/search-pass');
await page.getByTestId('search-input').focus();
await passReply;
}
async function typeSearch(page: Page, text: string) {
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
await searchInput.pressSequentially(text);
}
const searchPassTestCases: Test[] = [
{
name: 'No pass: searches go through the site route',
url: '',
screenshot: false,
run: async (page) => {
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
const passReply = page.waitForResponse('**/~gitbook/search-pass');
const apiCalls: Request[] = [];
page.on('request', (request) => {
if (SEARCH_API_URL.test(request.url())) {
apiCalls.push(request);
}
});
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await typeSearch(page, 'gitbook');
expect((await passReply).status()).toBe(204);
await expect
.poll(() => routeSearches.length, { timeout: 30_000 })
.toBeGreaterThanOrEqual(1);
expect((await routeSearches[0]?.response())?.status()).toBe(200);
expect(apiCalls).toHaveLength(0);
},
},
{
name: 'With a pass: searches go straight to the API',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const apiCalls = await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
expect((await apiCalls[0]?.allHeaders())?.authorization).toBe(
'Bearer test-search-pass-1'
);
expect(routeSearches).toHaveLength(0);
},
},
{
name: 'Expired pass: the search uses the route, then the next pass searches the API',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page, [1_000]);
const apiCalls = await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('expired');
expect(apiCalls).toHaveLength(0);
await typeSearch(page, ' editor');
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
expect((await apiCalls[0]?.allHeaders())?.authorization).toBe(
'Bearer test-search-pass-2'
);
},
},
{
name: 'Refused pass: the page stays on the route',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const apiCalls = await answerSearchAPI(page, [403]);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
expect(
routeSearches.map((request) => request.headers()['x-gitbook-search-fallback'])
).toEqual(['403', '403']);
expect(apiCalls).toHaveLength(1);
expect((await routeSearches.at(-1)?.response())?.status()).toBe(200);
},
},
{
name: 'Dropped API request: the search falls back to the route after its time limit',
url: '',
screenshot: false,
run: async (page) => {
await page.clock.install();
await giveSearchPasses(page);
const apiCalls: Request[] = [];
await page.route(SEARCH_API_URL, (route) => {
apiCalls.push(route.request());
});
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await page.clock.fastForward(5_000);
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('timeout');
expect((await routeSearches[0]?.response())?.status()).toBe(200);
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
expect(apiCalls).toHaveLength(1);
},
},
{
name: 'Withdrawn pass: a no-pass reply stops the page using the earlier pass',
url: '',
screenshot: false,
run: async (page) => {
let passReplies = 0;
await page.route('**/~gitbook/search-pass', async (route) => {
passReplies += 1;
await (passReplies === 1
? route.fulfill({ json: { token: 'test-search-pass-1', expiresIn: 300_000 } })
: route.fulfill({ status: 204 }));
});
const apiCalls = await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
await page.keyboard.press('Escape');
await openSearchWithPass(page);
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(apiCalls).toHaveLength(1);
},
},
{
name: 'Rejected replacement pass: the page stays on the route after one refresh',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const passRequests: Request[] = [];
page.on('request', (request) => {
if (request.url().endsWith('/~gitbook/search-pass')) {
passRequests.push(request);
}
});
const apiCalls = await answerSearchAPI(page, [401, 401, 401, 401]);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
for (const [index, text] of ['gitbook', ' editor', ' blocks', ' lists'].entries()) {
await typeSearch(page, text);
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(index + 1);
await page.waitForTimeout(500);
}
expect(apiCalls).toHaveLength(2);
expect(passRequests).toHaveLength(2);
},
},
{
name: 'Rate limited: the next query waits for the cooldown before using the route',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const apiCalls = await answerSearchAPI(page, [429]);
const routeSearchTimes: number[] = [];
page.on('request', (request) => {
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
routeSearchTimes.push(Date.now());
}
});
await waitForCookiesDialog(page);
await openSearchWithPass(page);
const rateLimited = page.waitForResponse(SEARCH_API_URL);
await typeSearch(page, 'gitbook');
await rateLimited;
const rateLimitedAt = Date.now();
await typeSearch(page, ' editor');
await expect.poll(() => routeSearchTimes.length, { timeout: 30_000 }).toBe(1);
expect(routeSearchTimes[0]! - rateLimitedAt).toBeGreaterThanOrEqual(1_500);
expect(apiCalls).toHaveLength(1);
},
},
{
name: 'Renewing pass: a search typed before the reply goes to the route',
url: '',
screenshot: false,
run: async (page) => {
let releaseRenewal = () => {};
const renewalHeld = new Promise<void>((resolve) => {
releaseRenewal = resolve;
});
let passReplies = 0;
await page.route('**/~gitbook/search-pass', async (route) => {
passReplies += 1;
if (passReplies === 1) {
await route.fulfill({
json: { token: 'test-search-pass-1', expiresIn: 300_000 },
});
return;
}
await renewalHeld;
await route.fulfill({ status: 204 }).catch(() => undefined);
});
const apiCalls = await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await page.keyboard.press('Escape');
const renewal = page.waitForRequest('**/~gitbook/search-pass');
await typeSearch(page, ' editor');
await renewal;
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(apiCalls).toHaveLength(1);
releaseRenewal();
},
},
{
name: 'Rate limited by a shared limit: searches fail at once until its reset',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const apiCalls: Request[] = [];
await page.route(SEARCH_API_URL, async (route) => {
apiCalls.push(route.request());
await route.fulfill({
status: 429,
headers: {
'access-control-allow-origin': '*',
'access-control-expose-headers': 'x-ratelimit-reset, x-ratelimit-scope',
'x-ratelimit-reset': String(Math.ceil(Date.now() / 1000) + 60),
'x-ratelimit-scope': 'tenant-operation',
},
json: { error: { code: 429 } },
});
});
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await typeSearch(page, ' editor');
await expect(page.getByRole('button', { name: 'Try again' })).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(3_000);
expect(routeSearches).toHaveLength(0);
expect(apiCalls).toHaveLength(1);
},
},
{
name: 'Cancelled search: a late API answer never replaces the newer query',
url: '',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
const staleTitle = 'Late answer for an older query';
await page.route(SEARCH_API_URL, async (route) => {
const { query } = route.request().postDataJSON() as { query: string };
const stale = query === 'gitbook';
if (stale) {
await page.waitForTimeout(3_000);
}
await route
.fulfill({
headers: { 'access-control-allow-origin': '*' },
json: {
items: [
stale
? { ...SEARCH_PASS_RECORD, title: staleTitle }
: SEARCH_PASS_RECORD,
],
},
})
.catch(() => undefined);
});
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
const firstSearch = page.waitForRequest(
(request) =>
SEARCH_API_URL.test(request.url()) &&
(request.postDataJSON() as { query: string }).query === 'gitbook'
);
await openSearchWithPass(page);
await typeSearch(page, 'gitbook');
await firstSearch;
await typeSearch(page, ' editor');
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(4_000);
await expect(page.getByText(staleTitle)).toHaveCount(0);
expect(routeSearches).toHaveLength(0);
},
},
{
name: 'Embedded search goes straight to the API',
url: '~gitbook/embed/search',
screenshot: false,
run: async (page) => {
await giveSearchPasses(page);
await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
// The embedded page keeps <html> hidden, so wait for hydration without visibility.
await page.locator('html.hydrated').waitFor({ state: 'attached' });
// The embedded search opens on the first key; a one-letter query is never sent.
const passReply = page.waitForResponse('**/~gitbook/search-pass');
await typeSearch(page, 'g');
await passReply;
await typeSearch(page, 'itbook');
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
// The one-letter query can reach the route when it is sent before the pass arrives.
const routeQueries = routeSearches.map((request) => request.postDataJSON().query);
expect(routeQueries).not.toContain('gitbook');
},
},
];
const VISITOR_AUTH_SITE = 'https://gitbook.gitbook.io/gbo-va-space/';
function signVisitorToken(name: string) {
return jwt.sign({ name }, '70b844d0-c519-4532-8586-5970ce48c537', { expiresIn: '24h' });
}
/**
* Give the page one search pass, then answer later pass requests with `later` or the site's route.
*/
async function giveOneSearchPass(page: Page, later?: { token: string }) {
let passes = 0;
await page.route('**/~gitbook/search-pass', async (route) => {
passes += 1;
if (passes > 1 && !later) {
await route.continue();
return;
}
await route.fulfill({
json: {
token: passes === 1 ? 'test-search-pass-1' : later?.token,
expiresIn: 300_000,
},
});
});
}
/**
* Open a second tab of the site at `path`, keeping it from leaving for an upstream sign-in page.
*/
async function visitInOtherTab(page: Page, path: string) {
const other = await page.context().newPage();
await other.route(
(url) => url.hostname !== new URL(page.url()).hostname,
(route) => route.abort()
);
await other.goto(getContentTestURL(new URL(path, VISITOR_AUTH_SITE).href), {
waitUntil: 'commit',
});
await other.close();
}
/**
* Close search and open it again, waiting for the pass request that opening sends.
*/
async function reopenSearch(page: Page) {
await page.keyboard.press('Escape');
const passReply = page.waitForResponse('**/~gitbook/search-pass');
await page.getByTestId('search-input').focus();
return passReply;
}
const searchPassSessionTestCases: Test[] = [
{
name: 'Signed out in another tab: reopening search drops the pass',
url: () => `first?jwt_token=${signVisitorToken('gitbook-open-tests')}`,
screenshot: false,
run: async (page) => {
await giveOneSearchPass(page);
const apiCalls = await answerSearchAPI(page);
const routeSearches = trackRouteSearches(page);
await waitForHydration(page);
await openSearchWithPass(page);
await typeSearch(page, 'first');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await visitInOtherTab(page, '~gitbook/auth/logout');
await expect
.poll(async () =>
(await page.context().cookies()).some((cookie) =>
cookie.name.startsWith(VISITOR_TOKEN_COOKIE)
)
)
.toBe(false);
expect((await reopenSearch(page)).status()).toBe(401);
await typeSearch(page, ' page');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(apiCalls).toHaveLength(1);
},
},
{
name: 'Signed in as another visitor in another tab: reopening search uses the new pass',
url: () => `first?jwt_token=${signVisitorToken('gitbook-open-tests')}`,
screenshot: false,
run: async (page) => {
await giveOneSearchPass(page, { token: 'test-search-pass-2' });
const apiCalls = await answerSearchAPI(page);
await waitForHydration(page);
await openSearchWithPass(page);
await typeSearch(page, 'first');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
const otherVisitor = signVisitorToken('another-visitor');
await visitInOtherTab(page, `first?jwt_token=${otherVisitor}`);
const passReply = await reopenSearch(page);
expect((await passReply.request().allHeaders()).cookie).toContain(otherVisitor);
await typeSearch(page, ' page');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(2);
expect((await apiCalls[1]?.allHeaders())?.authorization).toBe(
'Bearer test-search-pass-2'
);
},
},
];
const testCases: TestsCase[] = [
{
name: 'GitBook Site (Single Variant)',
@@ -1199,59 +480,6 @@ const testCases: TestsCase[] = [
await spaceDrowpdown.waitFor();
},
},
{
name: 'Search scope change while loading shows the new answer in server order',
url: '',
screenshot: false,
run: async (page) => {
await waitForHydration(page);
const heldSearch = await holdSearchRequests(page);
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('quick');
const variantSearch = await heldSearch('quick');
const searchPopup = page.getByTestId('search-popover');
await searchPopup.getByRole('button', { name: 'Multi-Variants' }).click();
await page.getByRole('menuitem', { name: /All content/ }).click();
const allContentSearch = await heldSearch('quick');
const variantScope = variantSearch.request().postDataJSON().scope;
expect(allContentSearch.request().postDataJSON().scope).not.toEqual(
variantScope
);
const { siteSpaceId } = variantScope;
await allContentSearch.fulfill({
json: [
searchPageResult(allContentSearch, siteSpaceId, 'Welcome!', ''),
searchPageResult(
allContentSearch,
siteSpaceId,
'Quick Start',
'quick-start'
),
],
});
await variantSearch
.fulfill({
json: [
searchPageResult(
variantSearch,
siteSpaceId,
'Quick Start',
'quick-start'
),
],
})
.catch(() => {});
const results = searchPopup.getByTestId('search-page-result');
await expect(results).toHaveText([/Welcome!/, /Quick Start/]);
await page.waitForTimeout(1000);
await expect(results).toHaveText([/Welcome!/, /Quick Start/]);
},
},
{
name: 'Default variant',
url: '',
@@ -1949,16 +1177,6 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: searchTestCases,
},
{
name: 'Search pass',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: searchPassTestCases,
},
{
name: 'Search pass with visitor authentication',
contentBaseURL: VISITOR_AUTH_SITE,
tests: searchPassSessionTestCases,
},
{
name: 'Content tests',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
@@ -3769,78 +2987,6 @@ const testCases: TestsCase[] = [
},
],
},
{
name: 'Docs Embed - Search',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/~gitbook/embed/',
tests: [
{
name: 'Enter while results load opens the top result',
url: 'search',
screenshot: false,
run: async (page) => {
await page.waitForLoadState('load');
const heldSearch = await holdSearchRequests(page);
const searchInput = page.getByTestId('search-input');
await searchInput.pressSequentially('files');
const search = await heldSearch('files');
await searchInput.press('Enter');
await page.waitForTimeout(1000);
await expect(searchInput).toBeFocused();
await expect(page.getByTestId('embed-docs-page')).toHaveCount(0);
const topResult = await answerSearch(search);
await expect(
page.getByRole('heading', { level: 1, name: topResult.title, exact: true })
).toBeVisible({ timeout: 20000 });
},
},
],
},
];
runTestCases(testCases);
test('Docs Embed inherits the site questions unless the host supplies questions', async ({
page,
}) => {
const docsURL = 'https://gitbook.com/docs/';
const { apiToken, organization, site, siteSpace } = await getSiteAPIToken(docsURL);
const api = new GitBookAPI({ endpoint: 'https://api.gitbook.com/cache', authToken: apiToken });
const { data } = await api.orgs.getPublishedContentSite(organization, site, {});
const customization = data.customizations.siteSpaces[siteSpace] ?? data.customizations.site;
const siteQuestions = [...new Set(customization.ai?.suggestions)];
expect(siteQuestions.length).toBeGreaterThan(0);
const hostURL = getContentTestURL(new URL('~gitbook/embed/demo/', docsURL).href);
const loaderURL = getContentTestURL(new URL('~gitbook/embed/script.js', docsURL).href);
const hostQuestions = ['Where should I start?'];
await page.route(hostURL, (route) =>
route.fulfill({
contentType: 'text/html',
body: `<!doctype html>
<button id="override">Use host questions</button>
<script src="${loaderURL}"></script>
<script>
GitBook('configure', {
tabs: ['assistant'],
assistantName: 'Docs Assistant',
suggestions: [],
});
GitBook('open');
document.getElementById('override').onclick = () => {
GitBook('configure', { suggestions: ${JSON.stringify(hostQuestions)} });
};
</script>`,
})
);
await page.goto(hostURL, { waitUntil: 'domcontentloaded' });
const frame = page.frameLocator('#gitbook-widget-iframe');
await expect(frame.getByText('Docs Assistant', { exact: true })).toBeVisible();
const questions = frame.getByTestId('ai-chat-suggested-question');
await expect(questions).toHaveText(siteQuestions);
await page.getByRole('button', { name: 'Use host questions' }).click();
await expect(questions).toHaveText(hostQuestions);
});
+3 -3
View File
@@ -59,7 +59,6 @@
"openapi-types": "^12.1.3",
"p-map": "^7.0.3",
"p-retry": "^8.0.0",
"parse5": "7.2.0",
"quick-lru": "^7.0.1",
"react": "19.2.4",
"react-dom": "19.2.4",
@@ -89,6 +88,7 @@
"devDependencies": {
"@argos-ci/playwright": "^7.2.0",
"@playwright/test": "^1.61.1",
"@scalar/api-client-react": "catalog:",
"@tailwindcss/postcss": "^4.1.11",
"@types/js-cookie": "^3.0.6",
"@types/jsontoxml": "^1.0.5",
@@ -118,9 +118,9 @@
},
"scripts": {
"generate": "./scripts/generate.sh",
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:fonts": "bun ./scripts/generate-font-faces.ts",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/fonts",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts",
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
"build": "bun run generate:assets && next build --webpack",
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
@@ -0,0 +1,81 @@
import { build } from 'bun';
import { mkdir, rename, rm } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { SCALAR_RUNTIME_PATH } from '../src/components/DocumentView/OpenAPI/scalar-runtime-path';
const scriptDir = dirname(fileURLToPath(import.meta.url));
const outputDir = join(scriptDir, '../public/~gitbook/static/scalar');
const temporaryDir = join(outputDir, '.build');
const scalarPackage = createRequire(import.meta.url)('@scalar/api-client-react/package.json') as {
version: string;
};
if (SCALAR_RUNTIME_PATH !== `scalar/scalar-api-client@${scalarPackage.version}.mjs`) {
throw new Error(
'Update SCALAR_RUNTIME_PATH for the installed @scalar/api-client-react version'
);
}
const reactShim = `
const react = () => globalThis.__gitbookScalarReact;
export const createContext = (...args) => react().createContext(...args);
export const useContext = (...args) => react().useContext(...args);
export const useEffect = (...args) => react().useEffect(...args);
export const useRef = (...args) => react().useRef(...args);
export const useSyncExternalStore = (...args) => react().useSyncExternalStore(...args);
`;
const jsxRuntimeShim = `
const runtime = () => globalThis.__gitbookScalarJSXRuntime;
export const jsx = (...args) => runtime().jsx(...args);
export const jsxs = (...args) => runtime().jsxs(...args);
`;
await rm(outputDir, { force: true, recursive: true });
await mkdir(temporaryDir, { recursive: true });
const result = await build({
entrypoints: [join(scriptDir, 'scalar-runtime.ts')],
format: 'esm',
minify: true,
outdir: temporaryDir,
plugins: [
{
name: 'scalar-react-shims',
setup(build) {
build.onResolve({ filter: /^react$/ }, () => ({
namespace: 'scalar-runtime',
path: 'react',
}));
build.onResolve({ filter: /^react\/jsx-runtime$/ }, () => ({
namespace: 'scalar-runtime',
path: 'react-jsx-runtime',
}));
build.onLoad({ filter: /^react$/, namespace: 'scalar-runtime' }, () => ({
contents: reactShim,
loader: 'js',
}));
build.onLoad(
{ filter: /^react-jsx-runtime$/, namespace: 'scalar-runtime' },
() => ({
contents: jsxRuntimeShim,
loader: 'js',
})
);
},
},
],
target: 'browser',
});
const [output] = result.outputs;
if (!result.success || !output || result.outputs.length !== 1) {
throw new Error(`Unable to build Scalar runtime: ${result.logs.join('\n')}`);
}
const outputPath = join(outputDir, SCALAR_RUNTIME_PATH.replace('scalar/', ''));
await rename(output.path, outputPath);
await rm(temporaryDir, { force: true, recursive: true });
@@ -0,0 +1 @@
export { ApiClientModalProvider, useApiClientModal } from '@scalar/api-client-react';
@@ -1,18 +1,16 @@
import { type NextRequest, NextResponse } from 'next/server';
import { SEARCH_FALLBACK_HEADER } from '@/components/Search/search-pass-store';
import type { SearchSiteContentRequest } from '@/components/Search/search-types';
import { orderSearchResultGroups } from './orderSearchResults';
import type {
OrderedComputedResult,
SearchSiteContentRequest,
} from '@/components/Search/search-types';
import { throwIfDataError } from '@/lib/data';
import { getLogger } from '@/lib/logger';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { transformSitePageResult } from '@/lib/search';
import { computeSearchResults } from '@/lib/search-results';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
const SEARCH_FALLBACK_REASON =
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
const [context, siteURLData] = await Promise.all([
@@ -20,15 +18,6 @@ export async function POST(request: NextRequest) {
getSiteURLDataFromMiddleware(),
]);
const fallback = request.headers.get(SEARCH_FALLBACK_HEADER);
if (fallback && SEARCH_FALLBACK_REASON.test(fallback)) {
getLogger()
.subLogger('search')
.info(
`Search pass fallback to the route (reason=${fallback}, organization=${siteURLData.organization}, site=${siteURLData.site})`
);
}
if (query.length <= 1) {
return NextResponse.json([]);
}
@@ -67,24 +56,49 @@ export async function POST(request: NextRequest) {
? getLinkerForSiteSpace(context.linker, currentSiteSpace.siteSpace, revision.pages)
: context.linker;
const results = computeSearchResults(searchResults, (spaceItem, pageItem) => {
const isCurrentRevisionSpace = Boolean(revision && spaceItem.id === siteURLData.space);
const found =
isCurrentRevisionSpace && currentSiteSpace
? currentSiteSpace
: findSiteSpaceBy(structure, (siteSpace) => siteSpace.space.id === spaceItem.id);
const results = orderSearchResultGroups<OrderedComputedResult>(
searchResults.map((resultItem) => {
if (resultItem.type === 'record') {
const result: OrderedComputedResult = {
type: 'record',
id: resultItem.id,
title: resultItem.title,
description: resultItem.description,
href: resultItem.url,
score: resultItem.score,
};
return transformSitePageResult({
asEmbeddable: Boolean(asEmbeddable),
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
pageItem,
spaceItem,
siteSpace: found?.siteSpace,
siteSection: found?.siteSection ?? undefined,
siteSectionGroup: found?.siteSectionGroup ?? undefined,
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
});
});
return { type: 'context' as const, results: [result] };
}
const isCurrentRevisionSpace = Boolean(revision && resultItem.id === siteURLData.space);
const found =
isCurrentRevisionSpace && currentSiteSpace
? currentSiteSpace
: findSiteSpaceBy(
structure,
(siteSpace) => siteSpace.space.id === resultItem.id
);
return {
type: 'pages' as const,
results: resultItem.pages.flatMap((pageItem) => {
const result = transformSitePageResult({
asEmbeddable: Boolean(asEmbeddable),
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
pageItem,
spaceItem: resultItem,
siteSpace: found?.siteSpace,
siteSection: found?.siteSection ?? undefined,
siteSectionGroup: found?.siteSectionGroup ?? undefined,
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
});
return result ? [{ rank: pageItem.rank, result }] : [];
}),
};
})
);
return NextResponse.json(results);
}
@@ -0,0 +1,13 @@
import type { NextRequest } from 'next/server';
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils';
import { serveLLMsTxt } from '@/routes/llms';
export const dynamic = 'force-static';
export async function GET(_request: NextRequest, { params }: { params: Promise<RouteParams> }) {
const { context } = await getStaticSiteContext(await params);
const pathname = getPagePathFromParams(await params);
return serveLLMsTxt(context, pathname);
}
@@ -1,14 +0,0 @@
import type { NextRequest } from 'next/server';
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
import { serveOpenSearchDescription } from '@/routes/opensearch';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const { context } = await getStaticSiteContext(await params);
return serveOpenSearchDescription(context);
}
@@ -65,7 +65,7 @@ export async function* streamAIChatResponse({
},
]
: [],
model: AIModel.ReasoningMedium,
model: AIModel.ReasoningLow,
previousResponseId,
toolCall,
tools,
@@ -180,11 +180,7 @@ function CodeBlockExpandable(props: {
<div
className={tcls(
!isExpanded
? [
'[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden',
// Mask the code rather than the pre to keep its border, with stops on the visible lines.
'[&_code]:mask-b-from-[calc((var(--line-count)+1)*var(--line-height)*0.55)] [&_code]:mask-b-to-[calc((var(--line-count)+1)*var(--line-height))]',
]
? '[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden'
: ''
)}
style={
@@ -127,7 +127,8 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
<code
className={tcls(
'table max-h-full w-fit min-w-full [counter-reset:line] print:max-h-none print:whitespace-pre-wrap',
withWrap && 'whitespace-pre-wrap'
withWrap && 'whitespace-pre-wrap',
'[[aria-expanded=false]_&]:mask-b-from-50%'
)}
>
{theme.lines.map((line, index) => (
@@ -40,12 +40,7 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
return (
<NotFoundRefHoverCard context={context}>
{fallback ? (
<InlineLinkAnchor
href={fallback.href}
contentRef={inline.data.ref}
target={inline.data.target}
isExternal
>
<InlineLinkAnchor href={fallback.href} contentRef={inline.data.ref} isExternal>
{inlinesElement}
</InlineLinkAnchor>
) : (
@@ -58,7 +53,6 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
<InlineLinkAnchor
href={resolved.href}
contentRef={resolved.resolvedRef ?? inline.data.ref}
target={inline.data.target}
isExternal={(resolved.resolvedRef ?? inline.data.ref).kind === 'url'}
>
{inlinesElement}
@@ -81,16 +75,14 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
function InlineLinkAnchor(props: {
href: string;
contentRef: ContentRef;
target: DocumentInlineLink['data']['target'];
isExternal?: boolean;
children: React.ReactNode;
}) {
const { href, isExternal, contentRef, target, children } = props;
const { href, isExternal, contentRef, children } = props;
const isMailto = href.startsWith('mailto:');
return (
<StyledLink
href={href}
target={target ? `_${target}` : undefined}
insights={{
type: 'link_click',
link: {
@@ -38,6 +38,7 @@ export type OpenAPIBlockClientContextProps = {
/** Rendered on the server: both go through the async document pipeline. */
headingNode: React.ReactNode;
descriptionNode: React.ReactNode;
scalarRuntimeURL: string;
};
type OpenAPIBlockVariant =
@@ -69,6 +70,7 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
renderDocument: () => descriptionNode,
renderHeading: () => headingNode,
resolveProxyUrl: proxyUrl ? () => proxyUrl : undefined,
scalarRuntimeURL: props.scalarRuntimeURL,
};
switch (props.variant) {
@@ -6,6 +6,7 @@ import {
type OpenAPISchemasData,
type OpenAPIWebhookData,
checkIsValidLocale,
extractOrigin,
getAllServerOrigins,
getOperationTitle,
getSchemasHeading,
@@ -16,7 +17,9 @@ import { PlainCodeBlock } from '../CodeBlock';
import { DocumentView } from '../DocumentView';
import { Heading } from '../Heading';
import type { OpenAPIBlockClientContextProps } from './OpenAPIBlockClient';
import { SCALAR_RUNTIME_PATH } from './scalar-runtime-path';
import { DEFAULT_LOCALE, getSpaceLocale } from '@/intl/server';
import { getAssetURL } from '@/lib/assets';
import type { GitBookAnyContext } from '@/lib/context';
import { GITBOOK_URL } from '@/lib/env';
import { buildSignedProxyUrl } from '@/lib/openapi/proxy-token';
@@ -121,6 +124,7 @@ export function getOpenAPIContext(args: {
expandAllResponses: expandAllResponses || props.context.mode === 'print',
expandAllModelSections: expandAllModelSections || props.context.mode === 'print',
headless,
scalarRuntimeURL: getAssetURL(SCALAR_RUNTIME_PATH),
id: block.meta?.id,
blockKey: block.key,
locale,
@@ -141,7 +145,7 @@ export function getOpenAPIBlockClientProps(args: {
expandAllModelSections?: boolean;
headless?: boolean;
}): OpenAPIBlockClientContextProps {
const { props, data, schemas, context } = args;
const { props, data, schemas, specUrl, context } = args;
const serverContext = getOpenAPIContext(args);
const { renderCodeBlock, renderDocument, renderHeading, resolveProxyUrl, ...serializable } =
serverContext;
@@ -154,6 +158,10 @@ export function getOpenAPIBlockClientProps(args: {
const descriptionDocument = data?.operation['x-gitbook-description-document'];
const origins = data ? getAllServerOrigins(data.servers) : [];
const specOrigin = specUrl ? extractOrigin(specUrl) : null;
if (specOrigin) {
origins.push(specOrigin);
}
return {
...serializable,
@@ -0,0 +1 @@
export const SCALAR_RUNTIME_PATH = 'scalar/scalar-api-client@1.3.46.mjs';
@@ -0,0 +1,360 @@
/* The vendor stylesheet is imported by ScalarApiModal so it ships with the lazy client chunk:
its `group-has-*` rules make every DOM change restyle the whole document. */
@reference "../../RootLayout/globals.css";
html,
body {
/** Override Scalar's overscroll-behavior */
@apply !overscroll-auto;
}
.light .scalar-modal-layout,
.light .scalar-app,
.light .scalar {
--scalar-color-1: color-mix(
in srgb,
rgb(var(--tint-color-300, 180 180 180)),
rgb(var(--tint-12, 23 23 23)) 96%
);
--scalar-color-2: color-mix(
in srgb,
var(--scalar-color-1),
transparent calc(100% - 100% * 0.72)
);
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
--scalar-color-accent: #007d9c;
--scalar-background-1: rgb(var(--tint-1, 255 255 255));
--scalar-background-2: color-mix(
in srgb,
rgb(var(--tint-color-800, 30 30 30)),
var(--scalar-background-1) 96%
);
--scalar-background-3: color-mix(
in srgb,
rgb(var(--tint-color-800, 30 30 30)),
var(--scalar-background-1) 90%
);
--scalar-background-accent: #007d9c1f;
--scalar-code-language-color-supersede: var(--scalar-color-1);
--scalar-code-languages-background-supersede: var(--scalar-background-1);
--scalar-border-color: color-mix(
in srgb,
var(--scalar-color-1),
transparent calc(100% - 100% * 0.08)
);
--scalar-color-green: #0a6355;
--scalar-color-red: #dc1b19;
--scalar-color-yellow: #ffc90d;
--scalar-color-blue: rgb(var(--primary-9, 52 109 219));
--scalar-color-orange: #ff8d4d;
--scalar-color-purple: #8250df;
--scalar-scrollbar-color: rgba(255, 255, 255, 0.24);
--scalar-scrollbar-color-active: rgba(255, 255, 255, 0.48);
--scalar-button-1: rgb(49 53 56);
--scalar-button-1-color: #fff;
--scalar-button-1-hover: rgb(28 31 33);
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
#eeeeed 0px 0 0 1px;
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--tint-12, 22 22 22));
}
.dark .scalar-modal-layout,
.dark .scalar-app,
.dark .scalar {
--scalar-color-1: color-mix(
in srgb,
rgb(var(--tint-color-700, 70 70 70)),
rgb(var(--tint-12, 255 255 255)) 100%
);
--scalar-color-2: color-mix(
in srgb,
var(--scalar-color-1),
transparent calc(100% - 100% * 0.64)
);
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
--scalar-color-accent: #50b7e0;
--scalar-background-1: rgb(var(--tint-1, 22 22 22));
--scalar-background-2: color-mix(
in srgb,
rgb(var(--tint-color-200, 200 200 200)),
var(--scalar-background-1) 92%
);
--scalar-background-3: color-mix(
in srgb,
rgb(var(--tint-color-200, 200 200 200)),
var(--scalar-background-1) 88%
);
--scalar-background-accent: #8ab4f81f;
--scalar-code-languages-background-supersede: var(--scalar-background-1);
--scalar-border-color: color-mix(
in srgb,
var(--scalar-color-1),
transparent calc(100% - 100% * 0.08)
);
--scalar-color-green: #56b6c2;
--scalar-color-red: rgb(245 124 97);
--scalar-color-yellow: #edbe20;
--scalar-color-blue: rgb(var(--primary-9, 93 138 226));
--scalar-color-orange: #d19a66;
--scalar-color-purple: #5203d1;
--scalar-scrollbar-color: rgba(0, 0, 0, 0.18);
--scalar-scrollbar-color-active: rgba(0, 0, 0, 0.36);
--scalar-button-1: #f6f6f6;
--scalar-button-1-color: #000;
--scalar-button-1-hover: #e7e7e7;
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px, 0 0 0
1px rgba(255, 255, 255, 0.1);
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--tint-12, 255 255 255));
}
.scalar-modal-layout,
.scalar-app,
.scalar {
--scalar-font: initial;
--scalar-font-code: var(--font-mono);
--scalar-paragraph: 16px;
--scalar-small: 14px;
--scalar-mini: 13px;
--scalar-micro: 12px;
--scalar-bold: 600;
--scalar-semibold: 500;
--scalar-regular: 400;
/* Font sizes for interactive applications (not rendered text content) */
--scalar-font-size-1: 24px;
--scalar-font-size-2: 16px;
--scalar-font-size-3: 14px;
--scalar-font-size-4: 13px;
--scalar-font-size-5: 12px;
--scalar-line-height-1: 32px;
--scalar-line-height-2: 24px;
--scalar-line-height-3: 20px;
--scalar-line-height-4: 18px;
--scalar-line-height-5: 16px;
--scalar-app-header-height: 35px;
}
.scalar input::placeholder {
color: var(--scalar-color-3);
}
.scalar .scalar-app-header {
width: 100%;
z-index: 1000;
padding: 6px 12px 6px 12px;
border-radius: 0.25rem 0.25rem 0 0;
font-size: 14px;
height: var(--scalar-app-header-height);
display: flex;
align-items: center;
flex-shrink: 0;
gap: 6px;
}
.scalar .scalar-api-client {
max-height: calc(100dvh - (100px + var(--scalar-app-header-height))) !important;
border-radius: 8px;
}
.scalar-api-client__close {
appearance: none;
border: none;
outline: none;
display: flex;
align-items: center;
background: transparent;
color: var(--scalar-color-1);
font-size: var(--scalar-small);
font-weight: var(--scalar-semibold);
}
.scalar-api-client__close:hover {
cursor: pointer;
}
.scalar .scalar-app-layout {
background: var(--scalar-background-3);
height: calc(100dvh - 100px);
max-width: 1280px;
width: 100%;
margin: auto;
opacity: 0;
animation: scalarapiclientfadein 0.35s forwards;
z-index: 1002;
position: relative;
overflow: hidden;
border-radius: 8px;
display: flex;
flex-direction: column;
}
@keyframes scalarapiclientfadein {
from {
transform: translate3d(0, 20px, 0) scale(0.985);
opacity: 0;
}
to {
transform: translate3d(0, 0, 0) scale(1);
opacity: 1;
}
}
.scalar .scalar-app-exit {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.62);
transition: all 0.3s ease-in-out;
z-index: 1000;
cursor: pointer;
animation: scalardrawerexitfadein 0.35s forwards;
}
@keyframes scalardrawerexitfadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.scalar-container {
overflow: hidden;
visibility: visible;
position: fixed;
bottom: 0;
left: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1001;
display: flex;
align-items: center;
justify-content: center;
}
.scalar .url-form-input {
min-height: auto !important;
}
.scalar .scalar-container {
line-height: normal;
}
.scalar .scalar-app-header span {
color: var(--scalar-color-3);
}
.scalar .scalar-app-header a {
color: var(--scalar-color-1);
}
.scalar .scalar-app-header a:hover {
text-decoration: underline;
}
.scalar-activate {
width: fit-content;
line-height: 24px;
font-size: 0.75rem;
cursor: pointer;
font-size: 0.875rem;
display: flex;
align-items: center;
gap: 6px;
}
.scalar-activate-button {
@apply flex gap-2 items-center;
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
@apply grow-0 shrink-0 truncate;
@apply text-[13px] px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
}
.scalar-activate-button svg {
@apply size-2.5;
}
/* Same size as the play icon it replaces, so the button doesn't shift while loading. */
.scalar-activate-button .scalar-activate-spinner {
@apply animate-spin motion-reduce:animate-none;
}
.scalar-app-loading {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.scalar .request-method {
white-space: nowrap;
}
/* Use :where to lower specificity to 0 */
.scalar .custom-scroll {
overflow-y: auto;
scrollbar-color: transparent transparent;
scrollbar-width: thin;
-webkit-overflow-scrolling: touch;
}
.scalar .custom-scroll:hover {
scrollbar-color: rgba(0, 0, 0, 0.24) transparent;
}
.dark .scalar .custom-scroll:hover {
scrollbar-color: rgba(255, 255, 255, 0.24) transparent;
}
.scalar .custom-scroll:hover::-webkit-scrollbar-thumb {
background: var(--scalar-scrollbar-color, var(--default-theme-scrollbar-color));
background-clip: content-box;
border: 3px solid transparent;
}
.scalar .custom-scroll::-webkit-scrollbar-thumb:active {
background: var(--scalar-scrollbar-color-active, var(--default-theme-scrollbar-color-active));
background-clip: content-box;
border: 3px solid transparent;
}
.scalar .custom-scroll::-webkit-scrollbar-corner {
background: transparent;
}
.scalar .custom-scroll::-webkit-scrollbar {
height: 12px;
width: 12px;
}
.scalar .custom-scroll::-webkit-scrollbar-track {
background: transparent;
}
.scalar .custom-scroll::-webkit-scrollbar-thumb {
border-radius: 20px;
background: transparent;
background-clip: content-box;
border: 3px solid transparent;
}
@media (pointer: coarse) {
.scalar .custom-scroll {
padding-right: 12px;
}
}
.dark .scalar .client-wrapper-bg-color {
background: linear-gradient(
color-mix(in srgb, var(--tw-bg-base) 6%, transparent) 1%,
color-mix(in srgb, var(--scalar-background-1) 30%, black) 9%
);
}
.light .scalar .client-wrapper-bg-color {
background-color: var(--scalar-background-2) !important;
}
.scalar .gitbook-show {
display: block !important;
}
.scalar .gitbook-hidden {
display: none !important;
}
@@ -1,5 +1,5 @@
@reference "../../RootLayout/globals.css";
@import './tryit.css';
@import './scalar.css';
/* Layout Components */
.openapi-operation,
@@ -1,244 +0,0 @@
@reference "../../RootLayout/globals.css";
.openapi-tryit-activate {
@apply flex items-center w-fit;
}
.openapi-tryit-button {
@apply flex gap-2 items-center cursor-pointer;
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover contrast-more:ring-1 rounded-lg straight-corners:rounded-none circular-corners:rounded-full circular-corners:px-3 place-self-start;
@apply depth-subtle:shadow-xs hover:depth-subtle:shadow-md focus-visible:depth-subtle:shadow-md active:depth-subtle:shadow-xs;
@apply contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12;
@apply hover:depth-subtle:-translate-y-px focus-visible:depth-subtle:-translate-y-px active:depth-subtle:translate-y-0 transition-all;
@apply grow-0 shrink-0 truncate;
@apply text-[13px] leading-6 px-2 py-0.5 font-mono font-medium [word-spacing:-2px];
}
.openapi-tryit-button svg {
@apply size-2.5;
}
.openapi-tryit-button-spinner {
@apply animate-spin motion-reduce:animate-none;
}
/* Dialog */
.openapi-tryit {
@apply m-auto p-0 w-[min(72rem,calc(100vw-2rem))] h-[min(48rem,calc(100dvh-2rem))] max-w-none max-h-none;
@apply bg-tint-base text-tint border border-tint-subtle shadow-2xl overflow-hidden;
@apply rounded-xl straight-corners:rounded-none circular-corners:rounded-2xl;
}
.openapi-tryit::backdrop {
@apply bg-tint-12/40 backdrop-blur-xs;
}
.openapi-tryit-layout {
@apply flex flex-col h-full;
}
.openapi-tryit-header {
@apply flex items-center gap-3 px-4 py-3 border-b border-tint-subtle;
}
.openapi-tryit-url {
@apply flex-1 min-w-0 truncate font-mono text-sm text-tint-strong;
}
.openapi-tryit-url-server {
@apply text-tint;
}
.openapi-tryit-send {
@apply shrink-0 cursor-pointer px-3 py-1 text-sm font-medium;
@apply bg-primary-original text-contrast-primary-original hover:bg-primary-solid-hover hover:text-contrast-primary-solid-hover;
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full transition-colors;
}
.openapi-tryit-close {
@apply shrink-0 cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
}
.openapi-tryit-close svg {
@apply size-4;
}
.openapi-tryit-body {
@apply flex-1 min-h-0 grid grid-cols-1 md:grid-cols-2 overflow-y-auto md:overflow-hidden;
}
.openapi-tryit-request {
@apply flex flex-col gap-5 p-4 md:overflow-y-auto border-b md:border-b-0 md:border-r border-tint-subtle;
}
.openapi-tryit-section {
@apply flex flex-col gap-2.5;
}
.openapi-tryit-section-header {
@apply flex items-center justify-between gap-3;
}
.openapi-tryit-section-title {
@apply text-xs font-semibold uppercase tracking-wide text-tint-strong;
}
.openapi-tryit-field {
@apply flex flex-col gap-1;
}
.openapi-tryit-field-label {
@apply flex flex-wrap items-baseline gap-x-1.5 text-[0.813rem];
}
.openapi-tryit-field-name {
@apply font-mono text-tint-strong;
}
.openapi-tryit-field-required {
@apply text-danger;
}
.openapi-tryit-field-description {
@apply text-xs text-tint line-clamp-2 basis-full;
}
.openapi-tryit-input {
@apply w-full min-w-0 px-2.5 py-1.5 text-sm font-mono bg-tint-base text-tint-strong border border-tint-subtle placeholder:text-tint/60;
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
@apply outline-none focus:border-primary focus:ring-2 focus:ring-primary/20;
}
.openapi-tryit-input-small {
@apply w-auto py-1 text-xs;
}
.openapi-tryit-code {
@apply resize-y leading-5 whitespace-pre;
}
.openapi-tryit-invalid {
@apply border-danger;
}
.openapi-tryit-file {
@apply text-sm text-tint file:mr-3 file:px-2.5 file:py-1 file:border file:border-tint-subtle file:bg-tint file:text-tint-strong file:rounded-md file:cursor-pointer;
}
.openapi-tryit-auth {
@apply grid grid-cols-1 sm:grid-cols-2 gap-2.5;
}
.openapi-tryit-hint {
@apply text-xs text-tint;
}
.openapi-tryit-alert {
@apply text-sm px-3 py-2 bg-danger text-danger border border-danger-subtle rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
}
.openapi-tryit-table {
@apply flex flex-col border border-tint-subtle divide-y divide-tint-subtle;
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
}
.openapi-tryit-table:empty {
@apply hidden;
}
/* Checkbox · name · value · remove, as a row of a key/value table. */
.openapi-tryit-row {
@apply grid grid-cols-[auto_minmax(0,1fr)_minmax(0,1.3fr)_1.75rem] gap-x-2 items-center px-2 py-1.5;
}
.openapi-tryit-row .openapi-tryit-input {
@apply py-1 text-[0.813rem];
}
.openapi-tryit-row .openapi-tryit-field-label {
@apply min-w-0;
}
.openapi-tryit-row .openapi-tryit-field-name {
@apply truncate;
}
.openapi-tryit-check {
@apply size-3.5 cursor-pointer disabled:cursor-default disabled:opacity-60;
accent-color: rgb(var(--primary-9, 52 109 219));
}
.openapi-tryit-row-remove {
@apply cursor-pointer p-1.5 text-tint hover:text-tint-strong hover:bg-tint-hover rounded-md straight-corners:rounded-none circular-corners:rounded-full;
}
.openapi-tryit-row-remove svg {
@apply size-3.5;
}
.openapi-tryit-add {
@apply self-start cursor-pointer px-2.5 py-1 text-xs text-tint-strong border border-dashed border-tint-subtle hover:bg-tint-hover;
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-full;
}
/* Response */
.openapi-tryit-response {
@apply flex flex-col gap-3 p-4 min-h-48 md:overflow-y-auto bg-tint-subtle;
}
.openapi-tryit-response-empty {
@apply items-center justify-center text-sm text-tint;
}
.openapi-tryit-spinner {
@apply size-5 rounded-full border-2 border-tint-subtle border-t-primary animate-spin motion-reduce:animate-none;
}
.openapi-tryit-response-meta {
@apply flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-tint font-mono;
}
.openapi-tryit-tabs {
@apply ml-auto flex gap-1;
}
.openapi-tryit-tab {
@apply cursor-pointer px-2 py-1 text-xs rounded-md straight-corners:rounded-none circular-corners:rounded-full text-tint hover:text-tint-strong;
}
.openapi-tryit-tab[aria-selected='true'] {
@apply bg-tint-active text-tint-strong;
}
.openapi-tryit-response-body {
@apply m-0 p-3 text-xs leading-5 font-mono whitespace-pre-wrap break-all text-tint-strong bg-tint-base border border-tint-subtle;
@apply rounded-md straight-corners:rounded-none circular-corners:rounded-lg;
}
.openapi-tryit-headers {
@apply m-0 flex flex-col text-xs font-mono;
}
.openapi-tryit-headers > div {
@apply grid grid-cols-[minmax(8rem,auto)_1fr] gap-3 py-1.5 border-b border-tint-subtle;
}
.openapi-tryit-headers dt {
@apply text-tint-strong;
}
.openapi-tryit-headers dd {
@apply m-0 text-tint break-all;
}
.openapi-tryit-binary {
@apply flex flex-col gap-3 text-sm;
}
.openapi-tryit-binary img {
@apply max-w-full max-h-96 self-start border border-tint-subtle;
}
.openapi-tryit-binary a {
@apply text-primary underline;
}
@@ -12,13 +12,7 @@ mock.module('./RecordCard', () => ({
}));
mock.module('./TableSearch', () => ({
TableSearchRecord: ({
children,
visibleClassName,
}: {
children: React.ReactNode;
visibleClassName: string;
}) => <div className={visibleClassName}>{children}</div>,
TableSearchRecord: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const { ViewCards } = await import('./ViewCards');
@@ -62,38 +56,9 @@ describe('ViewCards', () => {
expect(markup).toContain('snap-mandatory');
});
it.each([true, undefined])('renders the wrapping grid with wrap=%s', (wrap) => {
const props = makeProps(true);
props.view.wrap = wrap;
const markup = renderWithContext(<ViewCards {...props} />);
it('renders the wrapping grid by default', () => {
const markup = renderWithContext(<ViewCards {...makeProps(true)} />);
expect(markup).toContain('inline-grid');
});
it('renders small cards in four columns and uses the grid for print', () => {
const props = makeProps(true);
props.view.cardSize = 'small';
expect(renderWithContext(<ViewCards {...props} />)).toContain('@3xl:grid-cols-4');
props.view.wrap = false;
const carousel = renderWithContext(<ViewCards {...props} />);
expect(carousel).toContain('@3xl:w-[calc(22.5%-0.75rem)]');
expect(carousel).toContain('@5xl:w-[calc(25%-0.75rem)]');
props.context.mode = 'print';
const printed = renderWithContext(<ViewCards {...props} />);
expect(printed).toContain('@3xl:grid-cols-4');
expect(printed).not.toContain('snap-mandatory');
});
it.each([
['medium', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
['large', '@xl:grid-cols-2', '@5xl:w-[calc(50%-0.5rem)]'],
['unknown', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
])('preserves %s card layouts', (cardSize, grid, carousel) => {
const props = makeProps(true);
props.view.cardSize = cardSize;
expect(renderWithContext(<ViewCards {...props} />)).toContain(grid);
props.view.wrap = false;
expect(renderWithContext(<ViewCards {...props} />)).toContain(carousel);
});
});
@@ -6,18 +6,6 @@ import { TableSearchRecord } from './TableSearch';
import { ScrollContainer } from '@/components/primitives/ScrollContainer';
import { tcls } from '@/lib/tailwind';
const gridColumns = {
small: '@sm:grid-cols-2 @2xl:grid-cols-3 @3xl:grid-cols-4',
medium: '@2xl:grid-cols-3 @sm:grid-cols-2',
large: '@xl:grid-cols-2',
};
const carouselWidths = {
small: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @3xl:w-[calc(22.5%-0.75rem)] @5xl:w-[calc(25%-0.75rem)]',
medium: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]',
large: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]',
};
export function ViewCards(props: TableViewProps<DocumentTableViewCards>) {
// `wrap` defaults to `true` (a wrapping grid); only an explicit `false` opts into the
// horizontally-scrolling carousel row. Fall back to the grid in print mode: a PDF can't
@@ -42,7 +30,7 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
'inline-grid',
'gap-4',
'grid-cols-1',
gridColumns[view.cardSize] ?? gridColumns.medium,
view.cardSize === 'large' ? '@xl:grid-cols-2' : '@2xl:grid-cols-3 @sm:grid-cols-2', // Large cards break earlier to avoid becoming *too* big.
block.data.fullWidth ? 'large:flex-column' : null
)}
>
@@ -82,6 +70,13 @@ const PEEK = {
function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
const { view, records } = props;
// Cards need a fixed width so the row overflows and scrolls; mirror the grid's
// medium/large sizing.
const cardWidth =
view.cardSize === 'large'
? 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]'
: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]';
return (
<ScrollContainer
orientation="horizontal"
@@ -120,7 +115,7 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
'grid-cols-1',
'shrink-0',
'snap-start',
carouselWidths[view.cardSize] ?? carouselWidths.medium
cardWidth
)}
>
<RecordCard {...props} record={record} />
@@ -18,7 +18,7 @@ export function EmbeddableAIContextProvider(props: EmbeddableAIContextProviderPr
return (
<AIContextProvider
aiMode={aiMode}
suggestions={embedConfig.suggestions?.length ? embedConfig.suggestions : suggestions}
suggestions={embedConfig.suggestions ?? suggestions}
greeting={embedConfig.greeting ?? greeting}
trademark={trademark && (embedConfig.trademark ?? true)}
assistantName={embedConfig.assistantName?.substring(0, 32)} // Limit to 32 characters
@@ -5,11 +5,7 @@ import React, { useEffect, useRef } from 'react';
import { createStore, useStore } from 'zustand';
import type { GitBookIntegrationTool } from '@gitbook/browser-types';
import type {
FrameToParentMessage,
GitBookEmbeddableConfiguration,
ParentToFrameMessage,
} from '@gitbook/embed';
import type { GitBookEmbeddableConfiguration, ParentToFrameMessage } from '@gitbook/embed';
import { integrationsAssistantTools } from '../Integrations';
import { Button, LinkContext, type LinkContextType } from '../primitives';
@@ -24,6 +20,7 @@ const embeddableConfiguration = createStore<GitBookEmbeddableConfiguration>(() =
tabs: [],
actions: [],
greeting: { title: '', subtitle: '' },
suggestions: [],
tools: [],
trademark: true,
}));
@@ -72,27 +69,6 @@ export function EmbeddableIframeAPI(props: { baseURL: string }) {
});
}, [chatController]);
React.useEffect(() => {
const channel = getChannel();
if (!channel) {
return;
}
// Menus, dialogs and the zoomed image call preventDefault when Escape closes them.
const onKeyDown = (event: KeyboardEvent) => {
if (
event.key === 'Escape' &&
!event.defaultPrevented &&
!event.isComposing &&
!event.repeat
) {
channel.send({ type: 'escape' } satisfies FrameToParentMessage);
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, []);
React.useEffect(() => {
const channel = getChannel();
if (!channel) {
@@ -12,7 +12,6 @@ import { EmbeddableIframeAPI } from './EmbeddableIframeAPI';
import { EmbeddableThemeSync } from './EmbeddableThemeSync';
import { IfEmbeddableTrademark } from './EmbeddableTrademark';
import { CustomizationRootLayout } from '@/components/RootLayout';
import { getDirectSearchProps } from '@/components/Search/search-props';
import {
SiteLayoutClientContexts,
generateSiteLayoutMetadata,
@@ -61,7 +60,6 @@ export async function EmbeddableRootLayout({
contextId={context.contextId}
proxyOrigin={context.site.proxy?.origin}
searchPrewarmURL={context.linker.toPathInSite('~gitbook/search-prewarm')}
directSearch={getDirectSearchProps(context)}
>
{/* Persist an explicit ?theme= override so it survives tab navigation. RND-11571 */}
<EmbeddableThemeSync forcedTheme={rememberedTheme} />
@@ -50,9 +50,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
error,
fetching,
onInputKeyDown,
inputHandlers,
onResultSelect,
onResultHover,
query,
results,
resultsId,
@@ -81,7 +79,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
resultsId={resultsId}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
showAsk={showAsk}
dataTestId="embed-search"
input={
@@ -92,7 +89,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
aria-controls={resultsId}
onChange={setQuery}
onKeyDown={onInputKeyDown}
{...inputHandlers}
value={searchValue}
withAI={withSearchAI}
isOpen={true}
@@ -27,6 +27,7 @@ import {
hasTopLevelBlock,
isNodeEmpty,
} from '@/lib/document';
import { getLLMsTxtURL, getPageMarkdownURL } from '@/lib/llms-directive';
import type { AncestorRevisionPage } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
@@ -121,6 +122,7 @@ export async function PageBody(props: {
)}
>
<PreservePageLayout wideLayout={wideLayout} pageHasToc={pageHasToc} />
<LLMsTxtPageDirective context={context} page={page} />
{page.cover && page.layout.cover && page.layout.coverSize === 'hero' ? (
<PageCover as="hero" page={page} cover={page.cover} context={context} />
) : null}
@@ -205,3 +207,14 @@ export async function PageBody(props: {
</CurrentPageProvider>
);
}
function LLMsTxtPageDirective(props: { context: GitBookSiteContext; page: RevisionPageDocument }) {
const { context, page } = props;
return (
<div className="sr-only">
For the complete documentation index, see <a href={getLLMsTxtURL(context)}>llms.txt</a>.
This page is also available as <a href={getPageMarkdownURL(context, page)}>Markdown</a>.
</div>
);
}
@@ -0,0 +1,96 @@
'use client';
import { Icon, type IconName } from '@gitbook/icons';
import { Emoji } from '../primitives/Emoji/Emoji';
import { Link } from '../primitives/Link';
import type { LocalPageResult } from './useLocalSearchResults';
import { tcls } from '@/lib/tailwind';
/**
* Renders local search results above the main server results.
*
* Layout:
* - While server results are still fetching → 2-column wrapping row (cards fill width)
* - Once server results are ready → single horizontal scrollable row (fixed-width cards)
*
* The card width is CSS-transitioned so the switch between the two layouts animates smoothly.
*/
export function LocalSearchResults({
results,
fetching,
}: {
results: LocalPageResult[];
fetching: boolean;
}) {
if (results.length === 0) return null;
return (
<div
className={tcls(
'py-2',
'flex',
'flex-row',
'gap-2',
fetching
? 'flex-wrap'
: ['overflow-x-auto', '[scrollbar-width:none]', '[&::-webkit-scrollbar]:hidden']
)}
>
{results.map((result) => (
<LocalSearchResultCard key={result.id} result={result} fetching={fetching} />
))}
</div>
);
}
function LocalSearchResultCard({
result,
fetching,
}: {
result: LocalPageResult;
fetching: boolean;
}) {
return (
<Link
href={result.pathname}
className={tcls(
'group',
'flex',
'flex-col',
'gap-1',
'p-3',
'rounded-corners:rounded-lg',
'circular-corners:rounded-2xl',
'text-tint',
'bg-tint-subtle',
'hover:bg-tint',
'hover:text-tint-strong',
'transition-colors',
'cursor-pointer',
fetching ? ['basis-[calc(50%-4px)]', 'min-w-0'] : ['w-40', 'shrink-0']
)}
>
<div className={tcls('flex', 'flex-row', 'items-center', 'gap-1.5', 'min-w-0')}>
{result.emoji ? (
<span className="size-4 shrink-0 text-tint-subtle">
<Emoji code={result.emoji} style="text-base leading-none" />
</span>
) : result.icon ? (
<span className="size-4 shrink-0 text-tint-subtle">
<Icon icon={result.icon as IconName} className="size-4" />
</span>
) : null}
<p className="grow truncate font-heading text-sm font-semibold leading-snug text-tint-strong">
{result.title}
</p>
<span className="ml-auto shrink-0 text-tint-subtle">
<Icon icon="chevron-right" className="size-3" />
</span>
</div>
{result.description ? (
<p className="line-clamp-2 text-xs leading-snug">{result.description}</p>
) : null}
</Link>
);
}
@@ -1,5 +1,6 @@
'use client';
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
import { addRecentSearchQuery } from './recent-queries';
import { SearchResultItem } from './SearchResultItem';
import { useSearchLink } from './useSearch';
@@ -15,10 +16,10 @@ export function SearchAskBar(props: {
query: string;
assistant: Assistant;
active?: boolean;
onHover?: () => void;
withShortcut?: boolean;
onSelect?: () => void;
}) {
const { query, assistant, active = false, onHover, onSelect } = props;
const { query, assistant, active = false, withShortcut = false, onSelect } = props;
const language = useLanguage();
const { siteSpaceId } = useCurrentContent();
const getSearchLinkProps = useSearchLink();
@@ -42,14 +43,18 @@ export function SearchAskBar(props: {
<SearchResultItem
{...linkProps}
active={active}
onHover={onHover}
action={tString(language, 'ask')}
leadingIcon={assistant.icon}
data-testid="search-ask-question"
className="gutter-stable rounded-none! shrink-0 overflow-y-scroll border-t border-tint-subtle pl-6 pr-5"
>
<div className="line-clamp-1">
{t(language, 'ai_chat_ask_query', assistant.label, query)}
<div className="flex items-center justify-between gap-2">
<div className="line-clamp-1">
{t(language, 'ai_chat_ask_query', assistant.label, query)}
</div>
{withShortcut ? (
<KeyboardShortcut className="bg-tint-base" keys={['mod', 'i']} />
) : null}
</div>
</SearchResultItem>
);
@@ -43,9 +43,6 @@ export function SearchContainer({
const [searchPopup, setSearchPopup] = React.useState<HTMLDivElement | null>(null);
const language = useLanguage();
const usesSideSheet = useIsMobile(768);
// The header and sidebar copies are shown and hidden by CSS at the `lg` breakpoint.
const belowLg = useIsMobile();
const visible = viewport === 'desktop' ? !belowLg : viewport === 'mobile' ? belowLg : true;
const {
assistants,
askQuery,
@@ -56,9 +53,7 @@ export function SearchContainer({
error,
fetching,
onInputKeyDown,
inputHandlers,
onResultSelect,
onResultHover,
open,
query,
results,
@@ -71,7 +66,7 @@ export function SearchContainer({
withAI,
withSearchAI,
scopeControl,
} = useSearchController(searchProps, { requestsEnabled: visible });
} = useSearchController(searchProps);
const uiAssistants = assistants.filter((assistant) => assistant.ui === true);
useHotkeys(
@@ -119,6 +114,8 @@ export function SearchContainer({
};
}, [close]);
const visible =
viewport === 'desktop' ? !usesSideSheet : viewport === 'mobile' ? usesSideSheet : true;
const searchResultsActiveDescendant =
cursor !== null && cursor < results.length ? `${resultsId}-${cursor}` : undefined;
const isSearchOpen = Boolean(visible && (state?.open ?? false));
@@ -152,7 +149,6 @@ export function SearchContainer({
aria-controls={resultsId}
onChange={setQuery}
onKeyDown={onInputKeyDown}
{...inputHandlers}
value={searchValue}
withAI={withSearchAI}
isOpen={isSearchOpen}
@@ -180,7 +176,6 @@ export function SearchContainer({
resultsId={resultsId}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
showAsk={showAsk}
scopeControl={scopeControlNode}
fillHeight={usesSideSheet || shouldFillHeight}
@@ -220,7 +215,6 @@ export function SearchContainer({
aria-controls={resultsId}
onChange={setQuery}
onKeyDown={onInputKeyDown}
{...inputHandlers}
value={searchValue}
withAI={withSearchAI}
isOpen={isSearchOpen}
@@ -9,6 +9,8 @@ import {
EmbeddableFrameMain,
EmbeddableFrameSidebar,
} from '../Embeddable/EmbeddableFrame';
import { Tooltip } from '../primitives';
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
import { ScrollContainer } from '../primitives/ScrollContainer';
import { SearchAskAnswer } from './SearchAskAnswer';
import { SearchAskBar } from './SearchAskBar';
@@ -29,8 +31,6 @@ export function SearchFrame(props: {
resultsId: string;
resultsRef: React.Ref<SearchResultsRef>;
onResultSelect?: () => void;
/** Select the result under the mouse, so hover and keyboard share one highlight. */
onResultHover?: (index: number) => void;
scopeControl?: React.ReactNode;
showAsk: boolean;
sidebar?: React.ReactNode;
@@ -52,7 +52,6 @@ export function SearchFrame(props: {
resultsId,
resultsRef,
onResultSelect,
onResultHover,
scopeControl,
showAsk,
sidebar,
@@ -100,16 +99,8 @@ export function SearchFrame(props: {
<ScrollContainer
orientation="vertical"
className={tcls(fillHeight ? 'min-h-0 flex-1' : '')}
leading={{ fade: 'long', button: false }}
trailing={{
fade: 'long',
button: true,
// Loading placeholders are not more results.
buttonAlwaysVisible: results.length > 0,
}}
contentClassName={tcls(
// Keeps the keyboard selection clear of the faded edges.
'gutter-stable scroll-pt-12 scroll-pb-24 p-3',
'gutter-stable scroll-py-3 p-3',
fillHeight ? 'min-h-full' : ''
)}
>
@@ -125,7 +116,6 @@ export function SearchFrame(props: {
cursor={cursor}
error={error}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
/>
)}
</ScrollContainer>
@@ -136,16 +126,21 @@ export function SearchFrame(props: {
query={query}
assistant={assistant}
active={cursor === results.length + index}
onHover={() => onResultHover?.(results.length + index)}
withShortcut={assistant === assistants[0]}
onSelect={onResultSelect}
/>
))
: null}
{scopeControl && !showAsk ? (
<div className="flex gap-2 border-t border-tint-subtle bg-tint-subtle px-4 py-1.5">
{scopeControl}
</div>
) : null}
<div
className={tcls(
'flex gap-2 border-tint-subtle border-t bg-tint-subtle px-4 py-1.5',
!scopeControl ? 'not-pointer-fine:hidden' : '',
showAsk ? 'hidden' : ''
)}
>
{scopeControl && !showAsk ? scopeControl : null}
<SearchFrameKeyboardHints />
</div>
</div>
</React.Suspense>
</EmbeddableFrameMain>
@@ -153,3 +148,31 @@ export function SearchFrame(props: {
</SearchAskProvider>
);
}
const SearchFrameKeyboardHints = () => {
return (
<div className="not-pointer-fine:hidden flex w-full items-center justify-end py-1.5 @container/keyboard-hint">
{/* Compact view */}
<div className="@max-[6rem]/keyboard-hint:hidden @min-[12rem]/keyboard-hint:hidden flex items-center gap-2">
<Tooltip label="Navigate">
<div>
<KeyboardShortcut className="bg-tint-base" keys={['up', 'down']} />
</div>
</Tooltip>
/
<Tooltip label="Close">
<div>
<KeyboardShortcut className="bg-tint-base" keys={['esc']} />
</div>
</Tooltip>
</div>
{/* Normal view */}
<div className="@max-[12rem]/keyboard-hint:hidden flex items-center gap-2">
<KeyboardShortcut className="bg-tint-base" keys={['up', 'down']} />
Navigate
<KeyboardShortcut className="ml-1 bg-tint-base" keys={['esc']} />
Close
</div>
</div>
);
};
@@ -13,8 +13,6 @@ interface SearchInputProps {
onChange: (value: string) => void;
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;
onFocus?: () => void;
onInput?: (event: React.FormEvent<HTMLInputElement>) => void;
onCompositionEnd?: (event: React.CompositionEvent<HTMLInputElement>) => void;
value: string;
withAI: boolean;
isOpen: boolean;
@@ -1,20 +1,25 @@
import React from 'react';
import { Icon } from '@gitbook/icons';
import { Icon, type IconName } from '@gitbook/icons';
import { useResizeObserver } from '../hooks';
import { SkeletonParagraph } from '../primitives';
import { Tooltip } from '../primitives';
import { Emoji } from '../primitives/Emoji/Emoji';
import { getPageResultPresentation } from './getPageResultHref';
import { HighlightQuery } from './HighlightQuery';
import type { MergedPageResult } from './reciprocalRankFusion';
import type { ComputedPageResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import type { LocalPageResult } from './useLocalSearchResults';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
type PageItem = ComputedPageResult | LocalPageResult | MergedPageResult;
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
props: {
query: string;
item: ComputedPageResult;
item: PageItem;
active: boolean;
style?: React.CSSProperties;
},
@@ -23,19 +28,46 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
const { preview: bestSection, description, href } = getPageResultPresentation(item);
const { bestSection, description, href } = (() => {
if (item.type === 'page') {
const presentation = getPageResultPresentation(item);
return {
bestSection: presentation.preview,
description: presentation.description,
href: presentation.href,
};
}
return { bestSection: undefined, description: item.description, href: item.pathname };
})();
const preview = bestSection
? [bestSection.title, bestSection.body].filter(Boolean).join(' · ')
: undefined;
const insights = {
type: 'search_open_result' as const,
query,
result: {
pageId: item.pageId,
spaceId: item.spaceId,
},
};
const emoji = 'emoji' in item ? item.emoji : undefined;
const icon = 'icon' in item ? item.icon : undefined;
const leadingIcon = emoji ? (
<span className="flex size-4 shrink-0 items-center justify-center">
<Emoji code={emoji} style="text-base leading-none" />
</span>
) : icon ? (
<Icon icon={icon as IconName} className="size-4" />
) : (
<Icon icon="file-lines" className="size-4" />
);
const insights =
item.type === 'page'
? {
type: 'search_open_result' as const,
query,
result: {
pageId: item.pageId,
spaceId: item.spaceId,
},
}
: undefined;
return (
<SearchResultItem
@@ -44,6 +76,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
active={active}
data-testid="search-page-result"
action={tString(language, 'view')}
leadingIcon={leadingIcon}
insights={insights}
aria-label={tString(language, 'search_page_result_title', item.title)}
style={{
@@ -58,7 +91,11 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
<div
className={tcls(
'relative h-5 w-full transition-[height] duration-300',
!preview && !description ? 'h-0' : ''
item.type === 'local-page' && !preview && !description
? '[[aria-busy=false]_&]:h-0'
: !preview && !description
? 'h-0'
: ''
)}
style={{ transitionDelay: style?.animationDelay }}
>
@@ -82,152 +119,86 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
<HighlightQuery query={query} text={description} />
</p>
) : null}
{item.type === 'local-page' ? (
<SkeletonParagraph
size="small"
lines={1}
className={tcls(
'absolute inset-0 origin-left',
preview || description
? 'hidden animate-blur-out'
: '[[aria-busy=false]_&]:hidden [[aria-busy=false]_&]:animate-blur-out'
)}
style={{ animationDelay: style?.animationDelay }}
/>
) : null}
</div>
</SearchResultItem>
);
});
/** Widest a single crumb gets, so one long title can't collapse the rest by itself. */
const CRUMB_MAX_WIDTH = 200;
const Breadcrumbs = (props: { breadcrumbs: PageItem['breadcrumbs']; withOverflow?: boolean }) => {
const { breadcrumbs, withOverflow = (breadcrumbs?.length ?? 0) > 4 } = props;
/**
* One line of breadcrumbs that shows the whole path when it fits. When it doesn't, the levels next
* to the root fold into a "⋯" in second place, moving toward the result until the line fits; the
* last crumb is cut short only once everything between is folded. The folded levels show on a
* deliberate hover only, so moving the mouse across results doesn't pop them up.
*/
const Breadcrumbs = (props: { breadcrumbs: ComputedPageResult['breadcrumbs'] }) => {
const { breadcrumbs = [] } = props;
const containerRef = React.useRef<HTMLDivElement>(null);
const measureRef = React.useRef<HTMLDivElement>(null);
const [folded, setFolded] = React.useState(0);
if (!breadcrumbs || breadcrumbs.length === 0) return null;
const measureFolding = () => {
const container = containerRef.current;
const measure = measureRef.current;
if (!container || !measure) {
return;
}
const widths = Array.from(measure.children, (element) =>
Math.min(element.getBoundingClientRect().width, CRUMB_MAX_WIDTH)
);
const ellipsisWidth = widths.pop() ?? 0;
const separatorWidth =
(widths.pop() ?? 0) + 2 * Number.parseFloat(getComputedStyle(container).columnGap);
setFolded(countFoldedCrumbs(widths, container.clientWidth, separatorWidth, ellipsisWidth));
};
// The measuring copy resizes when the labels change, the container when the row does.
useResizeObserver(containerRef, measureFolding);
useResizeObserver(measureRef, measureFolding);
const crumbs =
breadcrumbs?.map((crumb) => (
<span key={crumb.label} className="flex items-center gap-1">
{crumb.icon ? <Icon className="size-3" icon={crumb.icon as IconName} /> : null}
{crumb.label}
</span>
)) ?? [];
const first = breadcrumbs[0];
if (!first) return null;
const hidden = breadcrumbs.slice(1, 1 + folded);
const shown = breadcrumbs.slice(1 + folded);
const separator = <Icon icon="chevron-right" className="size-2 shrink-0" />;
const textClassName = 'text-xs font-normal whitespace-nowrap';
return (
<div
ref={containerRef}
className={tcls(
'relative flex min-w-0 items-center gap-x-2 overflow-hidden text-tint/7 transition-colors group-[.is-active]:text-tint contrast-more:text-tint',
textClassName
)}
>
// Format breadcrumbs for display. Helper function to avoid code duplication across normal and in-tooltip display.
function formatCrumbs(crumbs: React.ReactElement[], className?: string) {
return (
<div
ref={measureRef}
aria-hidden
className="invisible absolute left-0 top-0 flex items-center"
className={tcls(
'transition-colors',
'font-normal',
'flex',
'flex-wrap',
'gap-x-2',
'gap-y-0',
'items-center',
className
)}
>
{breadcrumbs.map((crumb, index) => (
<span key={index}>{crumb.label}</span>
{crumbs.map((crumb, index) => (
<React.Fragment key={index}>
{index !== 0 ? (
<Icon
key={`${crumb.key}-icon`}
icon="chevron-right"
className="size-2"
/>
) : null}
<span className="line-clamp-1">{crumb}</span>
</React.Fragment>
))}
{separator}
<Icon icon="ellipsis" className="size-3" />
</div>
<CrumbLabel label={first.label} className="shrink-0" />
{hidden.length > 0 ? (
<>
{separator}
<Tooltip
delay={1000}
label={
<span className="flex flex-col py-0.5">
{hidden.map((crumb, index) => (
<span key={index}>{crumb.label}</span>
))}
</span>
}
>
<span className="flex shrink-0 items-center">
<Icon icon="ellipsis" className="size-3" />
<span className="sr-only">
{hidden.map((crumb) => crumb.label).join(' › ')}
</span>
</span>
</Tooltip>
</>
) : null}
{shown.map((crumb, index) => (
<React.Fragment key={index}>
{separator}
<CrumbLabel
label={crumb.label}
className={index === shown.length - 1 ? 'min-w-[3ch] shrink' : 'shrink-0'}
/>
</React.Fragment>
))}
</div>
);
};
const CrumbLabel = (props: { label: string; className: string }) => {
const { label, className } = props;
const ref = React.useRef<HTMLSpanElement>(null);
const [truncated, setTruncated] = React.useState(false);
useResizeObserver(ref, () => {
const element = ref.current;
if (element) {
setTruncated(element.scrollWidth > element.clientWidth);
}
});
return (
<span
ref={ref}
className={tcls('max-w-[200px] truncate', className)}
title={truncated ? label : undefined}
>
{label}
</span>
);
};
/**
* How many crumbs after the first to fold into the "⋯" so the line fits `available` pixels. The
* first and last crumbs never fold; when even folding everything between doesn't fit, the last
* crumb is cut short instead.
*/
function countFoldedCrumbs(
widths: number[],
available: number,
separatorWidth: number,
ellipsisWidth: number
): number {
const foldable = Math.max(widths.length - 2, 0);
for (let folded = 0; folded <= foldable; folded++) {
const visible = widths.filter((_, index) => index === 0 || index > folded);
const items = visible.length + (folded > 0 ? 1 : 0);
const total =
visible.reduce((sum, width) => sum + width, 0) +
(folded > 0 ? ellipsisWidth : 0) +
(items - 1) * separatorWidth;
if (total <= available + 0.5) {
return folded;
}
);
}
return foldable;
}
return formatCrumbs(
withOverflow
? [
...crumbs.slice(0, 3),
<Tooltip
key="breadcrumbs-overflow"
label={formatCrumbs(crumbs.slice(3, -1))}
delay={0}
arrow
>
<span>
<Icon key="ellipsis" icon="ellipsis-h" className="size-3" />
</span>
</Tooltip>,
...crumbs.slice(-1),
]
: crumbs,
'text-tint/7 contrast-more:text-tint group-[.is-active]:text-tint text-xs'
);
};
@@ -16,8 +16,6 @@ export const SearchResultItem = React.forwardRef(function SearchResultItem(
size?: 'small' | 'medium';
leadingIcon?: React.ReactNode;
disabled?: boolean;
/** Called when the mouse moves over the item, to make it the selected one. */
onHover?: () => void;
} & LinkInsightsProps &
Omit<React.ComponentProps<typeof Link>, keyof LinkInsightsProps>,
ref: React.Ref<HTMLAnchorElement>
@@ -31,7 +29,6 @@ export const SearchResultItem = React.forwardRef(function SearchResultItem(
size = 'medium',
action,
disabled,
onHover,
...rest
} = props;
@@ -40,16 +37,6 @@ export const SearchResultItem = React.forwardRef(function SearchResultItem(
ref={ref}
href={href ?? '#'}
aria-disabled={disabled}
// Only a real mouse move selects, so rows scrolling under a still pointer don't.
onPointerMove={
onHover && !active
? (event: React.PointerEvent) => {
if (event.pointerType === 'mouse') {
onHover();
}
}
: undefined
}
className={tcls(
'flex',
'items-center',
@@ -59,26 +46,27 @@ export const SearchResultItem = React.forwardRef(function SearchResultItem(
'pr-2',
'py-2',
'text-tint',
disabled ? ['pointer-events-none'] : null,
disabled ? ['pointer-events-none'] : ['hover:bg-tint', 'hover:text-tint-strong'],
'group',
'transition-colors',
'rounded-corners:rounded-md',
'circular-corners:rounded-2xl',
active ? ['is-active', 'bg-primary', 'text-primary-strong'] : null,
active
? ['is-active', 'bg-primary', 'text-primary-strong', 'hover:bg-primary']
: null,
className
)}
role="option"
{...rest}
>
{leadingIcon ? (
<div className="size-4 shrink-0 text-tint-subtle">
{typeof leadingIcon === 'string' ? (
<Icon icon={leadingIcon as IconName} className="size-4" />
) : (
leadingIcon
)}
</div>
) : null}
<div className="min-w-0 grow">{children}</div>
<div className="size-4 shrink-0 text-tint-subtle">
{typeof leadingIcon === 'string' ? (
<Icon icon={leadingIcon as IconName} className="size-4" />
) : (
leadingIcon
)}
</div>
<div className="grow">{children}</div>
{disabled ? null : active ? (
<Button
label={action}
@@ -4,39 +4,27 @@ import assertNever from 'assert-never';
import { motion } from 'framer-motion';
import React from 'react';
import { Button } from '../primitives';
import { Button, SkeletonParagraph, SkeletonSmall } from '../primitives';
import { isExternalLink } from '../utils/link';
import { addRecentSearchQuery } from './recent-queries';
import { SearchPageResultItem } from './SearchPageResultItem';
import { SearchQuestionResultItem } from './SearchQuestionResultItem';
import { SearchRecordResultItem } from './SearchRecordResultItem';
import { SearchResultItem } from './SearchResultItem';
import type { ResultType } from './useSearchResults';
import { useAI } from '@/components/AI';
import { useCurrentContent } from '@/components/hooks';
import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
/**
* Bar widths (breadcrumb, title, description, in %) of the loading placeholder rows. Six rows of
* this height fill the results area of the desktop popover; the count never depends on an answer.
*/
const PLACEHOLDER_ROWS: [crumb: number, title: number, description: number][] = [
[28, 64, 86],
[20, 48, 78],
[34, 58, 90],
[24, 70, 72],
[30, 52, 84],
[22, 60, 76],
];
export interface SearchResultsRef {
select(): boolean;
/** Activate the first result, ignoring the cursor. */
selectFirst(): boolean;
}
function getResultKey(item: ResultType): string {
switch (item.type) {
case 'local-page':
return `page:${item.id}`;
case 'page':
return `page:${item.pageId}`;
case 'record':
@@ -63,12 +51,10 @@ export const SearchResults = React.forwardRef(function SearchResults(
cursor: number | null;
error: boolean;
onResultSelect?: () => void;
onResultHover?: (index: number) => void;
},
ref: React.Ref<SearchResultsRef>
) {
const { children, id, query, results, fetching, cursor, error, onResultSelect, onResultHover } =
props;
const { children, id, query, results, fetching, cursor, error, onResultSelect } = props;
const language = useLanguage();
const { siteSpaceId } = useCurrentContent();
@@ -83,7 +69,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
}
const refs = React.useRef<(null | HTMLAnchorElement)[]>([]);
const selectedByPointer = React.useRef(false);
React.useEffect(() => {
for (const item of results) {
@@ -91,12 +76,8 @@ export const SearchResults = React.forwardRef(function SearchResults(
}
}, [results]);
// Scroll to the active result, unless the mouse picked it: it is already under the pointer.
// Scroll to the active result.
React.useEffect(() => {
if (selectedByPointer.current) {
selectedByPointer.current = false;
return;
}
if (cursor === null || !refs.current[cursor]) {
return;
}
@@ -126,11 +107,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
ref,
() => ({
select,
selectFirst: () => {
const first = refs.current[0];
first?.click();
return Boolean(first);
},
}),
[select]
);
@@ -138,7 +114,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
const { assistants } = useAI();
const primaryAssistant = assistants[0];
if (error) {
if (error && results.length === 0) {
return (
<output
className={tcls(
@@ -181,6 +157,26 @@ export const SearchResults = React.forwardRef(function SearchResults(
</output>
);
const partialError = error ? (
<div
className={tcls(
'mt-3',
'rounded-corners:rounded-md',
'circular-corners:rounded-2xl',
'bg-tint-subtle',
'px-3',
'py-2',
'text-center',
'text-sm',
'text-tint-subtle',
'animate-blur-in-slow'
)}
role="status"
>
{t(language, 'search_partial_error')}
</div>
) : null;
return (
<output className="flex grow flex-col" aria-busy={fetching}>
{children}
@@ -206,7 +202,10 @@ export const SearchResults = React.forwardRef(function SearchResults(
const handleResultSelect = (
event: React.MouseEvent<HTMLAnchorElement>
) => {
const isPageResult = item.type === 'page' || item.type === 'record';
const isPageResult =
item.type === 'local-page' ||
item.type === 'page' ||
item.type === 'record';
if (
isPageResult &&
@@ -237,14 +236,9 @@ export const SearchResults = React.forwardRef(function SearchResults(
'aria-setsize': results.length,
id: `${id}-${index}`,
onClickCapture: handleResultSelect,
onHover: onResultHover
? () => {
selectedByPointer.current = true;
onResultHover(index);
}
: undefined,
};
switch (item.type) {
case 'local-page':
case 'page': {
return (
<motion.div
@@ -359,61 +353,49 @@ export const SearchResults = React.forwardRef(function SearchResults(
{!fetching && results.length === 0 ? noResults : null}
</>
)}
{partialError}
{fetching ? (
<div
role="status"
aria-busy="true"
className={tcls(
results.length > 0 ? 'mt-1' : '',
'flex flex-col gap-1',
'animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] motion-reduce:animate-none'
'flex animate-blur-in flex-col gap-1'
)}
style={{ animationDelay: `${results.length * 25}ms` }}
>
<SearchResultsPlaceholder />
<SearchResultsSkeleton items={Math.max(3, 5 - results.length)} />
</div>
) : null}
</output>
);
});
/**
* Loading rows shaped like a page result: breadcrumb, title and description lines in the real
* row's box, so the first result lands where the first placeholder was.
*/
const SearchResultsPlaceholder = () =>
PLACEHOLDER_ROWS.map(([crumb, title, description], index) => (
<div
key={index}
data-search-placeholder-row
aria-hidden
className="flex items-center gap-3 py-2 pl-3 pr-2"
>
<div className="grow">
<PlaceholderLine className="text-xs" barClassName="h-2" width={crumb} />
<PlaceholderLine
className="font-heading text-base font-semibold leading-snug"
barClassName="h-3.5 bg-tint-solid/3"
width={title}
/>
<PlaceholderLine className="h-5 text-sm" barClassName="h-2.5" width={description} />
</div>
<div className="size-7 shrink-0" />
</div>
));
const SearchResultsSkeleton = (props: { items: number }) => {
const { items } = props;
const skeletonKeys = Array.from({ length: items }, (_, index) => `skeleton:${index}`);
/** One text line of a placeholder row: the line box of the real text, with a bar inside it. */
const PlaceholderLine = (props: { className: string; barClassName: string; width: number }) => (
<div className={tcls('relative', props.className)}>
{'\u00a0'}
<div
className={tcls(
'absolute inset-y-0 left-0 my-auto rounded-full bg-tint-solid/2',
props.barClassName
)}
style={{ width: `${props.width}%` }}
/>
</div>
);
return (
<>
{skeletonKeys.map((key, index) => (
<SearchResultItem
key={key}
active={false}
href="#"
action=""
disabled
data-testid="search-page-result"
leadingIcon={
<SkeletonSmall
className="size-4"
style={{ animationDelay: `${index * 0.3}s` }}
/>
}
>
<SkeletonParagraph size="small" start={index * 3} />
</SearchResultItem>
))}
</>
);
};
/**
* Whether clicking a result navigates the current window, and so closes the search — as opposed
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'bun:test';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import type { OrderedComputedResult } from './search-types';
import { computeFilterSiteSpaceIds } from './filter';
describe('computeFilterSiteSpaceIds', () => {
const currentId = 'space-current';
@@ -35,31 +34,3 @@ describe('computeFilterSiteSpaceIds', () => {
expect(r).toEqual(['space-other-a', 'space-other-b']);
});
});
describe('filterResultsBySiteSpaces', () => {
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
type: 'page',
id,
title: id,
href: `/${id}`,
score: 1,
pageId: id,
spaceId: 'space',
siteSpaceId,
description: '',
rank: 1,
});
it('keeps the server order and drops pages outside the scope', () => {
const results = [page('a', 'current'), page('b', 'other'), page('c', 'current'), page('d')];
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
'a',
'c',
]);
});
it('returns every result when the scope is unrestricted', () => {
const results = [page('b', 'other'), page('a', 'current')];
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
});
});
@@ -1,13 +1,16 @@
import type { OrderedComputedResult } from './search-types';
import type { SearchScope } from './useSearch';
/**
* Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction.
* Map UI search scope to local FlexSearch filtering.
*
* The server's "default" scope also returns pages from other site spaces. Without sections
* (only variants) the UI presents "default" as the current variant, so it is restricted to
* the current `siteSpaceId`. An explicitly selected section takes precedence.
* Rationale: when a site has no sections (only variants), the remote search
* "default" scope effectively queries the current variant. To keep local
* results consistent with remote ones, we also restrict "default" to the
* current `siteSpaceId` when `withSections` is false. Otherwise (sections
* present), local "default" stays unfiltered to match the broader section UI.
* An explicitly selected section takes precedence over these legacy scopes.
*/
export function computeFilterSiteSpaceIds(
scope: SearchScope,
siteSpaceId: string,
@@ -28,21 +31,3 @@ export function computeFilterSiteSpaceIds(
return withSections ? undefined : [siteSpaceId];
}
}
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
export function filterResultsBySiteSpaces(
results: OrderedComputedResult[],
allowedSiteSpaceIds: string[] | undefined
): OrderedComputedResult[] {
if (!allowedSiteSpaceIds) {
return results;
}
const allowed = new Set(allowedSiteSpaceIds);
return results.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
);
}
@@ -5,4 +5,5 @@ export * from './SearchContainer';
export * from './SearchScopeControl';
export * from './search-props';
export * from './useSearch';
export * from './useLocalSearchResults';
export * from './useSearchController';
@@ -0,0 +1,239 @@
import { describe, expect, it } from 'bun:test';
import {
type MergedPageResult,
fuseSearchResults,
getResultKey,
reciprocalRankFusion,
} from './reciprocalRankFusion';
import type { OrderedComputedResult } from './search-types';
import type { LocalPageResult } from './useLocalSearchResults';
function localPage(id: string, title = id, siteSpaceId = 'site-space-alpha'): LocalPageResult {
return {
type: 'local-page',
id,
siteSpaceId,
title,
pathname: `/${id}`,
description: `Local description for ${title}`,
breadcrumbs: [{ label: 'Local', icon: 'book-open' }],
};
}
function remotePage(
id: string,
title = id,
score = 0,
rank = 1,
spaceId = 'space-alpha',
siteSpaceId = 'site-space-alpha'
): OrderedComputedResult {
return {
type: 'page',
id: `remote-${id}`,
pageId: id,
spaceId,
siteSpaceId,
title,
description: `Remote description for ${title}`,
href: `/${id}`,
score,
rank,
breadcrumbs: [{ label: 'Remote' }],
};
}
function remoteRecord(id: string, title = id): OrderedComputedResult {
return {
type: 'record',
id,
title,
href: `/records/${id}`,
score: 0,
description: undefined,
};
}
describe('reciprocalRankFusion', () => {
it('keeps the first 3 remote results first and in remote order', () => {
const results = reciprocalRankFusion(
[localPage('local-match', 'Alpha Local Match')],
[
remotePage('remote-1'),
remoteRecord('remote-2'),
remotePage('remote-3'),
remotePage('remote-4'),
],
'alpha'
);
expect(results.slice(0, 3).map(getResultKey)).toEqual([
'page:remote-1',
'record:remote-2',
'page:remote-3',
]);
});
it('applies fusion only after the pinned remote results', () => {
const results = reciprocalRankFusion(
[localPage('local-match', 'Alpha Local Match')],
[
remotePage('remote-1'),
remotePage('remote-2'),
remotePage('remote-3'),
remotePage('remote-4'),
],
'alpha'
);
expect(results.slice(0, 3).map(getResultKey)).toEqual([
'page:remote-1',
'page:remote-2',
'page:remote-3',
]);
const firstFusedResult = results[3];
if (!firstFusedResult) {
throw new Error('Expected a fused result after the pinned remote results');
}
expect(getResultKey(firstFusedResult)).toBe('page:local-match');
});
it('pins all remote results when fewer than 3 are present', () => {
const results = reciprocalRankFusion(
[localPage('local-match', 'Alpha Local Match')],
[remoteRecord('remote-1'), remotePage('remote-2')],
'alpha'
);
expect(results.map(getResultKey)).toEqual([
'record:remote-1',
'page:remote-2',
'page:local-match',
]);
});
it('merges a pinned remote page with the matching local page without duplicating it', () => {
const results = reciprocalRankFusion(
[localPage('remote-1', 'Local title')],
[
remotePage('remote-1', 'Remote title', 1, 1),
remotePage('remote-2'),
remotePage('remote-3'),
],
'remote'
);
const pinnedResult = results[0] as MergedPageResult;
expect(pinnedResult.type).toBe('page');
expect(pinnedResult.title).toBe('Remote title');
expect(pinnedResult.pathname).toBe('/remote-1');
expect(pinnedResult.description).toBe('Remote description for Remote title');
expect(pinnedResult.rank).toBe(1);
expect(pinnedResult.breadcrumbs).toEqual([{ label: 'Local', icon: 'book-open' }]);
expect(results.map(getResultKey).filter((key) => key === 'page:remote-1')).toHaveLength(1);
});
it('does not duplicate pinned records in the fused tail', () => {
const results = reciprocalRankFusion(
[],
[
remoteRecord('record-1'),
remotePage('remote-2'),
remotePage('remote-3'),
remoteRecord('record-1'),
remotePage('remote-4'),
],
'remote'
);
expect(results.map(getResultKey).filter((key) => key === 'record:record-1')).toHaveLength(
1
);
});
});
describe('fuseSearchResults', () => {
it('filters every source to the current site space before fusion', () => {
const results = fuseSearchResults({
localResults: [
localPage('local-alpha', 'Alpha local result'),
localPage('remote-alpha-1', 'Beta local result', 'site-space-beta'),
],
remoteResults: [
remotePage('remote-alpha-1', 'Alpha remote one', 10, 1),
remotePage(
'local-alpha',
'Beta remote result',
9,
2,
'space-beta',
'site-space-beta'
),
remotePage('remote-alpha-2', 'Alpha remote two', 8, 3),
],
query: 'result',
allowedSiteSpaceIds: ['site-space-alpha'],
});
expect(results.map(getResultKey)).toEqual([
'page:remote-alpha-1',
'page:remote-alpha-2',
'page:local-alpha',
]);
expect(results[0]).not.toHaveProperty('pathname');
expect(results[2]?.type).toBe('local-page');
});
it('preserves cross-site-space results when the search is unrestricted', () => {
const results = fuseSearchResults({
localResults: [
localPage('local-alpha', 'Alpha local result'),
localPage('local-beta', 'Beta local result', 'site-space-beta'),
],
remoteResults: [
remotePage('remote-alpha', 'Alpha remote result', 10, 1),
remotePage(
'remote-beta',
'Beta remote result',
9,
2,
'space-beta',
'site-space-beta'
),
],
query: 'result',
});
expect(results.map(getResultKey)).toEqual([
'page:remote-alpha',
'page:remote-beta',
'page:local-alpha',
'page:local-beta',
]);
});
it('preserves every allowed site space in an intentionally multi-space search', () => {
const results = fuseSearchResults({
localResults: [
localPage('local-alpha'),
localPage('local-beta', 'local-beta', 'site-space-beta'),
localPage('local-gamma', 'local-gamma', 'site-space-gamma'),
],
remoteResults: [
remotePage('remote-alpha'),
remotePage('remote-beta', 'remote-beta', 0, 2, 'space-beta', 'site-space-beta'),
remotePage('remote-gamma', 'remote-gamma', 0, 3, 'space-gamma', 'site-space-gamma'),
],
query: 'page',
allowedSiteSpaceIds: ['site-space-alpha', 'site-space-beta'],
});
expect(results.map(getResultKey)).toEqual([
'page:remote-alpha',
'page:remote-beta',
'page:local-alpha',
'page:local-beta',
]);
});
});
@@ -0,0 +1,271 @@
import type { ComputedPageResult, OrderedComputedResult } from './search-types';
import type { LocalPageResult } from './useLocalSearchResults';
/**
* Jaro-Winkler similarity between two strings, in the range [0, 1].
* Higher is more similar. 1 means an exact match.
* https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance
*/
function jaroWinkler(s1: string, s2: string, p = 0.1): number {
if (s1 === s2) return 1;
const len1 = s1.length;
const len2 = s2.length;
if (len1 === 0 || len2 === 0) return 0;
const maxDist = Math.floor(Math.max(len1, len2) / 2) - 1;
const matched1 = new Array<boolean>(len1);
const matched2 = new Array<boolean>(len2);
for (let i = 0; i < len1; i++) matched1[i] = false;
for (let i = 0; i < len2; i++) matched2[i] = false;
let matches = 0;
for (let i = 0; i < len1; i++) {
const start = Math.max(0, i - maxDist);
const end = Math.min(len2 - 1, i + maxDist);
for (let j = start; j <= end; j++) {
if (!matched2[j] && s1.charCodeAt(i) === s2.charCodeAt(j)) {
matched1[i] = true;
matched2[j] = true;
matches++;
break;
}
}
}
if (matches === 0) return 0;
let t = 0;
let k = 0;
for (let i = 0; i < len1; i++) {
if (!matched1[i]) continue;
while (!matched2[k]) k++;
if (s1.charCodeAt(i) !== s2.charCodeAt(k)) t++;
k++;
}
const transpositions = t / 2;
const m = matches;
const jaro = (m / len1 + m / len2 + (m - transpositions) / m) / 3;
let prefix = 0;
const maxPrefix = 4;
const minLen = Math.min(len1, len2);
for (let i = 0; i < maxPrefix && i < minLen; i++) {
if (s1.charCodeAt(i) === s2.charCodeAt(i)) prefix++;
else break;
}
return jaro + prefix * p * (1 - jaro);
}
/** Standard RRF constant — moderates the impact of high-ranked items. */
const RRF_K = 60;
/** Lower k for local results gives them a slightly higher score than remote ones at the same rank. */
const RRF_K_LOCAL = 50;
/** Number of remote results that should keep their API order before fusion. */
const PINNED_REMOTE_RESULTS_COUNT = 3;
/**
* A page result that was present in both local and remote lists.
* Local fields (icon, emoji, pathname) are carried over as a base, and remote fields
* (description, href, pageId, spaceId, title) override them.
* Breadcrumbs prefer local (has icon + emoji) and fall back to remote.
*/
export type MergedPageResult = Omit<ComputedPageResult, 'breadcrumbs'> & {
pathname?: string;
icon?: string;
emoji?: string;
breadcrumbs?: LocalPageResult['breadcrumbs'] | ComputedPageResult['breadcrumbs'];
};
/**
* Derive a stable deduplication key for any result type.
* Pages from both local and remote share the same `page:` namespace so they
* can be deduplicated against each other.
*/
export function getResultKey(
result: LocalPageResult | OrderedComputedResult | MergedPageResult
): string {
switch (result.type) {
case 'local-page':
return `page:${result.id}`;
case 'page':
return `page:${result.pageId}`;
case 'record':
return `record:${result.id}`;
}
}
type RRFResult = LocalPageResult | OrderedComputedResult | MergedPageResult;
/** Filter page candidates at the final assembly boundary, immediately before ranking and fusion. */
export function fuseSearchResults(args: {
localResults: LocalPageResult[];
remoteResults: OrderedComputedResult[];
query: string;
allowedSiteSpaceIds?: string[];
}): RRFResult[] {
const { localResults, remoteResults, query, allowedSiteSpaceIds } = args;
if (!allowedSiteSpaceIds) {
return reciprocalRankFusion(localResults, remoteResults, query);
}
const allowed = new Set(allowedSiteSpaceIds);
return reciprocalRankFusion(
localResults.filter((result) => allowed.has(result.siteSpaceId)),
remoteResults.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
),
query
);
}
function mergeLocalPageWithRemotePage(
localResult: LocalPageResult,
remoteResult: ComputedPageResult
): MergedPageResult {
return {
...localResult,
...remoteResult,
// Merge breadcrumbs: prefer local (has icon + emoji), fall back to remote.
breadcrumbs: localResult.breadcrumbs ?? remoteResult.breadcrumbs,
};
}
function mergePinnedRemoteResult(
result: OrderedComputedResult,
localResultsByKey: Map<string, LocalPageResult>
): RRFResult {
if (result.type !== 'page') {
return result;
}
const localResult = localResultsByKey.get(getResultKey(result));
if (!localResult) {
return result;
}
return mergeLocalPageWithRemotePage(localResult, result);
}
/**
* Merge local (FlexSearch) and remote (API) search results using
* Reciprocal Rank Fusion (RRF), while preserving the order of the first
* three remote results.
*
* RRF formula: score(d) = Σ_i 1 / (k + rank_i(d))
*
* The pinned remote results are excluded from fusion and returned first. Pages
* present in both lists are deep-merged: local fields act as the base
* (preserving icon, emoji, pathname) and remote fields override (providing the
* authoritative page description, href, pageId, spaceId, and title). Breadcrumbs prefer local (has icon
* + emoji) and fall back to remote. In the fused tail, their rank contributions
* from both lists are summed.
*
* Sections and records have no local equivalent and only accumulate their own
* rank contribution.
*
* Additionally, a Jaro-Winkler title-match bonus is applied per query word:
* for each query word that appears as a substring in the title, the best
* Jaro-Winkler similarity score against any individual title word is added.
*/
export function reciprocalRankFusion(
localResults: LocalPageResult[],
remoteResults: OrderedComputedResult[],
query: string
): RRFResult[] {
const localResultsByKey = new Map(localResults.map((result) => [getResultKey(result), result]));
const pinnedRemoteResults = remoteResults.slice(0, PINNED_REMOTE_RESULTS_COUNT);
const pinnedResultKeys = new Set(pinnedRemoteResults.map((result) => getResultKey(result)));
const remainingLocalResults = localResults.filter(
(result) => !pinnedResultKeys.has(getResultKey(result))
);
const remainingRemoteResults = remoteResults
.slice(PINNED_REMOTE_RESULTS_COUNT)
.filter((result) => !pinnedResultKeys.has(getResultKey(result)));
// Map from dedup key → { result, score }
const scoreMap = new Map<string, { result: RRFResult; score: number }>();
// Process local results first (1-indexed rank)
// Using RRF_K_LOCAL (< RRF_K) slightly boosts local scores over remote ones.
remainingLocalResults.forEach((result, index) => {
const rank = index + 1;
const key = getResultKey(result);
const contribution = 1 / (RRF_K_LOCAL + rank);
const existing = scoreMap.get(key);
if (existing) {
existing.score += contribution;
} else {
scoreMap.set(key, { result, score: contribution });
}
});
// Process remote results, deduplicating against local pages
remainingRemoteResults.forEach((result, index) => {
const rank = index + 1;
const contribution = 1 / (RRF_K + rank);
const key = getResultKey(result);
const existing = scoreMap.get(key);
if (existing) {
// Page found in both lists: sum rank contributions and deep-merge.
// Local is the base (icon, emoji, pathname), while remote provides page fields.
existing.score += contribution;
if (existing.result.type === 'local-page' && result.type === 'page') {
existing.result = mergeLocalPageWithRemotePage(existing.result, result);
} else {
existing.result = result;
}
} else {
scoreMap.set(key, { result, score: contribution });
}
});
// Apply a title-match bonus per query word using Jaro-Winkler similarity.
// For each query word that appears (as a substring) in the title, compute the
// best Jaro-Winkler score against individual title words and add it to the score.
const queryWords = query
.toLowerCase()
.split(/\s+/)
.filter((w) => w.length > 0);
if (queryWords.length > 0) {
for (const entry of scoreMap.values()) {
// Only apply the bonus to page or local-page results
if (entry.result.type === 'record') continue;
const title = entry.result.title?.toLowerCase() ?? '';
const titleWords = title.split(/\s+/).filter((w) => w.length > 0);
for (const word of queryWords) {
// Only apply when there is at least a substring match in the title.
if (!title.includes(word)) continue;
let best = 0;
for (const titleWord of titleWords) {
const sim = jaroWinkler(word, titleWord);
if (sim > best) best = sim;
}
entry.score += best;
}
}
}
// Sort descending by RRF score
const fusedResults = Array.from(scoreMap.values())
.sort((a, b) => b.score - a.score)
.map(({ result }) => result);
return [
...pinnedRemoteResults.map((result) => mergePinnedRemoteResult(result, localResultsByKey)),
...fusedResults,
];
}
@@ -1,139 +0,0 @@
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
import { createSearchPassStore } from './search-pass-store';
import type { DirectSearchProps } from '@/lib/search-results';
const endpoint = 'https://api.gitbook.com/v1/orgs/org_1/sites/site_1/search';
const directSearch: DirectSearchProps = {
apiURL: 'https://api.gitbook.com',
organizationId: 'org_1',
siteId: 'site_1',
linker: {
urlMode: 'url-host',
siteHost: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/',
gitbookURL: undefined,
},
spaces: {},
passURL: '/~gitbook/search-pass',
};
/** Answer each pass request with a new pass, and each API search with the next status. */
function mockFetch(apiStatuses: number[], passLifetimesMs: number[] = []) {
const authorizations: (string | null)[] = [];
let passes = 0;
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (
input: RequestInfo | URL,
init?: RequestInit
) => {
if (init?.signal?.aborted) {
throw new DOMException('Aborted', 'AbortError');
}
if (String(input) === '/~gitbook/search-pass') {
passes += 1;
return Response.json({
token: `pass-${passes}`,
expiresIn: passLifetimesMs.shift() ?? 300_000,
});
}
expect(String(input)).toBe(endpoint);
authorizations.push(new Headers(init?.headers).get('authorization'));
const status = apiStatuses.shift() ?? 200;
return status === 200 ? Response.json({ items: [] }) : new Response(null, { status });
}) as typeof fetch);
return { authorizations, fetchSpy };
}
function search(store: ReturnType<typeof createSearchPassStore>, signal?: AbortSignal) {
return store.search({
query: 'tokens',
scope: { mode: 'all' },
signal: signal ?? new AbortController().signal,
asEmbeddable: false,
});
}
describe('createSearchPassStore', () => {
let restore: (() => void) | undefined;
afterEach(() => restore?.());
it('stays on the route for the rest of the page after a 403', async () => {
const { authorizations, fetchSpy } = mockFetch([403]);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '403' });
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '403' });
expect(authorizations).toHaveLength(1);
});
it.each([
['an expired pass', [], [1_000], 'expired', ['Bearer pass-2']],
['a 401', [401], [], '401', ['Bearer pass-1', 'Bearer pass-2']],
])(
'sends the search to the route on %s and searches directly again with a new pass',
async (_name, apiStatuses, passLifetimesMs, reason, sent) => {
const { authorizations, fetchSpy } = mockFetch(apiStatuses, passLifetimesMs);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(authorizations).toEqual(sent);
}
);
it('keeps the one-refresh bound when a 401 arrives while a refresh is pending', async () => {
const replies = {
search: Promise.withResolvers<Response>(),
pass: Promise.withResolvers<Response>(),
};
let passRequests = 0;
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (
input: RequestInfo | URL
) => {
if (String(input) === '/~gitbook/search-pass') {
passRequests += 1;
return passRequests === 2
? replies.pass.promise
: Response.json({ token: `pass-${passRequests}`, expiresIn: 300_000 });
}
return passRequests === 1
? replies.search.promise
: new Response(null, { status: 401 });
}) as typeof fetch);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
const inFlight = search(store);
const refresh = store.requestPass();
replies.search.resolve(new Response(null, { status: 401 }));
expect(await inFlight).toEqual({ type: 'route', reason: '401' });
replies.pass.resolve(Response.json({ token: 'pass-2', expiresIn: 300_000 }));
await refresh;
expect(await search(store)).toEqual({ type: 'route', reason: '401' });
expect(passRequests).toBe(2);
});
it('neither retries nor falls back when the search is aborted', async () => {
const { authorizations, fetchSpy } = mockFetch([]);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
const controller = new AbortController();
controller.abort();
await expect(search(store, controller.signal)).rejects.toThrow();
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(authorizations).toHaveLength(1);
});
});
@@ -1,258 +0,0 @@
import ReactDOM from 'react-dom';
import type { SearchRecordResult, SearchSpaceResult } from '@gitbook/api';
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
import { getEmbeddableLinker } from '@/lib/embeddable-linker';
import { createSiteLinker } from '@/lib/links';
import {
type DirectSearchProps,
computePublishedSearchResults,
toSearchSiteContentBody,
} from '@/lib/search-results';
/** Request header on a search route call naming why the search did not go to the API. */
export const SEARCH_FALLBACK_HEADER = 'x-gitbook-search-fallback';
const PASS_REQUEST_TIMEOUT_MS = 3_000;
const EXPIRY_MARGIN_MS = 5_000;
const RATE_LIMIT_WAIT_MS = 2_000;
// The longest shared rate limit window of the search API.
const RATE_LIMIT_MAX_WAIT_MS = 60_000;
const DIRECT_SEARCH_TIMEOUT_MS = 5_000;
// Which limit answered a 429: `caller` is the pass's own, `capacity` a saturated index.
const RATE_LIMIT_SCOPE_HEADER = 'x-ratelimit-scope';
type SearchPassState =
| { status: 'none'; reason?: string }
| { status: 'ready'; token: string; expiresAt: number; replacesRejectedPass: boolean }
| { status: 'route'; reason: string; cooldownUntil: number };
type DirectSearchOutcome =
| { type: 'results'; results: OrderedComputedResult[] }
| { type: 'route'; reason?: string };
export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
/**
* Hold a search pass from the site's search pass route in memory, and search the API with it.
*/
export function createSearchPassStore(directSearch: DirectSearchProps | undefined) {
let state: SearchPassState = { status: 'none' };
let pendingRequest: Promise<void> | null = null;
const sendPassRequest = async () => {
if (!directSearch || state.status === 'route') {
return;
}
// The held pass may belong to a session that has since ended, so it waits for the reply.
if (state.status === 'ready') {
state = state.replacesRejectedPass
? { status: 'none', reason: '401' }
: { status: 'none' };
}
const request = new AbortController();
const timeout = setTimeout(() => request.abort(), PASS_REQUEST_TIMEOUT_MS);
try {
const response = await fetch(directSearch.passURL, {
method: 'POST',
signal: request.signal,
});
const { token, expiresIn } =
response.status === 200
? ((await response.json()) as { token?: unknown; expiresIn?: unknown })
: {};
// A search may have moved the page to the route while this request was in flight.
const current = state as SearchPassState;
if (
current.status !== 'route' &&
typeof token === 'string' &&
typeof expiresIn === 'number'
) {
state = {
status: 'ready',
token,
expiresAt: Date.now() + expiresIn,
replacesRejectedPass:
(current.status === 'none' && current.reason === '401') ||
(current.status === 'ready' && current.replacesRejectedPass),
};
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
} else if (current.status === 'ready') {
state = { status: 'none' };
}
if (!response.ok) {
throw new Error(`Search pass request failed: ${response.status}`);
}
} catch (error) {
const current = state as SearchPassState;
// Keep the 401 so a later replacement pass is still refused only once.
if (
current.status === 'ready' ||
(current.status === 'none' && current.reason !== '401')
) {
state = { status: 'none', reason: 'pass_request' };
}
throw error;
} finally {
clearTimeout(timeout);
}
};
const requestPass = () => {
pendingRequest ??= sendPassRequest().finally(() => {
pendingRequest = null;
});
return pendingRequest;
};
const dropPass = (token: string, reason: string): DirectSearchOutcome => {
if (state.status === 'ready' && state.token === token) {
state = { status: 'none', reason };
void requestPass().catch(() => undefined);
} else if (state.status === 'none' && reason === '401') {
// The pass was suspended for a pending request: its reply must still see the rejection.
state = { status: 'none', reason };
}
return { type: 'route', reason };
};
const fallBack = (reason: string): DirectSearchOutcome => {
state = { status: 'route', reason, cooldownUntil: 0 };
return { type: 'route', reason };
};
const search = async (input: {
query: string;
scope: SearchSiteContentScope;
signal: AbortSignal;
asEmbeddable: boolean;
}): Promise<DirectSearchOutcome> => {
const { query, scope, signal, asEmbeddable } = input;
if (!directSearch) {
return { type: 'route' };
}
if (state.status === 'ready' && state.expiresAt - Date.now() <= EXPIRY_MARGIN_MS) {
return dropPass(state.token, 'expired');
}
if (state.status === 'route') {
return waitForCooldown(state, signal);
}
if (state.status !== 'ready') {
return { type: 'route', reason: state.reason };
}
if (query.length <= 1) {
return { type: 'results', results: [] };
}
const { token, replacesRejectedPass } = state;
const { apiURL, organizationId, siteId } = directSearch;
// A request dropped on the way to the API never settles, so it gets its own time limit.
// The browser targets predate `AbortSignal.any`.
const request = new AbortController();
if (signal.aborted) {
request.abort();
}
signal.addEventListener('abort', () => request.abort(), { once: true });
const timeout = setTimeout(() => request.abort(), DIRECT_SEARCH_TIMEOUT_MS);
let response: Response;
try {
response = await fetch(`${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(toSearchSiteContentBody(query, scope)),
credentials: 'omit',
signal: request.signal,
});
} catch (error) {
if (signal.aborted) {
throw error;
}
return fallBack(request.signal.aborted ? 'timeout' : 'network');
}
if (response.status === 401) {
return replacesRejectedPass ? fallBack('401') : dropPass(token, '401');
}
if (response.status === 429) {
state = {
status: 'route',
reason: '429',
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
};
return waitForCooldown(state, signal);
}
if (!response.ok) {
return fallBack(String(response.status));
}
let results: OrderedComputedResult[] | null;
try {
const { items } = (await response.json()) as {
items: (SearchSpaceResult | SearchRecordResult)[];
};
const linker = createSiteLinker(directSearch.linker);
results = computePublishedSearchResults({
asEmbeddable,
linker: asEmbeddable ? getEmbeddableLinker(linker) : linker,
searchResults: items,
spaces: directSearch.spaces,
});
} catch (error) {
if (signal.aborted) {
throw error;
}
return fallBack(request.signal.aborted ? 'timeout' : 'invalid');
} finally {
clearTimeout(timeout);
}
return results ? { type: 'results', results } : fallBack('unknown_space');
};
return { requestPass, search };
}
/**
* Hold a search until a short rate limit cooldown ends, then send it to the route.
* During a longer cooldown the search fails at once, as the route would.
*/
async function waitForCooldown(
route: Extract<SearchPassState, { status: 'route' }>,
signal: AbortSignal
): Promise<DirectSearchOutcome> {
const waitMs = route.cooldownUntil - Date.now();
if (waitMs > RATE_LIMIT_WAIT_MS) {
throw new Error('Search is rate limited');
}
if (waitMs > 0) {
await new Promise((resolve) => setTimeout(resolve, waitMs));
if (signal.aborted) {
throw new DOMException('Search aborted', 'AbortError');
}
}
return { type: 'route', reason: route.reason };
}
/**
* How long to hold searches after a 429: until the API's rate limit resets, when it says so.
*/
function getRateLimitWaitMs(response: Response): number {
switch (response.headers.get(RATE_LIMIT_SCOPE_HEADER)) {
// The route does not use the pass, and an unnamed limit may come from an older API.
case null:
case 'caller':
case 'capacity':
return RATE_LIMIT_WAIT_MS;
default: {
const resetSeconds = Number(response.headers.get('x-ratelimit-reset'));
if (!resetSeconds) {
return RATE_LIMIT_WAIT_MS;
}
return Math.min(Math.max(resetSeconds * 1000 - Date.now(), 0), RATE_LIMIT_MAX_WAIT_MS);
}
}
}
@@ -2,8 +2,6 @@ import type { SiteExternalLink, SiteSection, SiteSectionGroup, SiteSpace } from
import { hasMultipleSiteSections } from '../SiteSections';
import type { GitBookSiteContext } from '@/lib/context';
import { getSearchSpaceLookup } from '@/lib/search';
import type { DirectSearchProps } from '@/lib/search-results';
import { getLocalizedTitle } from '@/lib/sites';
export type SearchSection = Pick<SiteSection, 'id' | 'icon' | 'object'> & {
@@ -27,6 +25,7 @@ export interface SearchBaseProps {
sections: SearchSectionItem[];
withVariants: boolean;
withSiteVariants: boolean;
indexURL: string;
searchURL: string;
}
@@ -48,6 +47,7 @@ export function getSearchBaseProps(context: GitBookSiteContext): SearchBaseProps
visibleSections?.list.some(
(section) => section.object === 'site-section' && section.siteSpaces.length > 1
) ?? false,
indexURL: context.linker.toPathInSite('~gitbook/site-index'),
withVariants: visibleSiteSpaces.length > 1,
};
}
@@ -123,18 +123,3 @@ export function findSearchSection(
return undefined;
}
/**
* What the browser needs to search the API directly, built from the site spaces visitors can see.
*/
export function getDirectSearchProps(context: GitBookSiteContext): DirectSearchProps | undefined {
if (!context.directSearch) {
return undefined;
}
return {
...context.directSearch,
spaces: getSearchSpaceLookup(context.structure),
passURL: context.linker.toPathInSite('~gitbook/search-pass'),
};
}
@@ -1,5 +1,15 @@
'use client';
/**
* Client-side access to the `~gitbook/site-index` JSON, shared by every consumer
* (instant search in `useLocalSearchResults`, related pages on the 404 page).
*
* Loading strategy: the download starts as early as possible (server-rendered
* preload hint in `SiteLayout`, deduped here at first call) and is kept as raw
* text so the multi-MB `JSON.parse` — main-thread work — is only paid when a
* consumer actually needs the pages.
*/
export interface SiteIndexBreadcrumb {
label: string;
icon?: string;
@@ -20,14 +30,50 @@ export interface SiteIndexPage {
breadcrumbs?: SiteIndexBreadcrumb[];
}
/** Fetch the pages of the site from the `~gitbook/site-index` JSON. */
let siteIndexText: Promise<string> | null = null;
/**
* Start (or reuse) the single-flight download of the raw index. Errors clear the
* cache so the next consumer retries.
*/
export function prefetchSiteIndex(indexURL: string): void {
fetchSiteIndexText(indexURL).catch(() => {
// Ignored: consumers surface errors when they actually read the index.
});
}
/**
* Get the parsed index pages. Parses per call (cheap for the rare second
* consumer) so the parsed object graph is never retained at module scope.
*/
export async function fetchSiteIndex(
indexURL: string
): Promise<{ version: 1; pages: SiteIndexPage[] }> {
const response = await fetch(indexURL);
if (!response.ok) {
throw new Error(`Failed to fetch site index: ${response.status}`);
return JSON.parse(await fetchSiteIndexText(indexURL));
}
/**
* Drop the cached raw text (several MB for large sites) once a consumer has
* turned it into a longer-lived form. Purely a memory release: a later consumer
* re-fetches, hitting the HTTP cache.
*/
export function releaseSiteIndex(): void {
siteIndexText = null;
}
function fetchSiteIndexText(indexURL: string): Promise<string> {
if (!siteIndexText) {
siteIndexText = fetch(indexURL).then((response) => {
if (!response.ok) {
throw new Error(`Failed to fetch search index: ${response.status}`);
}
return response.text();
});
siteIndexText.catch(() => {
siteIndexText = null;
});
}
return response.json();
return siteIndexText;
}
@@ -0,0 +1,262 @@
'use client';
import type { Document, DocumentValue } from 'flexsearch';
import React from 'react';
import {
type SiteIndexBreadcrumb,
type SiteIndexPage,
fetchSiteIndex,
prefetchSiteIndex,
releaseSiteIndex,
} from './site-index';
/** FlexSearch-compatible document type — satisfies DocumentData via explicit index signature */
interface IndexPage {
[key: string]: DocumentValue | DocumentValue[];
id: string;
title: string;
description: string | null;
siteSpaceId: string;
}
/** Result type returned by this hook */
export interface LocalPageResult {
type: 'local-page';
id: string;
siteSpaceId: string;
title: string;
pathname: string;
icon?: string;
emoji?: string;
description?: string;
breadcrumbs?: SiteIndexBreadcrumb[];
}
type LocalSearchState = {
results: LocalPageResult[];
fetching: boolean;
error: boolean;
};
// Module-level singletons — one Document per language per session.
// Keys are the page's `lang` value, or `''` when no language is set.
const cachedIndexes = new Map<string, Document<IndexPage>>();
// Side-map for data that doesn't belong in the FlexSearch index.
// Keyed by page id, shared across all language groups.
const cachedPageData = new Map<
string,
{ pathname: string; icon?: string; emoji?: string; breadcrumbs?: SiteIndexBreadcrumb[] }
>();
let pendingFetch: Promise<Map<string, Document<IndexPage>>> | null = null;
function buildLangIndex(
DocumentCtor: typeof import('flexsearch').Document,
pages: SiteIndexPage[]
): Document<IndexPage> {
const index = new DocumentCtor<IndexPage>({
document: {
id: 'id',
index: ['title', 'description'],
store: ['id', 'title', 'description', 'siteSpaceId'],
tag: 'siteSpaceId',
},
tokenize: 'full',
resolution: 15,
encoder: 'Normalize',
});
for (const page of pages) {
index
.addAsync({
id: page.id,
title: page.title,
description: page.description ?? null,
siteSpaceId: page.siteSpaceId,
})
.catch(() => {
// We just ignore these errors, it's not worth failing the whole index for a single bad record
// And we still have remote search as a fallback for these cases
});
cachedPageData.set(`${page.siteSpaceId}:${page.id}`, {
pathname: page.pathname,
icon: page.icon,
emoji: page.emoji,
breadcrumbs: page.breadcrumbs?.length ? page.breadcrumbs : undefined,
});
}
return index;
}
async function getOrBuildIndexes(indexURL: string): Promise<Map<string, Document<IndexPage>>> {
if (cachedIndexes.size > 0) {
return cachedIndexes;
}
if (pendingFetch) {
return pendingFetch;
}
pendingFetch = (async () => {
// FlexSearch stays in an on-demand chunk instead of the main client bundle, it's only needed once the user actually searches.
const [{ Document }, data] = await Promise.all([
import('flexsearch'),
fetchSiteIndex(indexURL),
]);
// Group pages by their `lang` value (empty string for pages without one)
const pagesByLang = new Map<string, SiteIndexPage[]>();
for (const page of data.pages) {
const key = page.lang ?? '';
const bucket = pagesByLang.get(key);
if (bucket) {
bucket.push(page);
} else {
pagesByLang.set(key, [page]);
}
}
// Build one FlexSearch Document per language group
for (const [lang, pages] of pagesByLang) {
cachedIndexes.set(lang, buildLangIndex(Document, pages));
}
releaseSiteIndex();
return cachedIndexes;
})();
// Clear pendingFetch on error so a retry is possible
pendingFetch.catch(() => {
console.error('Error fetching/building search index', indexURL);
pendingFetch = null;
});
return pendingFetch;
}
export function useLocalSearchResults(props: {
query: string;
indexURL: string;
/** BCP-47 language code of the current site space. When provided, only results
* from pages with a matching language are returned. */
lang?: string;
/** When provided, only results from pages belonging to one of these site space IDs
* are returned. Uses FlexSearch native tag filtering. Omit for no filtering (all spaces). */
filterSiteSpaceIds?: string[];
disabled?: boolean;
/** Whether the search surface is open. */
open: boolean;
}): LocalSearchState {
const { query, indexURL, lang, filterSiteSpaceIds, disabled = false, open } = props;
const [state, setState] = React.useState<LocalSearchState>({
results: [],
fetching: false,
error: false,
});
// Track whether the indexes are loaded so the search effect re-runs after load
const [indexReady, setIndexReady] = React.useState(cachedIndexes.size > 0);
const active = open || Boolean(query);
// Load the indexes once
React.useEffect(() => {
if (cachedIndexes.size > 0) {
setIndexReady(true);
return;
}
prefetchSiteIndex(indexURL);
if (!active) {
return;
}
let cancelled = false;
setState((prev) => ({ ...prev, fetching: true, error: false }));
getOrBuildIndexes(indexURL)
.then(() => {
if (!cancelled) {
setIndexReady(true);
setState((prev) => ({ ...prev, fetching: false }));
}
})
.catch(() => {
if (!cancelled) {
setState({ results: [], fetching: false, error: true });
}
});
return () => {
cancelled = true;
};
}, [indexURL, active]);
// Perform instant local search whenever query, lang, or index readiness changes
React.useEffect(() => {
// Resolve the per-language index to query. When `lang` is not set we fall
// back to the `''` bucket (pages with no language tag).
const langKey = lang ?? '';
const index = cachedIndexes.get(langKey);
if (disabled || !indexReady || !index) {
return;
}
if (!query) {
setState({ results: [], fetching: false, error: false });
return;
}
//@ts-ignore - Typing is wrong here, tags can be arrays when using the `tag` filter option
const rawResults = index.search(query, {
enrich: true,
limit: 5,
suggest: true,
...(filterSiteSpaceIds
? {
tag: {
siteSpaceId: filterSiteSpaceIds,
},
}
: {}),
});
// Flatten and deduplicate results across fields (flexsearch returns one array per indexed field)
const seen = new Set<string>();
const results: LocalPageResult[] = [];
for (const fieldResult of rawResults) {
for (const item of fieldResult.result) {
const doc = (item as { id: string; doc: IndexPage }).doc;
const cacheKey = `${doc.siteSpaceId}:${doc.id}`;
if (!seen.has(cacheKey)) {
seen.add(cacheKey);
const extra = cachedPageData.get(cacheKey);
results.push({
type: 'local-page',
id: doc.id,
siteSpaceId: doc.siteSpaceId,
title: doc.title,
pathname: extra?.pathname ?? '',
icon: extra?.icon,
emoji: extra?.emoji,
description: (doc.description as string | null) ?? undefined,
breadcrumbs: extra?.breadcrumbs,
});
}
}
}
setState({ results, fetching: false, error: false });
}, [query, lang, filterSiteSpaceIds, indexReady, disabled]);
return state;
}
@@ -10,10 +10,7 @@ import {
import React from 'react';
import type { LinkProps } from '../primitives';
import { type SearchPassStore, createSearchPassStore } from './search-pass-store';
import { createSearchPrewarmer } from './search-prewarm';
import { useSearchPrewarm } from './useSearchPrewarm';
import type { DirectSearchProps } from '@/lib/search-results';
export type SearchScope =
/** Search all content on the site */
@@ -52,7 +49,6 @@ export type UpdateSearchState = (
const SetSearchStateContext = React.createContext<UpdateSearchState | undefined>(undefined);
const SearchStateContext = React.createContext<SearchState | null | undefined>(undefined);
const SearchPassContext = React.createContext<SearchPassStore | null>(null);
/**
* Normalize the raw state to handle legacy formats.
@@ -77,9 +73,9 @@ export function shouldKeepSearchState(
}
export function SearchContextProvider(
props: React.PropsWithChildren<{ prewarmURL: string; directSearch?: DirectSearchProps }>
props: React.PropsWithChildren<{ prewarmURL: string }>
): React.ReactElement {
const { children, prewarmURL, directSearch } = props;
const { children, prewarmURL } = props;
// URL-backed state
const [rawState, setRawState] = useQueryStates(keyMap, {
@@ -105,12 +101,6 @@ export function SearchContextProvider(
useSearchPrewarm(Boolean(state?.open), prewarmURL);
const searchPass = React.useMemo(() => createSearchPassStore(directSearch), [directSearch]);
const passRequester = React.useMemo(() => createSearchPrewarmer(false), []);
React.useEffect(() => {
passRequester.update(Boolean(state?.open), searchPass.requestPass);
}, [state?.open, searchPass, passRequester]);
const stateRef = React.useRef(state);
React.useLayoutEffect(() => {
stateRef.current = state;
@@ -146,18 +136,12 @@ export function SearchContextProvider(
return (
<SearchStateContext.Provider value={state}>
<SetSearchStateContext.Provider value={setState}>
<SearchPassContext.Provider value={searchPass}>
{children}
</SearchPassContext.Provider>
{children}
</SetSearchStateContext.Provider>
</SearchStateContext.Provider>
);
}
export function useSearchPass() {
return React.useContext(SearchPassContext);
}
export function useSetSearchState() {
const setState = React.useContext(SetSearchStateContext);
if (setState === undefined) {
@@ -73,101 +73,17 @@ function useFilteredSiteSpaceIds(props: {
);
}
/** Edits that complete a query rather than continue typing it. */
const COMPLETING_INPUT_TYPES = new Set([
'insertFromPaste',
'insertFromDrop',
'insertReplacementText',
'insertFromYank',
'insertFromComposition',
]);
/**
* Read the intent of each edit from the native input event: completed edits are sent without the
* idle delay and a typed word boundary sends the words so far. IME composition text is searched
* like typing; committing it sends at once.
*/
function useSearchInputIntent() {
const immediateQueryRef = React.useRef<string | null>(null);
const flushRef = React.useRef<() => void>(() => {});
const consumeImmediate = React.useCallback((query: string) => {
const immediate = immediateQueryRef.current === query;
immediateQueryRef.current = null;
return immediate;
}, []);
const onInput = React.useCallback((event: React.FormEvent<HTMLInputElement>) => {
const native = event.nativeEvent as InputEvent;
if (native.isComposing) {
return;
}
const query = event.currentTarget.value.trim();
if (COMPLETING_INPUT_TYPES.has(native.inputType)) {
immediateQueryRef.current = query;
} else if (
native.inputType === 'insertText' &&
native.data &&
/^\s+$/.test(native.data) &&
query
) {
// A typed space leaves the trimmed query unchanged, so send the pending words now.
flushRef.current();
}
}, []);
const onCompositionEnd = React.useCallback(
(event: React.CompositionEvent<HTMLInputElement>) => {
// The committed text is usually already the query, so send its pending request now.
immediateQueryRef.current = event.currentTarget.value.trim();
flushRef.current();
},
[]
);
return {
consumeImmediate,
flushRef,
inputHandlers: { onInput, onCompositionEnd },
};
}
function useSearchKeyboardNavigation(props: {
query: string;
results: ReturnType<typeof useSearchResults>['results'];
fetching: boolean;
error: boolean;
isOpen: boolean;
requestKey: string;
flush: () => void;
resultsRef: React.RefObject<SearchResultsRef | null>;
abort: () => void;
askCount: number;
onAskSelect: (index: number) => void;
}) {
const {
const { query, results, resultsRef, abort, askCount, onAskSelect } = props;
const { cursor, moveBy: moveCursorBy } = useSearchResultsCursor({
query,
results,
fetching,
error,
isOpen,
requestKey,
flush,
resultsRef,
abort,
askCount,
onAskSelect,
} = props;
// Enter pressed before the answer arrived: open the top result of this exact query and scope,
// or Ask when that answer is empty. Closing the search cancels it.
const pendingOpenRef = React.useRef<string | null>(null);
const {
cursor,
setCursor,
moveBy: moveCursorBy,
} = useSearchResultsCursor({
query,
fetching,
resultCount: results.length,
totalCount: results.length + askCount,
});
@@ -176,11 +92,9 @@ function useSearchKeyboardNavigation(props: {
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'ArrowUp') {
event.preventDefault();
pendingOpenRef.current = null;
moveCursorBy(-1);
} else if (event.key === 'ArrowDown') {
event.preventDefault();
pendingOpenRef.current = null;
moveCursorBy(1);
} else if (event.key === 'Enter' && !isComposingKeyEvent(event)) {
event.preventDefault();
@@ -192,65 +106,21 @@ function useSearchKeyboardNavigation(props: {
if (resultsRef.current?.select()) {
// Stop any in-flight search request only when activating a result.
abort();
return;
}
if (query && fetching) {
pendingOpenRef.current = requestKey;
flush();
}
}
},
[
moveCursorBy,
cursor,
results.length,
onAskSelect,
resultsRef,
abort,
query,
fetching,
requestKey,
flush,
]
[moveCursorBy, cursor, results.length, onAskSelect, resultsRef, abort]
);
React.useEffect(() => {
const pending = pendingOpenRef.current;
if (pending === null) {
return;
}
if (!isOpen || pending !== requestKey) {
pendingOpenRef.current = null;
return;
}
if (fetching) {
return;
}
pendingOpenRef.current = null;
if (results.length > 0) {
if (resultsRef.current?.selectFirst()) {
abort();
}
} else if (!error && askCount > 0) {
onAskSelect(0);
}
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
return {
cursor,
setCursor,
onInputKeyDown,
};
}
export function useSearchController(
props: SearchBaseProps,
options: {
restoreLastQueryOnMount?: boolean;
/** False for a container the current viewport hides, so only the shown one sends searches. */
requestsEnabled?: boolean;
} = {}
options: { restoreLastQueryOnMount?: boolean } = {}
) {
const {
asEmbeddable,
@@ -262,6 +132,7 @@ export function useSearchController(
withSections,
siteSpaces,
searchURL,
indexURL,
} = props;
const { assistants, config } = useAI();
@@ -378,10 +249,10 @@ export function useSearchController(
});
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
const { results, fetching, error, abort } = useSearchResults({
asEmbeddable,
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
disabled: !(normalizedQuery || withAI),
open: Boolean(state?.open),
query: normalizedQuery,
siteSpaceId: siteSpace.id,
siteSpaceIds,
@@ -389,10 +260,10 @@ export function useSearchController(
scope: state?.scope ?? 'default',
suggestions: config.suggestions,
searchURL,
indexURL,
lang: siteSpace.space.language,
withSections,
consumeImmediate,
});
flushRef.current = flush;
const searchValue =
state?.query ?? (askIsSearchQuery ? state?.ask : null) ?? lastSearchQuery ?? '';
@@ -432,15 +303,9 @@ export function useSearchController(
const askCount = normalizedQuery && !showAsk ? assistants.length : 0;
const { cursor, setCursor, onInputKeyDown } = useSearchKeyboardNavigation({
const { cursor, onInputKeyDown } = useSearchKeyboardNavigation({
query: normalizedQuery,
results,
fetching,
error,
// A container that hides on this viewport drops its pending Enter.
isOpen: Boolean(state?.open) && options.requestsEnabled !== false,
requestKey,
flush,
resultsRef,
abort,
askCount,
@@ -459,7 +324,6 @@ export function useSearchController(
open: onOpen,
close: onClose,
onResultSelect,
onResultHover: setCursor,
query: normalizedQuery,
results,
resultsId: searchResultsId,
@@ -468,7 +332,6 @@ export function useSearchController(
setQuery,
state,
onInputKeyDown,
inputHandlers,
showAsk,
withAI,
withSearchAI,
@@ -8,22 +8,26 @@ import {
createRecommendedQuestionResult,
getEmptySearchResults,
} from './empty-search-results';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import { computeFilterSiteSpaceIds } from './filter';
import { useRecentSearchQueries } from './recent-queries';
import { type MergedPageResult, fuseSearchResults } from './reciprocalRankFusion';
import { computeRemoteSearchScope } from './remote-scope';
import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store';
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
import { streamRecommendedQuestions } from './server-actions';
import { type SearchScope, useSearchPass } from './useSearch';
import { type LocalPageResult, useLocalSearchResults } from './useLocalSearchResults';
import type { SearchScope } from './useSearch';
import { useAI } from '@/components/AI';
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
export type ResultType =
| OrderedComputedResult
| LocalPageResult
| MergedPageResult
| RecommendedQuestionResult;
type RemoteSearchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
| { status: 'error' };
export type { LocalPageResult, MergedPageResult };
// Small helper extracted for unit testing of scope → local filter mapping
// computeFilterSiteSpaceIds is imported from './filter' for testability
/**
* We cache the recommended questions globally to avoid calling the API multiple times
@@ -36,6 +40,8 @@ const cachedRecommendedQuestions: Map<string, RecommendedQuestionResult[]> = new
export function useSearchResults(props: {
asEmbeddable?: boolean;
disabled: boolean;
/** Whether the search surface is open. Gates building the local search index. */
open: boolean;
query: string;
siteSpaceId: string;
siteSpaceIds: string[];
@@ -44,14 +50,17 @@ export function useSearchResults(props: {
suggestions?: string[];
/** URL for the search API route (e.g. from linker.toPathInSpace('~gitbook/search')). */
searchURL: string;
/** Whether the site has multiple sections. If false, the default scope only shows the current site space. */
/** URL for the local index JSON (e.g. from linker.toPathInSite('~gitbook/site-index')). */
indexURL: string;
/** BCP-47 language code of the current site space, used to filter local search results. */
lang?: string;
/** Whether the site has multiple sections. If false, treat default scope as current for local filtering. */
withSections?: boolean;
/** Returns true when the latest edit completed the query (paste, IME commit), so it is sent without the idle delay. */
consumeImmediate?: (query: string) => boolean;
}) {
const {
asEmbeddable,
disabled,
open,
query,
siteSpaceId,
siteSpaceIds,
@@ -59,12 +68,12 @@ export function useSearchResults(props: {
scope,
suggestions,
searchURL,
indexURL,
lang,
withSections,
consumeImmediate,
} = props;
const trackEvent = useTrackEvent();
const searchPass = useSearchPass();
const filterSiteSpaceIds = React.useMemo(
() =>
@@ -78,21 +87,24 @@ export function useSearchResults(props: {
[scope, siteSpaceId, siteSpaceIds, withSections, selectedSectionSiteSpaceIds]
);
const remoteScope = React.useMemo(
() =>
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
);
// Identifies the answer the UI needs now; an answer for any other key is never shown as current.
const requestKey = JSON.stringify([query, remoteScope]);
const { results: localResults } = useLocalSearchResults({
query,
indexURL,
lang,
disabled,
open,
filterSiteSpaceIds,
});
const [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
const [remoteState, setRemoteState] = React.useState<{
results: OrderedComputedResult[];
fetching: boolean;
error: boolean;
}>({ results: [], fetching: false, error: false });
// Track the current in-flight fetch so it can be aborted imperatively
// when the user navigates away before the request completes.
const abortRef = React.useRef<(() => void) | null>(null);
// Sends the pending request now instead of waiting for the idle delay.
const flushRef = React.useRef<(() => void) | null>(null);
const { assistants } = useAI();
const withAI = assistants.length > 0;
@@ -104,7 +116,11 @@ export function useSearchResults(props: {
}
if (!query) {
if (!withAI) {
setRemoteState({ status: 'idle' });
setRemoteState({
results: [],
fetching: false,
error: false,
});
return;
}
@@ -115,11 +131,19 @@ export function useSearchResults(props: {
`Cached recommended questions should be set for site-space ${siteSpaceId}`
);
// Recommended questions are stored as ResultType[] already
setRemoteState({ status: 'idle' });
setRemoteState({
results: [],
fetching: false,
error: false,
});
return;
}
setRemoteState({ status: 'idle' });
setRemoteState({
results: [],
fetching: false,
error: false,
});
let cancelled = false;
@@ -132,7 +156,11 @@ export function useSearchResults(props: {
suggestions.forEach((question) => {
questions.add(question);
});
setRemoteState({ status: 'idle' });
setRemoteState({
results: [],
fetching: false,
error: false,
});
return;
}
@@ -158,7 +186,11 @@ export function useSearchResults(props: {
if (!cancelled) {
// Recommended questions are handled via a separate path below
setRemoteState({ status: 'idle' });
setRemoteState({
results: [],
fetching: false,
error: false,
});
}
}
}, 100);
@@ -168,25 +200,28 @@ export function useSearchResults(props: {
clearTimeout(timeout);
};
}
setRemoteState({ status: 'loading' });
setRemoteState({
results: [],
fetching: true,
error: false,
});
let cancelled = false;
const abortController = new AbortController();
const send = async () => {
flushRef.current = null;
const timeout = setTimeout(async () => {
const fetchSearch = (
scope: Parameters<typeof fetchSearchResults>[1]
): Promise<OrderedComputedResult[]> =>
fetchSearchResults(
searchURL,
scope,
query,
abortController.signal,
asEmbeddable,
searchPass
);
fetchSearchResults(searchURL, scope, query, abortController.signal, asEmbeddable);
try {
const resultsPromise = fetchSearch(remoteScope);
const resultsPromise = fetchSearch(
computeRemoteSearchScope(
scope,
siteSpaceId,
siteSpaceIds,
selectedSectionSiteSpaceIds
)
);
const onResults = (results: OrderedComputedResult[]) => {
if (cancelled) {
@@ -195,34 +230,38 @@ export function useSearchResults(props: {
if (!results) {
// Can happen when the route cannot be found and returns the page's html.
setRemoteState({ status: 'error' });
setRemoteState((prev) => ({ ...prev, error: true }));
return;
}
setRemoteState({ status: 'ready', requestKey, results });
setRemoteState((prev) => ({ ...prev, results }));
trackEvent({ type: 'search_type_query', query });
};
const onError = () => {
if (cancelled) {
return;
}
setRemoteState({ status: 'error' });
setRemoteState((prev) => ({ ...prev, error: true }));
};
await resultsPromise.then(onResults, onError);
if (cancelled) {
return;
}
setRemoteState((prev) => ({ ...prev, fetching: false }));
} catch {
// If there is an error, we need to catch it to avoid infinite loading state.
if (cancelled) {
return;
}
setRemoteState({ status: 'error' });
setRemoteState({
results: [],
fetching: false,
error: true,
});
}
};
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 150);
flushRef.current = () => {
clearTimeout(timeout);
void send();
};
}, 200);
abortRef.current = () => {
cancelled = true;
@@ -235,33 +274,29 @@ export function useSearchResults(props: {
clearTimeout(timeout);
abortController.abort();
abortRef.current = null;
flushRef.current = null;
};
}, [
query,
remoteScope,
requestKey,
scope,
trackEvent,
withAI,
siteSpaceId,
siteSpaceIds,
selectedSectionSiteSpaceIds,
disabled,
suggestions,
searchURL,
asEmbeddable,
consumeImmediate,
searchPass,
]);
const flush = React.useCallback(() => {
flushRef.current?.();
}, []);
const abort = React.useCallback(() => {
abortRef.current?.();
abortRef.current = null;
setRemoteState((prev) => (prev.status === 'loading' ? { status: 'idle' } : prev));
setRemoteState((prev) => (prev.fetching ? { ...prev, fetching: false } : prev));
}, []);
// Merge local and remote results.
// Re-runs immediately whenever either result set changes.
const results = React.useMemo<ResultType[]>(() => {
if (!query) {
const recommendedQuestions =
@@ -278,12 +313,15 @@ export function useSearchResults(props: {
});
}
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
: [];
return fuseSearchResults({
localResults,
remoteResults: remoteState.results,
query,
allowedSiteSpaceIds: filterSiteSpaceIds,
});
}, [
remoteState,
requestKey,
localResults,
remoteState.results,
query,
filterSiteSpaceIds,
withAI,
@@ -292,46 +330,27 @@ export function useSearchResults(props: {
recentQueries,
]);
// Between a query change and its loading state, the previous answer must still read as loading.
const isOutdated = remoteState.status === 'ready' && remoteState.requestKey !== requestKey;
return {
results,
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
error: remoteState.status === 'error',
requestKey,
flush,
fetching: remoteState.fetching,
error: remoteState.error,
abort,
};
}
/**
* Fetch search results from the search API with a search pass, or else from the search API route.
* Fetch search results from the search API route.
*/
async function fetchSearchResults(
searchURL: string,
scope: SearchSiteContentScope,
query: string,
signal: AbortSignal,
asEmbeddable: boolean | undefined,
searchPass: SearchPassStore | null
signal?: AbortSignal,
asEmbeddable?: boolean
): Promise<OrderedComputedResult[]> {
const direct = await searchPass?.search({
query,
scope,
signal,
asEmbeddable: Boolean(asEmbeddable),
});
if (direct?.type === 'results') {
return direct.results;
}
const response = await fetch(searchURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(direct?.reason ? { [SEARCH_FALLBACK_HEADER]: direct.reason } : {}),
},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
asEmbeddable,
query,
@@ -2,12 +2,11 @@ import React from 'react';
export function useSearchResultsCursor(props: {
query: string;
fetching: boolean;
resultCount: number;
totalCount: number;
}) {
const [cursor, setCursor] = React.useState<number | null>(null);
const { query, fetching, resultCount, totalCount } = props;
const { query, resultCount, totalCount } = props;
React.useEffect(() => {
if (!query) {
@@ -17,12 +16,6 @@ export function useSearchResultsCursor(props: {
}, [query]);
React.useEffect(() => {
if (fetching && resultCount === 0) {
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
setCursor(null);
return;
}
if (totalCount === 0) {
return;
}
@@ -34,7 +27,7 @@ export function useSearchResultsCursor(props: {
return prev ?? 0;
});
}, [fetching, resultCount, totalCount]);
}, [resultCount, totalCount]);
React.useEffect(() => {
setCursor((prev) => {
@@ -1,17 +0,0 @@
import type { GitBookSiteContext } from '@/lib/context';
import { getLLMsTxtURL } from '@/lib/llms-directive';
/**
* Agent-facing pointer to the site index and the Markdown versions of pages.
*/
export function LLMsTxtDirective(props: { context: GitBookSiteContext }) {
const { context } = props;
return (
<div className="sr-only">
For the complete documentation index, see <a href={getLLMsTxtURL(context)}>llms.txt</a>.
Markdown versions of documentation pages are available by appending <code>.md</code> to
page URLs.
</div>
);
}
@@ -6,13 +6,11 @@ import * as ReactDOM from 'react-dom';
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
import { AIContextProvider } from '../AI';
import { LLMsTxtDirective } from './LLMsTxtDirective';
import { RocketLoaderDetector } from './RocketLoaderDetector';
import { SiteLayoutClientContexts } from './SiteLayoutClientContexts';
import { AdminToolbar } from '@/components/AdminToolbar';
import { CookiesToast } from '@/components/Cookies';
import { LoadIntegrations } from '@/components/Integrations';
import { getDirectSearchProps } from '@/components/Search/search-props';
import { SpaceLayout } from '@/components/SpaceLayout';
import { WebMCP } from '@/components/WebMCP/WebMCP';
import type { VisitorAuthClaims } from '@/lib/adaptive';
@@ -22,7 +20,6 @@ import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@
import { getResizedImageURL } from '@/lib/images';
import { removeTrailingSlash } from '@/lib/paths';
import { isSiteIndexable } from '@/lib/seo';
import { getOpenSearchURL } from '@/routes/opensearch';
// Pure trackers with no visitor-facing UI, safe to load after `load` + idle. Anything not
// listed (consent managers, chats, assistants…) keeps loading eagerly.
@@ -74,6 +71,17 @@ export async function SiteLayout(props: {
}
});
// Start the search-index download from the HTML itself. `crossOrigin` must match the
// client `fetch()` (cors + same-origin credentials) or the preload is ignored and the
// index downloads twice — the omission was exactly that bug before.
// Low priority: it's only needed once search opens and must not compete with the LCP.
ReactDOM.preload(`${context.linker.siteBasePath}~gitbook/site-index`, {
as: 'fetch',
type: 'application/json',
crossOrigin: 'anonymous',
fetchPriority: 'low',
});
scripts.forEach(({ script }) => {
if (!isDeferrableScript(script)) {
ReactDOM.preload(script, {
@@ -83,72 +91,61 @@ export async function SiteLayout(props: {
});
return (
<>
{/* First in <body> so agents reading the HTML find it before the navigation. */}
<LLMsTxtDirective context={context} />
<link
rel="search"
type="application/opensearchdescription+xml"
href={getOpenSearchURL(context)}
title={context.site.title}
/>
<SiteLayoutClientContexts
contextId={context.contextId}
forcedTheme={
forcedTheme ??
// Only force concrete light/dark; System stays unforced so next-themes resolves prefers-color-scheme pre-paint (avoids the flash). A theme saved while the toggle was previously on still wins — see the PR's "Known limitation". RND-11643
(customization.themes.toggeable ||
customization.themes.default === CustomizationDefaultThemeMode.System
? undefined
: customization.themes.default)
}
defaultTheme={customization.themes.default}
externalLinksTarget={customization.externalLinks.target}
proxyOrigin={context.site.proxy?.origin}
siteURL={removeTrailingSlash(
context.linker.toAbsoluteURL(context.linker.toPathInSite(''))
)}
searchPrewarmURL={context.linker.toPathInSite('~gitbook/search-prewarm')}
directSearch={getDirectSearchProps(context)}
<SiteLayoutClientContexts
contextId={context.contextId}
forcedTheme={
forcedTheme ??
// Only force concrete light/dark; System stays unforced so next-themes resolves prefers-color-scheme pre-paint (avoids the flash). A theme saved while the toggle was previously on still wins — see the PR's "Known limitation". RND-11643
(customization.themes.toggeable ||
customization.themes.default === CustomizationDefaultThemeMode.System
? undefined
: customization.themes.default)
}
defaultTheme={customization.themes.default}
externalLinksTarget={customization.externalLinks.target}
proxyOrigin={context.site.proxy?.origin}
siteURL={removeTrailingSlash(
context.linker.toAbsoluteURL(context.linker.toPathInSite(''))
)}
searchPrewarmURL={context.linker.toPathInSite('~gitbook/search-prewarm')}
>
<AIContextProvider
aiMode={customization.ai?.mode}
suggestions={context.customization.ai?.suggestions}
trademark={customization.trademark.enabled}
greeting={aiGreeting ? { subtitle: aiGreeting } : undefined}
>
<AIContextProvider
aiMode={customization.ai?.mode}
suggestions={context.customization.ai?.suggestions}
trademark={customization.trademark.enabled}
greeting={aiGreeting ? { subtitle: aiGreeting } : undefined}
<SpaceLayout
context={context}
withTracking={withTracking}
visitorAuthClaims={visitorAuthClaims}
>
<SpaceLayout
context={context}
withTracking={withTracking}
visitorAuthClaims={visitorAuthClaims}
>
{children}
</SpaceLayout>
</AIContextProvider>
{children}
</SpaceLayout>
</AIContextProvider>
<LoadIntegrations />
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
) : null}
{scripts.map(({ script }) =>
isDeferrableScript(script) ? (
<Script key={script} src={script} strategy="lazyOnload" />
) : (
<script key={script} async src={script} />
)
)}
<LoadIntegrations />
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
) : null}
{scripts.map(({ script }) =>
isDeferrableScript(script) ? (
<Script key={script} src={script} strategy="lazyOnload" />
) : (
<script key={script} async src={script} />
)
)}
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
<React.Suspense fallback={null}>
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
</React.Suspense>
) : null}
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
<React.Suspense fallback={null}>
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
</React.Suspense>
) : null}
<RocketLoaderDetector />
<RocketLoaderDetector />
<AdminToolbar context={context} />
</SiteLayoutClientContexts>
</>
<AdminToolbar context={context} />
</SiteLayoutClientContexts>
);
}
@@ -13,7 +13,6 @@ import { LinkContext, type LinkContextType } from '../primitives';
import { SearchContextProvider } from '../Search';
import { SelectProvider } from '../Select';
import { isExternalLink } from '../utils/link';
import type { DirectSearchProps } from '@/lib/search-results';
/**
* Client component context providers for the site layout.
@@ -28,7 +27,6 @@ export function SiteLayoutClientContexts(props: {
/** Absolute URL of the site, so same-site absolute links render as internal on the server. */
siteURL?: string;
searchPrewarmURL: string;
directSearch: DirectSearchProps | undefined;
children: React.ReactNode;
}) {
const {
@@ -41,7 +39,6 @@ export function SiteLayoutClientContexts(props: {
proxyOrigin,
siteURL,
searchPrewarmURL,
directSearch,
} = props;
useClearRouterCache(contextId);
@@ -75,10 +72,7 @@ export function SiteLayoutClientContexts(props: {
<NuqsAdapter>
<SelectProvider>
<LinkContext.Provider value={linkContext}>
<SearchContextProvider
prewarmURL={searchPrewarmURL}
directSearch={directSearch}
>
<SearchContextProvider prewarmURL={searchPrewarmURL}>
<ReducedMotionProvider>{children}</ReducedMotionProvider>
</SearchContextProvider>
</LinkContext.Provider>
@@ -70,8 +70,8 @@ export function SitePageNotFound() {
return;
}
// Otherwise, rank the site's pages against the path that 404'd. The site index is
// CDN-cached, so this adds no origin request — see getRelatedPages.
// Otherwise, rank the site's pages against the path that 404'd. We reuse the search index
// (already preloaded and CDN-cached), so this adds no origin request — see getRelatedPages.
let active = true;
getRelatedPages(siteIndexURL, pathname ?? '', siteSpaceId).then(
(pages) => {
@@ -224,7 +224,7 @@ function NotFoundSuggestions(props: { suggestions: RelatedPage[] | null }) {
<h2 className="font-heading font-medium text-tint">
{t(language, 'notfound_suggestions_title')}
</h2>
<ul className="flex flex-col gap-2" aria-busy={loading}>
<ul className="flex flex-col gap-2">
{loading ? (
<SkeletonList items={RELATED_PAGES_COUNT} className="my-0.75 max-w-md" />
) : (
@@ -261,8 +261,9 @@ function NotFoundSuggestions(props: { suggestions: RelatedPage[] | null }) {
/**
* Return the pages whose path is closest to the one that 404'd.
*
* Rather than asking the server (which would mean an extra origin request per 404), this reads
* the CDN-cached page index served at `~gitbook/site-index`.
* Rather than asking the server (which would mean an extra request per 404), this reuses the
* search index served at `~gitbook/site-index` — preloaded on every page and shared with
* instant search via the module cache in `site-index.ts`, so at most one request is made.
* The ranking is a lighter, client-side cousin of `getSimilarPages` (which the Markdown 404
* runs server-side from the full page tree).
*/
@@ -70,7 +70,7 @@ export function useIsLoggedInVisitor() {
}
/**
* Return the URL of the site page index (`~gitbook/site-index`).
* Return the URL of the site search index (`~gitbook/site-index`).
*/
export function useSiteIndexURL() {
const context = React.useContext(SpaceLayoutContext);
@@ -9,14 +9,6 @@ export function TableOfContentsScript() {
useEffect(() => {
const root = document.documentElement;
// Older Chrome (e.g. 130) emits a mutation record even when the value is unchanged,
// which would make the observer below re-trigger itself forever.
const setRootProperty = (name: string, value: string) => {
if (root.style.getPropertyValue(name) !== value) {
root.style.setProperty(name, value);
}
};
// Calculate and set TOC dimensions
const updateTocLayout = () => {
// Get key elements
@@ -50,8 +42,8 @@ export function TableOfContentsScript() {
}
// Update height
setRootProperty('--toc-height', `${Math.max(height, 0)}px`);
setRootProperty('--toc-top-offset', `${Math.max(offset, 0)}px`);
root.style.setProperty('--toc-height', `${Math.max(height, 0)}px`);
root.style.setProperty('--toc-top-offset', `${Math.max(offset, 0)}px`);
// Subtract visible pageCover (if any)
if (
@@ -72,8 +64,8 @@ export function TableOfContentsScript() {
}
}
setRootProperty('--outline-height', `${Math.max(height, 0)}px`);
setRootProperty('--outline-top-offset', `${Math.max(offset, 0)}px`);
root.style.setProperty('--outline-height', `${Math.max(height, 0)}px`);
root.style.setProperty('--outline-top-offset', `${Math.max(offset, 0)}px`);
};
// Initial update
@@ -84,15 +76,8 @@ export function TableOfContentsScript() {
window.addEventListener('resize', updateTocLayout, { passive: true });
// Use MutationObserver for DOM changes
let pendingFrame: number | null = null;
const observer = new MutationObserver(() => {
if (pendingFrame !== null) {
return;
}
pendingFrame = requestAnimationFrame(() => {
pendingFrame = null;
updateTocLayout();
});
requestAnimationFrame(updateTocLayout);
});
// Only observe what matters
@@ -104,9 +89,6 @@ export function TableOfContentsScript() {
return () => {
observer.disconnect();
if (pendingFrame !== null) {
cancelAnimationFrame(pendingFrame);
}
window.removeEventListener('scroll', updateTocLayout);
window.removeEventListener('resize', updateTocLayout);
};
@@ -11,4 +11,3 @@ export * from './useListOverflow';
export * from './useCurrentPageMetadata';
export * from './useBackToSpace';
export * from './useCopyToClipboard';
export * from './useResizeObserver';
@@ -1,29 +0,0 @@
'use client';
import * as React from 'react';
/**
* Call `onResize` once the element is mounted and again whenever its size changes. Browsers
* without `ResizeObserver` get the first call only.
*/
export function useResizeObserver(ref: React.RefObject<HTMLElement | null>, onResize: () => void) {
const callback = React.useRef(onResize);
React.useLayoutEffect(() => {
callback.current = onResize;
});
React.useLayoutEffect(() => {
const element = ref.current;
if (!element) {
return;
}
const run = () => callback.current();
run();
if (typeof ResizeObserver === 'undefined') {
return;
}
const observer = new ResizeObserver(run);
observer.observe(element);
return () => observer.disconnect();
}, [ref]);
}
@@ -206,6 +206,7 @@ export const Input = React.forwardRef<InputElement, InputProps>((props, passedRe
event.preventDefault();
handleSubmit();
} else if (event.key === 'Escape') {
event.preventDefault();
event.currentTarget.blur();
}
};
@@ -22,23 +22,19 @@ export type ScrollContainerProps = {
orientation: 'horizontal' | 'vertical';
leading?: {
/** Whether to fade out the leading edge of the container, over 1rem or 3rem (`long`). */
fade: boolean | 'long';
/** Whether to fade out the leading edge of the container. */
fade: boolean;
/** Whether to show a button to scroll back. */
button: boolean | ButtonProps;
/** Show the button whenever the container can scroll back, not only on hover. */
buttonAlwaysVisible?: boolean;
/** Optional class(es) to apply when there the container can be scrolled on the leading (left or top) edge */
className?: string;
};
trailing?: {
/** Whether to fade out the trailing edge of the container, over 1rem or 6rem (`long`). */
fade: boolean | 'long';
/** Whether to fade out the trailing edge of the container. */
fade: boolean;
/** Whether to show a button to scroll forward. */
button: boolean | ButtonProps;
/** Show the button whenever the container can scroll forward, not only on hover. */
buttonAlwaysVisible?: boolean;
/** Optional class(es) to apply when there the container can be scrolled on the trailing (right or bottom) edge */
className?: string;
};
@@ -194,21 +190,13 @@ export function ScrollContainer(props: ScrollContainerProps) {
orientation === 'horizontal' ? 'overflow-x-scroll' : 'flex-col overflow-y-auto',
leading.fade && scrollPosition > 0
? orientation === 'horizontal'
? leading.fade === 'long'
? 'mask-l-from-[calc(100%-3rem)]'
: 'mask-l-from-[calc(100%-1rem)]'
: leading.fade === 'long'
? 'mask-t-from-[calc(100%-3rem)]'
: 'mask-t-from-[calc(100%-1rem)]'
? 'mask-l-from-[calc(100%-1rem)]'
: 'mask-t-from-[calc(100%-1rem)]'
: '',
trailing.fade && scrollPosition < scrollSize
? orientation === 'horizontal'
? trailing.fade === 'long'
? 'mask-r-from-[calc(100%-6rem)]'
: 'mask-r-from-[calc(100%-1rem)]'
: trailing.fade === 'long'
? 'mask-b-from-[calc(100%-6rem)]'
: 'mask-b-from-[calc(100%-1rem)]'
? 'mask-r-from-[calc(100%-1rem)]'
: 'mask-b-from-[calc(100%-1rem)]'
: '',
contentClassName
)}
@@ -235,9 +223,7 @@ export function ScrollContainer(props: ScrollContainerProps) {
: '-translate-x-1/2! top-0 left-1/2 mt-2',
'absolute z-10 not-pointer-none:block hidden scale-0 opacity-0 transition-[scale,opacity]',
scrollPosition > 0
? leading.buttonAlwaysVisible
? 'not-pointer-none:scale-100 not-pointer-none:opacity-11'
: 'not-pointer-none:group-hover/scroll-container:scale-100 not-pointer-none:group-hover/scroll-container:opacity-11'
? 'not-pointer-none:group-hover/scroll-container:scale-100 not-pointer-none:group-hover/scroll-container:opacity-11'
: 'pointer-events-none',
typeof leading.button === 'object' ? leading.button.className : ''
)}
@@ -260,9 +246,7 @@ export function ScrollContainer(props: ScrollContainerProps) {
: '-translate-x-1/2! bottom-0 left-1/2 mb-2',
'absolute z-10 not-pointer-none:block hidden scale-0 transition-[scale,opacity]',
scrollPosition < scrollSize
? trailing.buttonAlwaysVisible
? 'not-pointer-none:scale-100 not-pointer-none:opacity-11'
: 'not-pointer-none:group-hover/scroll-container:scale-100 not-pointer-none:group-hover/scroll-container:opacity-11'
? 'not-pointer-none:group-hover/scroll-container:scale-100 not-pointer-none:group-hover/scroll-container:opacity-11'
: 'pointer-events-none',
typeof trailing.button === 'object' ? trailing.button.className : ''
)}
@@ -176,7 +176,6 @@ function ZoomImageModal(props: {
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
onClose();
}
};
@@ -43,6 +43,7 @@ export const ar: TranslationLanguage = {
search_ask_no_answer:
'تعذر العثور على إجابة لسؤالك. يمكنك محاولة إعادة صياغته أو جعله أكثر تحديدا.',
search_ask_error: 'حدث خطأ ما. يرجى المحاولة مرة أخرى لاحقا.',
search_partial_error: 'تعذر تحميل بعض النتائج. يتم عرض النتائج المتاحة.',
on_this_page: 'في هذه الصفحة',
next_page: 'التالي',
previous_page: 'السابق',
@@ -43,6 +43,8 @@ export const bg: TranslationLanguage = {
search_ask_no_answer:
'Не беше намерен отговор на въпроса ви. Можете да опитате да го преформулирате или да бъдете по-конкретни.',
search_ask_error: 'Нещо се обърка. Моля, опитайте отново по-късно.',
search_partial_error:
'Някои резултати не можаха да се заредят. Показват се наличните резултати.',
on_this_page: 'На тази страница',
next_page: 'Следваща',
previous_page: 'Предишна',
@@ -43,6 +43,7 @@ export const cs: TranslationLanguage = {
search_ask_no_answer:
'Na vaši otázku se nepodařilo najít odpověď. Zkuste ji přeformulovat nebo být konkrétnější.',
search_ask_error: 'Něco se pokazilo. Zkuste to prosím znovu později.',
search_partial_error: 'Některé výsledky se nepodařilo načíst. Zobrazují se dostupné výsledky.',
on_this_page: 'Na této stránce',
next_page: 'Další',
previous_page: 'Předchozí',
@@ -43,6 +43,7 @@ export const da: TranslationLanguage = {
search_ask_no_answer:
'Der kunne ikke findes et svar på dit spørgsmål. Prøv at omformulere det eller være mere specifik.',
search_ask_error: 'Noget gik galt. Prøv igen senere.',
search_partial_error: 'Nogle resultater kunne ikke indlæses. Viser tilgængelige resultater.',
on_this_page: 'På denne side',
next_page: 'Næste',
previous_page: 'Forrige',
@@ -44,6 +44,8 @@ export const de: TranslationLanguage = {
search_ask_no_answer:
'Es konnte keine Antwort auf Ihre Frage gefunden werden. Versuchen Sie, sie umzuformulieren oder genauer zu sein.',
search_ask_error: 'Etwas ist schief gelaufen. Bitte versuchen Sie es später noch einmal.',
search_partial_error:
'Einige Ergebnisse konnten nicht geladen werden. Verfügbare Ergebnisse werden angezeigt.',
on_this_page: 'Auf dieser Seite',
next_page: 'Nächste',
previous_page: 'Vorherige',
@@ -43,6 +43,8 @@ export const el: TranslationLanguage = {
search_ask_no_answer:
'Δεν ήταν δυνατή η εύρεση απάντησης στην ερώτησή σας. Δοκιμάστε να τη διατυπώσετε διαφορετικά ή πιο συγκεκριμένα.',
search_ask_error: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά αργότερα.',
search_partial_error:
'Δεν ήταν δυνατή η φόρτωση ορισμένων αποτελεσμάτων. Εμφανίζονται τα διαθέσιμα αποτελέσματα.',
on_this_page: 'Σε αυτήν τη σελίδα',
next_page: 'Επόμενη',
previous_page: 'Προηγούμενη',
@@ -41,6 +41,7 @@ export const en = {
search_ask_no_answer:
'An answer could not be found for your question. You could try rephrasing it, or be more specific.',
search_ask_error: 'Something went wrong. Please try again later.',
search_partial_error: "Some results couldn't load. Showing available results.",
on_this_page: 'On this page',
next_page: 'Next',
previous_page: 'Previous',
@@ -44,6 +44,8 @@ export const es: TranslationLanguage = {
search_ask_no_answer:
'No se pudo encontrar una respuesta para su pregunta. Puede intentar reformularla o ser más específico.',
search_ask_error: 'Algo salió mal. Por favor, inténtalo de nuevo más tarde.',
search_partial_error:
'No se pudieron cargar algunos resultados. Se muestran los resultados disponibles.',
on_this_page: 'En esta página',
next_page: 'Siguiente',
previous_page: 'Anterior',
@@ -43,6 +43,7 @@ export const et: TranslationLanguage = {
search_ask_no_answer:
'Teie küsimusele ei leitud vastust. Proovige seda ümber sõnastada või olla täpsem.',
search_ask_error: 'Midagi läks valesti. Palun proovige hiljem uuesti.',
search_partial_error: 'Mõnda tulemust ei saanud laadida. Kuvatakse saadaolevad tulemused.',
on_this_page: 'Sellel lehel',
next_page: 'Järgmine',
previous_page: 'Eelmine',
@@ -43,6 +43,8 @@ export const fi: TranslationLanguage = {
search_ask_no_answer:
'Kysymykseesi ei löytynyt vastausta. Voit yrittää muotoilla sen uudelleen tai olla tarkempi.',
search_ask_error: 'Jokin meni pieleen. Yritä myöhemmin uudelleen.',
search_partial_error:
'Joitakin tuloksia ei voitu ladata. Näytetään saatavilla olevat tulokset.',
on_this_page: 'Tällä sivulla',
next_page: 'Seuraava',
previous_page: 'Edellinen',
@@ -43,6 +43,8 @@ export const fr: TranslationLanguage = {
search_ask_sources_no_answer: 'Pages associées',
search_ask_no_answer: 'Pas de réponse trouvée. Essayez de reformuler votre question.',
search_ask_error: 'Une erreur est survenue. Veuillez réessayer plus tard.',
search_partial_error:
'Certains résultats n’ont pas pu être chargés. Les résultats disponibles sont affichés.',
on_this_page: 'Sur cette page',
next_page: 'Suivant',
previous_page: 'Précédent',
@@ -43,6 +43,7 @@ export const he: TranslationLanguage = {
search_ask_no_answer:
'לא נמצאה תשובה לשאלה שלך. אפשר לנסות לנסח אותה מחדש או להיות מדויקים יותר.',
search_ask_error: 'משהו השתבש. נסה שוב מאוחר יותר.',
search_partial_error: 'לא ניתן היה לטעון חלק מהתוצאות. מוצגות התוצאות הזמינות.',
on_this_page: 'בדף הזה',
next_page: 'הבא',
previous_page: 'הקודם',

Some files were not shown because too many files have changed in this diff Show More