Compare commits

..

5 Commits

Author SHA1 Message Date
Nicolas Dorseuil 5c50ba2d5d Show Try it headers and query parameters as Scalar-style tables
Declared query parameters and headers appear prefilled in their own
tables, optional ones unchecked until the reader types or ticks them,
with a default Accept header and room to add rows. Booleans get a
true/false dropdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:05:35 +01:00
Nicolas Dorseuil 84ba78bd4d Scope saved Try it values by resolved server hosts
Raw server templates like {host}/v1 made unrelated APIs share a scope,
and so their saved tokens. Resolve variables first, and share nothing
when no server resolves to a concrete host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:27:46 +01:00
Nicolas Dorseuil 5d60c2a7c7 Remember Try it values per API and allow extra headers and query parameters
Reopening Try it no longer starts over: values stay for the page's
lifetime, in memory only, scoped by the API's server origins so a token
is never sent to another API. Readers can also add headers and query
parameters the spec doesn't declare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:26:00 +01:00
Nicolas Dorseuil bca0b711d8 changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:54:20 +01:00
Nicolas Dorseuil ea375ecefc Replace the Scalar API client with a lightweight Try it panel
The Test it button loaded a 9 MB Vue runtime (6.3 MB over the wire) to
send one request. The new panel is ~7 KB gzipped, lazy-loaded, and
built from the operation GitBook already renders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:54:20 +01:00
195 changed files with 4105 additions and 6008 deletions
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Handle optional emoji and icon values when rendering tags.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Point agents to the site MCP server from Markdown pages, the page HTML, llms.txt and llms-full.txt.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Serve the site AI Catalog as specification version 0.9, with identifiers in its `urn:air:{publisher}:{name}:{kind}` format.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump @opennextjs/aws to 4.2.1 and @opennextjs/cloudflare to 1.20.19.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Retry direct site search on the site's own domain after a network error or timeout.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Name a site's MCP server as docs, such as "Acme Docs MCP Server", in AI clients and in the install commands and links, so it is not confused with a product's own MCP server.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce the wait after typing in site search to 100 ms.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published pages available when an integration block needs its connection or settings checked.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published site search results visible while visitors refine a query.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Apply the default language-aware search scope to legacy search links.
+6
View File
@@ -0,0 +1,6 @@
---
"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
---
Count only MCP tool calls in the MCP request insights event.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer GET requests to the MCP endpoint with an `Allow: POST` header.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Support MCP protocol version 2025-11-25 on published site MCP servers.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published revision URLs out of search results.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render a page's search keywords in its metadata.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Track the displayed position and search request ID when a visitor opens a search result.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Update the GitBook API SDK for site revision responses.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix wide content in Updates blocks overflowing into the page outline.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Paginate published Updates pages with more than 50 entries into 20-entry pages.
+155 -634
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -48,8 +48,7 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.214.0",
"@scalar/api-client-react": "^1.3.46",
"@gitbook/api": "0.210.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"assert-never": "^1.4.0",
+5
View File
@@ -443,6 +443,11 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://help.openloyalty.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'retrozia.gitbook.io/retrozia',
contentBaseURL: 'https://retrozia.gitbook.io',
tests: [{ name: 'Home', url: '/retrozia' }],
},
{
name: 'helpcenter.channable.com',
contentBaseURL: 'https://helpcenter.channable.com',
+3 -69
View File
@@ -442,48 +442,6 @@ const searchTestCases: Test[] = [
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
},
},
{
name: 'Search - Enter opens the visible result while a new query loads',
url: `blocks/lists${getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
})}`,
screenshot: false,
run: async (page) => {
await waitForHydration(page);
const heldSearch = await holdSearchRequests(page);
const searchInput = page.getByTestId('search-input');
const searchPopup = page.getByTestId('search-popover');
await searchInput.focus();
await page.waitForURL(/[?&]q=/);
await searchInput.pressSequentially('gitbook');
const initialSearch = await heldSearch('gitbook');
const { siteSpaceId } = initialSearch.request().postDataJSON().scope;
const topResult = searchPageResult(
initialSearch,
siteSpaceId,
'Headings',
'blocks/headings'
);
await initialSearch.fulfill({ json: [topResult] });
const firstResult = searchPopup.getByTestId('search-page-result').first();
await expect(firstResult).toHaveAttribute('href', topResult.href);
await searchInput.pressSequentially(' docs');
const pendingSearch = await heldSearch('gitbook docs');
await expect(searchPopup.locator('output[aria-busy="true"]')).toBeVisible();
await expect(firstResult).toHaveAttribute('href', topResult.href);
await expect(searchPopup.locator('[data-search-placeholder-row]')).toHaveCount(0);
await searchInput.press('Enter');
await expect(searchPopup).toBeHidden();
await expect
.poll(() => new URL(page.url()).pathname)
.toBe(new URL(topResult.href, page.url()).pathname);
await pendingSearch.abort().catch(() => {});
},
},
{
name: 'Search - Enter opens the result under the mouse',
url: `blocks/lists${getCustomizationURL({
@@ -781,7 +739,7 @@ const searchPassTestCases: Test[] = [
},
},
{
name: 'Dropped API request: search uses the site proxy before falling back to the route',
name: 'Dropped API request: the search falls back to the route after its time limit',
url: '',
screenshot: false,
run: async (page) => {
@@ -791,18 +749,6 @@ const searchPassTestCases: Test[] = [
await page.route(SEARCH_API_URL, (route) => {
apiCalls.push(route.request());
});
const proxyCalls: Request[] = [];
await page.route(
/\/~gitbook\/search-direct\/orgs\/[^/]+\/sites\/[^/]+$/,
async (route) => {
proxyCalls.push(route.request());
if (proxyCalls.length === 1) {
await route.fulfill({ json: { items: [SEARCH_PASS_RECORD] } });
return;
}
await route.fulfill({ status: 502 });
}
);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
@@ -810,24 +756,12 @@ const searchPassTestCases: Test[] = [
await typeSearch(page, 'gitbook');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await page.clock.fastForward(5_000);
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
expect(routeSearches).toHaveLength(0);
expect((await proxyCalls[0]?.allHeaders())?.['x-gitbook-search-pass']).toBe(
'test-search-pass-1'
);
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('502');
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('timeout');
expect((await routeSearches[0]?.response())?.status()).toBe(200);
await typeSearch(page, ' blocks');
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
expect(proxyCalls).toHaveLength(2);
expect(apiCalls).toHaveLength(1);
},
},
+7 -8
View File
@@ -19,9 +19,9 @@
"@gitbook/react-math": "workspace:*",
"@gitbook/react-openapi": "workspace:*",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"@modelcontextprotocol/sdk": "1.26.0",
"@opennextjs/aws": "4.2.1",
"@opennextjs/cloudflare": "1.20.19",
"@modelcontextprotocol/sdk": "1.17.5",
"@opennextjs/aws": "4.1.16",
"@opennextjs/cloudflare": "1.20.17",
"@panzoom/panzoom": "^4.6.1",
"@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1",
@@ -40,7 +40,7 @@
"jsontoxml": "^1.0.1",
"jwt-decode": "^4.0.0",
"leven": "^4.1.0",
"mcp-handler": "^1.1.0",
"mcp-handler": "^1.0.2",
"mdast-util-from-markdown": "^2.0.2",
"mdast-util-frontmatter": "^2.0.1",
"mdast-util-gfm": "^3.1.0",
@@ -82,14 +82,13 @@
"url-join": "^5.0.0",
"usehooks-ts": "catalog:",
"warn-once": "^0.1.1",
"zod": "^3.25",
"zod": "^3",
"zod-to-json-schema": "^3.25.1",
"zustand": "^5.0.3"
},
"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",
@@ -119,9 +118,9 @@
},
"scripts": {
"generate": "./scripts/generate.sh",
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:assets": "bun ./scripts/generate-mermaid-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/scalar && 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/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",
@@ -1,81 +0,0 @@
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 });
@@ -1 +0,0 @@
export { ApiClientModalProvider, useApiClientModal } from '@scalar/api-client-react';
@@ -1,54 +0,0 @@
import type { Metadata, Viewport } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
} from '@/components/SitePage';
import { parseUpdatesPageParam } from '@/lib/updates-url';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return (
<SitePage
context={context}
pageParams={{ pathname }}
staticRoute={false}
updatesPage={updatesPage}
/>
);
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getDynamicSiteContext(await props.params);
return generateSitePageViewport(context);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({
context,
pageParams: { pathname },
updatesPage,
});
}
@@ -1,41 +0,0 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
import { getEmbeddableDynamicContext } from '@/lib/embeddable';
import { parseUpdatesPageParam } from '@/lib/updates-url';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableDynamicContext(params);
const pathname = getPagePathFromParams(params);
return (
<EmbeddableDocsPage
context={context}
pageParams={{ pathname }}
staticRoute={false}
updatesPage={updatesPage}
/>
);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableDynamicContext(params);
const pathname = getPagePathFromParams(params);
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
}
@@ -19,37 +19,28 @@ export async function handleMcpRequest(
return new Response('Not Found', { status: 404 });
}
// The server is stateless, so it has no notification stream for a GET to open. `Allow` tells
// clients to stop asking, as the Streamable HTTP transport expects.
if (rawRequest.method === 'GET') {
return new Response('Method Not Allowed', { status: 405, headers: { Allow: 'POST' } });
}
// Next.js request.url is the original URL and not the rewritten one from the middleware
const requestURL = new URL(context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint)));
requestURL.search = rawRequest.nextUrl.search;
const request = new Request(requestURL, rawRequest);
trackMcpEvent({
organizationId: context.organizationId,
siteId: context.site.id,
events: [
{
type: 'mcp_request',
location: {
displayContext: SiteInsightsDisplayContext.Server,
},
},
],
request,
});
const mcpHandler = createMcpHandler(
(server) => {
registerSiteMcpTools(server, createSiteMcpTools(context, { request }), {
// Connecting, listing tools and notifications are protocol overhead, several
// requests per client session: only tool calls count as usage.
onToolCall: () =>
trackMcpEvent({
organizationId: context.organizationId,
siteId: context.site.id,
events: [
{
type: 'mcp_request',
location: {
displayContext: SiteInsightsDisplayContext.Server,
},
},
],
request,
}),
});
registerSiteMcpTools(server, createSiteMcpTools(context, { request }));
},
{
// The same identity the server card republishes, so the card and the handshake agree.
@@ -2,8 +2,7 @@ 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 type { SiteURLData } from '@/lib/context';
import { type SearchRouteReason, throwIfDataError } from '@/lib/data';
import { throwIfDataError } from '@/lib/data';
import { getLogger } from '@/lib/logger';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { transformSitePageResult } from '@/lib/search';
@@ -15,8 +14,7 @@ const SEARCH_FALLBACK_REASON =
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope, searchId } =
(await request.json()) as SearchSiteContentRequest;
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
const [context, siteURLData] = await Promise.all([
getServerActionBaseContext({ isEmbeddable: asEmbeddable }),
getSiteURLDataFromMiddleware(),
@@ -42,8 +40,6 @@ export async function POST(request: NextRequest) {
siteId: siteURLData.site,
query,
scope,
searchId,
routeReason: getSearchRouteReason(siteURLData, fallback),
})
),
throwIfDataError(
@@ -92,38 +88,3 @@ export async function POST(request: NextRequest) {
return NextResponse.json(results);
}
function getSearchRouteReason(
siteURLData: SiteURLData,
fallback: string | null
): SearchRouteReason {
if (siteURLData.changeRequest) {
return 'change_request';
}
if (siteURLData.revision) {
return 'revision';
}
if (siteURLData.preview) {
return 'preview';
}
switch (fallback) {
case null:
case 'expired':
case 'pass_request':
return 'no_pass';
case '401':
case '403':
case '429':
case 'network':
case 'timeout':
case 'invalid':
case 'unknown_space':
return `fallback:${fallback}`;
default:
if (/^5\d{2}$/.test(fallback)) {
return 'fallback:5xx';
}
return /^\d{3}$/.test(fallback) ? 'fallback:http' : 'unknown';
}
}
@@ -1,56 +0,0 @@
import type { Metadata, Viewport } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
} from '@/components/SitePage';
import { parseUpdatesPageParam } from '@/lib/updates-url';
export const dynamic = 'force-static';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params);
return (
<SitePage
context={context}
pageParams={{ pathname }}
staticRoute
updatesPage={updatesPage}
/>
);
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getStaticSiteContext(await props.params);
return generateSitePageViewport(context);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({
context,
pageParams: { pathname },
updatesPage,
});
}
@@ -1,43 +0,0 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
import { getEmbeddableStaticContext } from '@/lib/embeddable';
import { parseUpdatesPageParam } from '@/lib/updates-url';
export const dynamic = 'force-static';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableStaticContext(params);
const pathname = getPagePathFromParams(params);
return (
<EmbeddableDocsPage
context={context}
pageParams={{ pathname }}
staticRoute
updatesPage={updatesPage}
/>
);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableStaticContext(params);
const pathname = getPagePathFromParams(params);
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
}
@@ -14,11 +14,6 @@ export async function hasContentBeenUpdated(props: { revisionId: string }) {
const context = await getServerActionBaseContext();
const siteURLData = await getSiteURLDataFromMiddleware();
// A site revision never changes what it shows.
if (siteURLData.siteRevision) {
return false;
}
if (siteURLData.changeRequest) {
const changeRequest = await getDataOrNull(
context.dataFetcher.getChangeRequest({
@@ -1,5 +1,4 @@
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { ContentKitOutput } from '@gitbook/react-contentkit';
import type { BlockProps } from '../Block';
@@ -54,7 +53,6 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
{
integrationName: block.data.integration,
request: initialInput,
allowFailedDependency: true,
}
);
@@ -68,29 +66,12 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
// Integration output can render blocks with generated keys.
{...getCommentAnchorProps(context, block.key)}
{...getCommentMarkerProps(context, 'data-comment-block')}
role="note"
className={tcls(
'flex items-start gap-3 p-4 text-sm',
'rounded-corners:rounded-md circular-corners:rounded-xl',
'bg-warning border-warning text-neutral-strong',
style
)}
className={tcls(style)}
>
<Icon
icon="circle-exclamation"
className="mt-0.5 size-4 shrink-0 text-warning-subtle contrast-more:text-warning"
aria-hidden="true"
/>
<div className="wrap-anywhere min-w-0">
<p className="font-medium">
Could not load the {block.data.integration} integration
</p>
<p>
{initialResponse.error.code === 424
? 'Ask an administrator to check its connection and settings.'
: initialResponse.error.message}
</p>
</div>
<pre>
Unexpected error with integration {block.data.integration}:{' '}
{initialResponse.error.message}
</pre>
</div>
);
}
@@ -11,11 +11,9 @@ export async function fetchSafeIntegrationUI(
{
integrationName,
request,
allowFailedDependency = false,
}: {
integrationName: string;
request: RenderIntegrationUI;
allowFailedDependency?: boolean;
}
) {
const output = await ignoreDataFetcherErrors(
@@ -29,7 +27,6 @@ export async function fetchSafeIntegrationUI(
404, // Integration has been uninstalled
400, // Integration is rejecting its own request
422, // Integration is triggering an invalid request, failing at the validation step
...(allowFailedDependency ? [424] : []),
502, // Integration is failing in an unexpected way
]
);
@@ -38,7 +38,6 @@ export type OpenAPIBlockClientContextProps = {
/** Rendered on the server: both go through the async document pipeline. */
headingNode: React.ReactNode;
descriptionNode: React.ReactNode;
scalarRuntimeURL: string;
};
type OpenAPIBlockVariant =
@@ -70,7 +69,6 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
renderDocument: () => descriptionNode,
renderHeading: () => headingNode,
resolveProxyUrl: proxyUrl ? () => proxyUrl : undefined,
scalarRuntimeURL: props.scalarRuntimeURL,
};
switch (props.variant) {
@@ -6,7 +6,6 @@ import {
type OpenAPISchemasData,
type OpenAPIWebhookData,
checkIsValidLocale,
extractOrigin,
getAllServerOrigins,
getOperationTitle,
getSchemasHeading,
@@ -17,9 +16,7 @@ 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';
@@ -124,7 +121,6 @@ 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,
@@ -145,7 +141,7 @@ export function getOpenAPIBlockClientProps(args: {
expandAllModelSections?: boolean;
headless?: boolean;
}): OpenAPIBlockClientContextProps {
const { props, data, schemas, specUrl, context } = args;
const { props, data, schemas, context } = args;
const serverContext = getOpenAPIContext(args);
const { renderCodeBlock, renderDocument, renderHeading, resolveProxyUrl, ...serializable } =
serverContext;
@@ -158,10 +154,6 @@ 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,
@@ -1 +0,0 @@
export const SCALAR_RUNTIME_PATH = 'scalar/scalar-api-client@1.3.46.mjs';
@@ -1,360 +0,0 @@
/* 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 './scalar.css';
@import './tryit.css';
/* Layout Components */
.openapi-operation,
@@ -0,0 +1,244 @@
@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;
}
@@ -1,384 +0,0 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import { useHash, scrollToHash } from '../hooks';
import { CONTENT_STYLE_REDUCED, MAIN_CONTENT_ID } from '../layout';
import { Button, SkeletonUpdate, SuspenseLoadedHint } from '../primitives';
import { UpdatesFilterContext, applyTagFilterAttribute, areTagsEqual } from './UpdatesFilter';
import { UpdatesFilterScript } from './UpdatesFilterScript';
import {
type FilteredUpdatesPageResult,
getFilteredUpdatesPage,
resolveUpdatesAnchor,
} from './UpdatesServerActions';
import { tString, useLanguage } from '@/intl/client';
import {
UPDATES_FILTER_KEY_ATTR,
UPDATES_FILTER_SEARCH_PARAM,
type UpdatesPageRange,
getUpdatesPageRange,
normalizeUpdatesFilterTags,
updatesFilterStyleKey,
} from '@/lib/updates';
import {
UPDATES_PAGE_SEARCH_PARAM,
parseUpdatesPageParam,
setUpdatesPageParam,
} from '@/lib/updates-url';
const PENDING_FILTER_ATTR = 'data-updates-pending-filter';
export const HIDE_PENDING_UPDATES = '[html[data-updates-pending-filter]_&]:hidden';
type FilteredPage = Extract<FilteredUpdatesPageResult, { status: 'ok' }>;
type UpdatesView =
| { status: 'unfiltered'; pagination: UpdatesPageRange }
| { status: 'loading'; pagination: UpdatesPageRange | null }
| { status: 'error'; pagination: null }
| ({ status: 'filtered' } & Omit<FilteredPage, 'status'>);
type UpdatesSelection = { tags: string[]; page: number };
const PaginatedUpdatesContext = React.createContext<{
view: UpdatesView;
goToPage: (page: number) => void;
retry: () => void;
} | null>(null);
export function PaginatedUpdatesProvider(props: {
pageId: string;
revisionId: string;
isEmbeddable: boolean;
tagSlugs: string[];
initialPagination: UpdatesPageRange;
children: React.ReactNode;
}) {
const { pageId, revisionId, isEmbeddable, tagSlugs, initialPagination, children } = props;
const router = useRouter();
const searchParams = useSearchParams();
const hash = useHash();
const availableTags = React.useMemo(() => new Set(tagSlugs), [tagSlugs]);
const styleKey = updatesFilterStyleKey(tagSlugs);
const [selectedTags, setSelectedTags] = React.useState<string[]>([]);
const [view, setView] = React.useState<UpdatesView>({
status: 'unfiltered',
pagination: initialPagination,
});
const selection = React.useRef<UpdatesSelection>({ tags: [], page: initialPagination.page });
const hasNewerRevision = React.useRef(false);
const requestId = React.useRef(0);
React.useLayoutEffect(() => {
document.documentElement.setAttribute(UPDATES_FILTER_KEY_ATTR, styleKey);
return () => {
requestId.current++;
document.documentElement.removeAttribute(UPDATES_FILTER_KEY_ATTR);
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
applyTagFilterAttribute([]);
};
}, [styleKey]);
const syncLocation = React.useCallback(
(force = false) => {
const url = new URL(window.location.href);
const { tags, page } = getUpdatesSelection(url, availableTags);
const previous = selection.current;
const sameTags = areTagsEqual(tags, previous.tags);
if (!force && sameTags && page === previous.page) {
return;
}
const id = ++requestId.current;
selection.current = { tags, page };
setSelectedTags(tags);
applyTagFilterAttribute(tags);
if (!tags.length) {
if (page !== initialPagination.page) {
setView({ status: 'loading', pagination: null });
router.replace(relativeURL(url));
return;
}
if (hasNewerRevision.current) {
setView({ status: 'loading', pagination: null });
window.location.replace(relativeURL(url));
return;
}
setView({ status: 'unfiltered', pagination: initialPagination });
return;
}
setView((current) => {
let pagination = null;
if (sameTags && current.pagination) {
pagination = getUpdatesPageRange(page, current.pagination.totalItems);
}
return { status: 'loading', pagination };
});
async function load() {
let result: FilteredUpdatesPageResult = { status: 'error' };
try {
result = await getFilteredUpdatesPage({ pageId, tags, page, isEmbeddable });
} catch {
// Network or aborted action leaves the filter selected so the reader can retry.
}
const currentURL = new URL(window.location.href);
const selected = getUpdatesSelection(currentURL, availableTags);
if (
id !== requestId.current ||
currentURL.pathname !== url.pathname ||
selected.page !== page ||
!areTagsEqual(selected.tags, tags)
) {
return;
}
if (result.status === 'error') {
setView({ status: 'error', pagination: null });
return;
}
if (result.revisionId !== revisionId) {
hasNewerRevision.current = true;
}
if (result.status === 'unfiltered') {
const fallback = currentURL;
fallback.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
setUpdatesPageParam(fallback.searchParams, initialPagination.page);
window.history.replaceState(null, '', relativeURL(fallback));
selection.current = { tags: [], page: initialPagination.page };
setSelectedTags([]);
applyTagFilterAttribute([]);
if (hasNewerRevision.current) {
setView({ status: 'loading', pagination: null });
window.location.replace(relativeURL(fallback));
return;
}
setView({ status: 'unfiltered', pagination: initialPagination });
return;
}
if (result.pagination.isClamped) {
const clamped = currentURL;
setUpdatesPageParam(clamped.searchParams, result.pagination.page);
window.history.replaceState(null, '', relativeURL(clamped));
selection.current = { tags, page: result.pagination.page };
}
setView({
status: 'filtered',
revisionId: result.revisionId,
content: result.content,
sections: result.sections,
pagination: result.pagination,
});
}
void load();
},
[availableTags, pageId, revisionId, initialPagination, isEmbeddable, router]
);
React.useLayoutEffect(() => {
syncLocation();
}, [searchParams, syncLocation]);
React.useEffect(() => {
const onPopState = () => syncLocation();
window.addEventListener('popstate', onPopState);
return () => {
window.removeEventListener('popstate', onPopState);
};
}, [syncLocation]);
React.useLayoutEffect(() => {
if (view.status !== 'loading') {
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
}
}, [view]);
React.useEffect(() => {
if (
view.status === 'loading' ||
view.status === 'error' ||
(view.status === 'unfiltered' && selection.current.tags.length > 0)
) {
return;
}
let active = true;
async function resolveHash() {
const url = new URL(window.location.href);
const anchorHash = url.hash;
if (!anchorHash || scrollToHash(anchorHash.slice(1))) {
return;
}
let anchor: string;
try {
anchor = decodeURIComponent(anchorHash.slice(1));
} catch {
return;
}
const id = requestId.current;
const { tags } = selection.current;
try {
const result = await resolveUpdatesAnchor({ pageId, anchor, tags, isEmbeddable });
if (
!active ||
!result.found ||
id !== requestId.current ||
url.href !== window.location.href
) {
return;
}
setUpdatesPageParam(url.searchParams, result.page);
if (result.clearTags) {
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
}
if (url.href !== window.location.href) {
router.replace(relativeURL(url));
}
} catch {
// An unresolved hash should leave the visitor on the current page.
}
}
void resolveHash();
window.addEventListener('hashchange', resolveHash);
return () => {
active = false;
window.removeEventListener('hashchange', resolveHash);
};
}, [hash, isEmbeddable, pageId, router, view]);
function navigate(tags: string[], page: number, history: 'push' | 'replace') {
const url = new URL(window.location.href);
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
for (const tag of tags) {
url.searchParams.append(UPDATES_FILTER_SEARCH_PARAM, tag);
}
setUpdatesPageParam(url.searchParams, page);
url.hash = '';
if (tags.length === 0 && (page !== initialPagination.page || hasNewerRevision.current)) {
requestId.current++;
selection.current = { tags, page };
setSelectedTags(tags);
applyTagFilterAttribute(tags);
setView({ status: 'loading', pagination: null });
if (hasNewerRevision.current) {
window.location.replace(relativeURL(url));
} else {
router.replace(relativeURL(url));
}
return;
}
if (history === 'push') {
window.history.pushState(null, '', relativeURL(url));
} else {
window.history.replaceState(null, '', relativeURL(url));
}
syncLocation();
const main = document.getElementById(MAIN_CONTENT_ID);
if (main) {
main.scrollIntoView({ block: 'start', behavior: 'instant' });
main.focus({ preventScroll: true });
}
}
function toggleTag(tag: string) {
const { tags } = selection.current;
if (tags.includes(tag)) {
navigate(
tags.filter((selected) => selected !== tag),
1,
'replace'
);
return;
}
navigate(normalizeUpdatesFilterTags([...tags, tag], availableTags), 1, 'replace');
}
return (
<UpdatesFilterContext.Provider
value={{
selectedTags,
selectedTagSet: new Set(selectedTags),
toggleTag,
clearTags: () => navigate([], 1, 'replace'),
}}
>
<PaginatedUpdatesContext.Provider
value={{
view,
goToPage: (page) => navigate(selection.current.tags, page, 'push'),
retry: () => syncLocation(true),
}}
>
{tagSlugs.length > 0 && (
<UpdatesFilterScript
tagSlugs={tagSlugs}
filterAttribute={PENDING_FILTER_ATTR}
/>
)}
{children}
</PaginatedUpdatesContext.Provider>
</UpdatesFilterContext.Provider>
);
}
export function usePaginatedUpdates() {
return React.useContext(PaginatedUpdatesContext);
}
export function PaginatedUpdatesBody(props: { children: React.ReactNode }) {
const updates = usePaginatedUpdates();
const language = useLanguage();
if (updates?.view.status === 'loading') {
return <SkeletonUpdate className={CONTENT_STYLE_REDUCED} />;
}
if (updates?.view.status === 'error') {
return (
<div
role="alert"
className={`${CONTENT_STYLE_REDUCED} flex items-center justify-between gap-4 rounded-lg border border-tint-subtle p-4 text-sm text-tint`}
>
<span>{tString(language, 'unexpected_error')}</span>
<Button
variant="secondary"
size="small"
label={tString(language, 'unexpected_error_retry')}
onClick={updates.retry}
/>
</div>
);
}
if (updates?.view.status === 'filtered') {
return (
<div className="contents" data-content-ref-root="">
<SuspenseLoadedHint />
{updates.view.content}
</div>
);
}
return <div className={`contents ${HIDE_PENDING_UPDATES}`}>{props.children}</div>;
}
function getUpdatesSelection(url: URL, availableTags: ReadonlySet<string>): UpdatesSelection {
return {
tags: normalizeUpdatesFilterTags(
url.searchParams.getAll(UPDATES_FILTER_SEARCH_PARAM),
availableTags
),
page: parseUpdatesPageParam(url.searchParams.get(UPDATES_PAGE_SEARCH_PARAM)) ?? 1,
};
}
function relativeURL(url: URL): string {
return `${url.pathname}${url.search}${url.hash}`;
}
@@ -75,7 +75,7 @@ export function Update(props: BlockProps<DocumentBlockUpdate>) {
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style="flex min-w-0 flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
style="flex flex-1 flex-col [&>*+*]:mt-5 [&>*:first-child]:!pt-0"
/>
</FilteredUpdate>
);
@@ -36,7 +36,7 @@ const emptyUpdatesFilterContext: UpdatesFilterContextValue = {
clearTags: () => {},
};
export const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
export function UpdatesFilterProvider(props: { tagSlugs: string[]; children: React.ReactNode }) {
const { tagSlugs, children } = props;
@@ -249,12 +249,12 @@ function TagChip(props: { tag: RevisionTag; onToggle: (tag: string) => void }) {
);
}
export function areTagsEqual(left: string[], right: string[]): boolean {
function areTagsEqual(left: string[], right: string[]): boolean {
return left.length === right.length && left.every((tag, index) => tag === right[index]);
}
/** Mirrors the active filter onto `<html>`, matching what the pre-paint script does on first load. */
export function applyTagFilterAttribute(tags: string[]) {
function applyTagFilterAttribute(tags: string[]) {
if (typeof document === 'undefined') {
return;
}
@@ -58,12 +58,12 @@ export function applyUpdatesFilterScript(
* Inline script that applies the URL's `?tag=` filter to `<html>` before first paint. Rendered only
* on pages with filterable updates (see SitePage), not globally.
*/
export function UpdatesFilterScript(props: { tagSlugs: string[]; filterAttribute?: string }) {
const { tagSlugs, filterAttribute = UPDATES_TAG_FILTER_ATTR } = props;
export function UpdatesFilterScript(props: { tagSlugs: string[] }) {
const { tagSlugs } = props;
const inserted = useRef(false);
const scriptArgs = serializeUpdatesFilterScriptArgs([
UPDATES_FILTER_SEARCH_PARAM,
filterAttribute,
UPDATES_TAG_FILTER_ATTR,
UPDATES_TAG_FILTER_CAP,
tagSlugs,
UPDATES_FILTER_KEY_ATTR,
@@ -1,90 +0,0 @@
'use client';
import { useSearchParams } from 'next/navigation';
import { Icon } from '@gitbook/icons';
import { CONTENT_STYLE_REDUCED } from '../layout';
import { Button } from '../primitives';
import { HIDE_PENDING_UPDATES, usePaginatedUpdates } from './PaginatedUpdates';
import { tString } from '@/intl/translate';
import type { TranslationLanguage } from '@/intl/translations';
import { tcls } from '@/lib/tailwind';
import {
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_MAX_PAGE,
setUpdatesPageParam,
} from '@/lib/updates-url';
export function UpdatesPagination(props: { language: TranslationLanguage; baseHref: string }) {
const { language, baseHref } = props;
const updates = usePaginatedUpdates();
const searchParams = useSearchParams();
if (!updates?.view.pagination || updates.view.pagination.totalPages <= 1) {
return null;
}
const { view, goToPage } = updates;
const { page, totalPages, totalItems, start, end } = updates.view.pagination;
const number = new Intl.NumberFormat(language.locale);
const previousLabel = tString(language, 'previous_page');
const nextLabel = tString(language, 'next_page');
function buttonProps(targetPage: number, rel: 'prev' | 'next') {
if (view.status !== 'unfiltered') {
return { onClick: () => goToPage(targetPage) };
}
const params = new URLSearchParams(searchParams?.toString());
params.delete(UPDATES_FILTER_SEARCH_PARAM);
setUpdatesPageParam(params, targetPage);
const query = params.toString();
let href = baseHref;
if (query) {
href += `?${query}`;
}
return { href, rel };
}
return (
<div
className={tcls(
CONTENT_STYLE_REDUCED,
'mt-8 flex items-center justify-between gap-2 border-t border-tint-subtle pt-4',
view.status === 'unfiltered' && HIDE_PENDING_UPDATES
)}
>
<div aria-live="polite" className="text-sm text-tint">
{tString(
language,
'updates_pagination_range',
number.format(start),
number.format(end),
number.format(totalItems)
)}
</div>
<nav
aria-label={tString(language, 'updates_pagination_navigation')}
className="flex justify-end gap-2"
>
{page > 1 && (
<Button
variant="blank"
size="small"
icon="chevron-left"
label={previousLabel}
{...buttonProps(page - 1, 'prev')}
/>
)}
{page < totalPages && page < UPDATES_MAX_PAGE && (
<Button
variant="blank"
size="small"
trailing={<Icon icon="chevron-right" className="size-3" />}
label={nextLabel}
{...buttonProps(page + 1, 'next')}
/>
)}
</nav>
</div>
);
}
@@ -1,144 +0,0 @@
'use server';
import type * as React from 'react';
import { IconsProvider } from '@gitbook/icons';
import { PageBodyDocument } from '../PageBody/PageBodyDocument';
import { getPageDocument } from '@/lib/data';
import { getDocumentSections } from '@/lib/document-sections';
import {
getContentInlineIconSourceRequests,
getCustomizationIconStyle,
getInlineIconSources,
} from '@/lib/icons/inline';
import { getLogger } from '@/lib/logger';
import { resolvePageId } from '@/lib/pages';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import {
findUpdateAnchorPage,
getDocumentFilterableTags,
normalizeUpdatesFilterTags,
paginateUpdatesDocument,
} from '@/lib/updates';
import { UPDATES_MAX_PAGE } from '@/lib/updates-url';
type UpdatesPageAction = {
pageId: string;
tags: string[];
isEmbeddable: boolean;
};
export type FilteredUpdatesPageResult =
| {
status: 'ok';
revisionId: string;
content: React.ReactNode;
sections: Awaited<ReturnType<typeof getDocumentSections>>;
pagination: NonNullable<ReturnType<typeof paginateUpdatesDocument>['pagination']>;
}
| {
status: 'unfiltered';
revisionId: string;
}
| {
status: 'error';
};
export async function getFilteredUpdatesPage(
options: UpdatesPageAction & { page: number }
): Promise<FilteredUpdatesPageResult> {
const logger = getLogger().subLogger('updatesPagination');
if (!Number.isInteger(options.page) || options.page < 1 || options.page > UPDATES_MAX_PAGE) {
logger.warn('Invalid filtered updates page number');
return { status: 'error' };
}
try {
const { context, page, document } = await getUpdatesPageDocument(options);
const availableTags = new Set(
getDocumentFilterableTags(document, context.revision).map((tag) => tag.slug)
);
const tags = normalizeUpdatesFilterTags(options.tags, availableTags);
if (!tags.length) {
logger.info('No selected tags on the current revision', { pageId: page.id });
return { status: 'unfiltered', revisionId: context.revisionId };
}
const result = paginateUpdatesDocument(document, context.revision, {
page: options.page,
tags,
});
if (!result.pagination) {
logger.info('Current revision no longer needs updates pagination', { pageId: page.id });
return { status: 'unfiltered', revisionId: context.revisionId };
}
const [sections, iconSources] = await Promise.all([
getDocumentSections(context, result.document),
getInlineIconSources(
getContentInlineIconSourceRequests({
iconStyle: getCustomizationIconStyle(context.customization),
document: result.document,
})
),
]);
logger.info('Rendered filtered updates page', {
siteId: context.site.id,
pageId: page.id,
page: result.pagination.page,
totalItems: result.pagination.totalItems,
totalPages: result.pagination.totalPages,
});
return {
status: 'ok',
revisionId: context.revisionId,
content: (
<IconsProvider iconSources={iconSources}>
<PageBodyDocument context={context} page={page} document={result.document} />
</IconsProvider>
),
sections,
pagination: result.pagination,
};
} catch {
logger.warn('Could not render filtered updates page');
return { status: 'error' };
}
}
export async function resolveUpdatesAnchor(options: UpdatesPageAction & { anchor: string }) {
const logger = getLogger().subLogger('updatesPagination');
try {
const { context, page, document } = await getUpdatesPageDocument(options);
const result = findUpdateAnchorPage(document, context.revision, options);
logger.info('Resolved updates anchor', {
siteId: context.site.id,
pageId: page.id,
found: result.found,
page: result.found && result.page,
});
if (result.found && result.page <= UPDATES_MAX_PAGE) {
return result;
}
} catch {
logger.warn('Could not resolve updates anchor');
}
return { found: false as const };
}
async function getUpdatesPageDocument({ pageId, isEmbeddable }: UpdatesPageAction) {
const context = await fetchServerActionSiteContext(
await getServerActionBaseContext({ isEmbeddable })
);
const target = resolvePageId(context.revision.pages, pageId);
if (!target) {
throw new Error('Updates page not found');
}
const { page } = target;
const document = await getPageDocument(context, page);
if (!document) {
throw new Error('Updates document not found');
}
return { context: { ...context, page }, page, document };
}
@@ -1,9 +1,7 @@
import type { Metadata } from 'next';
import { SiteInsightsDisplayContext } from '@gitbook/api';
import { IconsProvider } from '@gitbook/icons';
import { PaginatedUpdatesProvider } from '../DocumentView/PaginatedUpdates';
import { HeaderMobileMenu } from '../Header/HeaderMobileMenu';
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
import { PageBody } from '../PageBody';
@@ -35,7 +33,6 @@ export const dynamic = 'force-static';
type EmbeddableDocsPageProps = {
context: GitBookSiteContext;
pageParams: PagePathParams;
updatesPage?: number;
};
/**
@@ -44,51 +41,11 @@ type EmbeddableDocsPageProps = {
export async function EmbeddableDocsPage(
props: EmbeddableDocsPageProps & { staticRoute: boolean }
) {
const { context } = props;
const {
page,
document,
ancestors,
withPageFeedback,
contentHasUpdates,
pagination,
pageHref,
filterableTags,
iconSources,
} = await getSitePageData(props);
let updatesBaseHref: string | undefined;
if (pagination) {
updatesBaseHref = pageHref;
}
let pageBody = (
<PageBody
context={context}
page={page}
ancestors={ancestors}
document={document}
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
staticRoute={props.staticRoute}
contentHasUpdates={contentHasUpdates}
updatesBaseHref={updatesBaseHref}
/>
);
if (pagination) {
pageBody = (
<IconsProvider iconSources={iconSources}>
<PaginatedUpdatesProvider
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
pageId={page.id}
revisionId={context.revisionId}
isEmbeddable
tagSlugs={filterableTags.map((tag) => tag.slug)}
initialPagination={pagination}
>
{pageBody}
</PaginatedUpdatesProvider>
</IconsProvider>
);
}
const { context, pageParams } = props;
const { page, document, ancestors, withPageFeedback } = await getSitePageData({
context,
pageParams,
});
const variants = categorizeVariants(context);
@@ -190,7 +147,15 @@ export async function EmbeddableDocsPage(
) : null
}
/>
{pageBody}
<PageBody
context={context}
page={page}
ancestors={ancestors}
document={document}
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
staticRoute={props.staticRoute}
/>
</ScrollContainer>
</EmbeddableFrameBody>
</EmbeddableFrameMain>
@@ -2,8 +2,6 @@
import React from 'react';
import { SiteInsightsDisplayContext } from '@gitbook/api';
import { useTrackEvent } from '../Insights';
import { LinkContext } from '../primitives';
import { useIsVisible } from '../VisibilityContext';
@@ -39,10 +37,9 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
return;
}
trackEvent(
{ type: 'search_open' },
{ pageId: null, displayContext: SiteInsightsDisplayContext.Embed }
);
trackEvent({
type: 'search_open',
});
}, [trackEvent, isVisible]);
const tabsRef = React.useRef<HTMLDivElement>(null);
@@ -59,7 +56,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
query,
results,
resultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -83,7 +79,6 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
query={query}
results={results}
resultsId={resultsId}
resultsQuery={resultsQuery}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
@@ -15,7 +15,6 @@ import { Button } from '@/components/primitives/Button';
import { DropdownMenuItem, useDropdownMenuClose } from '@/components/primitives/DropdownMenu';
import { getURLForLLM } from '@/components/utils';
import { tString, useLanguage } from '@/intl/client';
import { getSiteMcpServerName } from '@/lib/mcp/naming';
type PageActionType = 'button' | 'dropdown-menu-item';
@@ -297,7 +296,7 @@ export function ActionOpenMCP(props: {
const providerInfo = React.useMemo<{ label: string; icon: IconName; url: string }>(() => {
switch (provider) {
case 'vscode': {
const vscodeConfig = { name: getSiteMcpServerName(siteTitle), url: mcpURL };
const vscodeConfig = { name: siteTitle, url: mcpURL };
return {
label: 'VSCode',
icon: 'vscode',
@@ -333,7 +332,7 @@ export function ActionCopyMCPCommand(props: {
const language = useLanguage();
const slug =
getSiteMcpServerName(siteTitle)
siteTitle
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '') || 'docs';
@@ -1,31 +0,0 @@
import type { RevisionPageDocument } from '@gitbook/api';
import { PageActionsDropdown } from './PageActionsDropdown';
import { getPageActionsURLs } from './pageActionsURLs';
import type { GitBookSiteContext } from '@/lib/context';
/**
* Menu of the page actions. It loads what it shows from the context and the page alone, so it can be
* rendered and cached apart from the page body.
*/
export async function PageActionsMenu(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
}) {
const { context, page } = props;
const { linker, revision } = context;
return (
<PageActionsDropdown
siteTitle={context.site.title}
urls={await getPageActionsURLs(context, page)}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
);
}
@@ -1,101 +0,0 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getPageGitMetadata } = await import('./pageActionsData');
const page = {
id: 'page-1',
title: 'Introduction',
kind: 'sheet',
type: 'document',
path: 'readme',
slug: 'readme',
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('getPageGitMetadata', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result).toEqual(git);
});
it('does not fetch Git metadata already on the page', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, { ...page, git });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
@@ -1,63 +0,0 @@
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
const CONFIGURABLE_PAGE_ACTIONS = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
];
/**
* Whether a given built-in page action is enabled.
*/
export function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* Whether any of the configured page actions is enabled. The RSS feed is not part of them: it is
* only offered on pages with an updates block.
*/
export function hasConfiguredPageActions(customization: GitBookSiteContext['customization']) {
return CONFIGURABLE_PAGE_ACTIONS.some((type) => isPageActionEnabled(customization, type));
}
/**
* Get the Git metadata of a page for the Edit on Git action, or nothing when that action is not shown.
*/
export async function getPageGitMetadata(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<RevisionPageDocument['git']> {
if (
!context.space.gitSync?.url ||
!isPageActionEnabled(context.customization, CustomizationPageActionType.Git)
) {
return undefined;
}
if (page.git) {
return page.git;
}
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
return pageWithMetadata?.type === 'document' ? pageWithMetadata.git : undefined;
}
@@ -1,66 +0,0 @@
import urlJoin from 'url-join';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import { getPDFURLSearchParams } from '../PDF';
import { getPageGitMetadata, isPageActionEnabled } from './pageActionsData';
import type { PageActionsDropdownURLs } from './PageActionsDropdown';
import type { GitBookSiteContext } from '@/lib/context';
import { getPageDocument } from '@/lib/data';
import { hasTopLevelBlock } from '@/lib/document';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { getPageRSSURL } from '@/routes/rss';
/**
* Return the URLs for the page actions. The page's Git path and RSS feed are loaded here, so the
* page actions depend on the context and the page alone.
*/
export async function getPageActionsURLs(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<PageActionsDropdownURLs> {
const [document, git] = await Promise.all([
getPageDocument(context, page),
getPageGitMetadata(context, page),
]);
// Update blocks can only be at the top level of the document, so we optimize the check.
const withRSSFeed = document
? hasTopLevelBlock(document, (block) => block.type === 'updates')
: false;
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
const { gitSync } = context.space;
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
gitSync?.url && git
? {
provider: gitSync.installationProvider,
url: urlJoin(gitSync.url, git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -15,7 +15,7 @@ import { PageFeedbackForm } from '../PageFeedback';
import { SideSheet } from '../primitives/SideSheet';
import { ThemeToggler } from '../ThemeToggler';
import { PageAsideCloseButton } from './PageAsideButton';
import { PaginatedScrollSectionsList, ScrollSectionsList } from './ScrollSectionsList';
import { ScrollSectionsList } from './ScrollSectionsList';
import { ScrollToTopButton } from './ScrollToTopButton';
import { getSpaceLanguage, t, tString } from '@/intl/server';
import type { GitBookSiteContext } from '@/lib/context';
@@ -29,7 +29,6 @@ export async function PageAside(props: {
page: RevisionPageDocument;
document: JSONDocument | null;
filterableTags: RevisionTag[];
withUpdatesPagination: boolean;
context: GitBookSiteContext;
withHeaderOffset: { sectionsHeader: boolean; topHeader: boolean };
withFullPageCover: boolean;
@@ -143,11 +142,7 @@ export async function PageAside(props: {
<div className="flex shrink flex-col overflow-hidden">
{document ? (
<React.Suspense fallback={null}>
<PageAsideSections
document={document}
context={context}
withUpdatesPagination={props.withUpdatesPagination}
/>
<PageAsideSections document={document} context={context} />
</React.Suspense>
) : null}
<PageAsideActions page={page} withPageFeedback={withPageFeedback} />
@@ -162,19 +157,11 @@ export async function PageAside(props: {
);
}
async function PageAsideSections(props: {
document: JSONDocument;
context: GitBookSiteContext;
withUpdatesPagination: boolean;
}) {
async function PageAsideSections(props: { document: JSONDocument; context: GitBookSiteContext }) {
const { document, context } = props;
const sections = await getDocumentSections(context, document);
if (props.withUpdatesPagination) {
return <PaginatedScrollSectionsList sections={sections} />;
}
return sections.length > 1 ? (
<div data-gb-page-outline className="overflow-y-auto">
<ScrollSectionsList sections={sections} />
@@ -4,10 +4,6 @@ import React from 'react';
import { OpenAPIMethodBadge } from '@gitbook/react-openapi';
import { HEADER_HEIGHT_DESKTOP } from '../layout';
import {
HIDE_PENDING_UPDATES,
usePaginatedUpdates,
} from '@/components/DocumentView/PaginatedUpdates';
import { useUpdatesFilter } from '@/components/DocumentView/UpdatesFilter';
import { useScrollActiveId } from '@/components/hooks';
import { useBodyLoaded } from '@/components/primitives';
@@ -25,34 +21,6 @@ const SECTION_INTERSECTING_THRESHOLD = 0.9;
*/
const ACTIVE_ITEM_OFFSET = 100;
export function PaginatedScrollSectionsList(props: { sections: DocumentSection[] }) {
const updates = usePaginatedUpdates();
const view = updates?.view;
if (view?.status === 'loading' || view?.status === 'error') {
return null;
}
let sections = props.sections;
if (view?.status === 'filtered') {
sections = view.sections;
}
if (sections.length <= 1) {
return null;
}
return (
<div
data-gb-page-outline
className={tcls(
'overflow-y-auto',
view?.status === 'unfiltered' && HIDE_PENDING_UPDATES
)}
>
<ScrollSectionsList sections={sections} />
</div>
);
}
export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }) {
const { selectedTagSet } = useUpdatesFilter();
const ids = React.useMemo(
@@ -4,9 +4,7 @@ import {
SiteInsightsDisplayContext,
} from '@gitbook/api';
import { DocumentViewSkeleton } from '../DocumentView';
import { PaginatedUpdatesBody } from '../DocumentView/PaginatedUpdates';
import { UpdatesPagination } from '../DocumentView/UpdatesPagination';
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { CurrentPageProvider } from '../hooks/useCurrentPage';
import { TrackPageViewEvent } from '../Insights';
import { CONTENT_STYLE } from '../layout';
@@ -14,7 +12,6 @@ import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative, SuspenseLoadedHint } from '../primitives';
import OptionalSuspense from './OptionalSuspense';
import { PageBodyBlankslate } from './PageBodyBlankslate';
import { PageBodyDocument } from './PageBodyDocument';
import { PageCover } from './PageCover';
import { PageFooterNavigation } from './PageFooterNavigation';
import { PageHeader } from './PageHeader';
@@ -23,11 +20,19 @@ import { MAIN_CONTENT_ID } from '@/components/layout';
import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate';
import type { GitBookSiteContext } from '@/lib/context';
import { hasAPIBlock, hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
import {
hasAPIBlock,
hasFullWidthBlock,
hasMoreThan,
hasTopLevelBlock,
isNodeEmpty,
} from '@/lib/document';
import type { AncestorRevisionPage } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
const LINK_PREVIEW_MAX_COUNT = 500;
export async function PageBody(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
@@ -36,8 +41,6 @@ export async function PageBody(props: {
withPageFeedback: boolean;
insightsDisplayContext: SiteInsightsDisplayContext;
staticRoute: boolean;
contentHasUpdates: boolean;
updatesBaseHref?: string | undefined;
}) {
const {
page,
@@ -47,14 +50,26 @@ export async function PageBody(props: {
withPageFeedback,
insightsDisplayContext,
staticRoute,
contentHasUpdates,
updatesBaseHref,
} = props;
const { customization } = context;
// Update blocks can only be at the top level of the document, so we optimize the check.
const contentHasUpdates = document
? hasTopLevelBlock(document, (block) => block.type === 'updates')
: false;
// Comments can only be made on change request previews, so public pages skip their markers.
const withCommentAnchors = Boolean(context.changeRequest);
// Render link previews only if there are less than LINK_PREVIEW_MAX_COUNT links in the document.
const withLinkPreviews = document
? !hasMoreThan(
document,
(inline) => inline.object === 'inline' && inline.type === 'link',
LINK_PREVIEW_MAX_COUNT
)
: false;
// Determine if content should use wide layout (2-column or 1-column instead of 3-column)
// This happens when: (1) document has full-width blocks, OR (2) page layout is explicitly set to 'wide'
const wideContent = document ? hasFullWidthBlock(document) : false;
@@ -77,29 +92,6 @@ export async function PageBody(props: {
const pageHasToc = page.layout.tableOfContents && hasVisibleTOCItems;
let content = <PageBodyBlankslate page={page} context={context} />;
if (document && !isNodeEmpty(document)) {
content = (
<OptionalSuspense
staticRoute={staticRoute}
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
>
<SuspenseLoadedHint />
<div className="contents" data-content-ref-root="">
<PageBodyDocument document={document} context={context} page={page} />
</div>
</OptionalSuspense>
);
}
if (updatesBaseHref) {
content = (
<>
<PaginatedUpdatesBody>{content}</PaginatedUpdatesBody>
<UpdatesPagination language={language} baseHref={updatesBaseHref} />
</>
);
}
return (
<CurrentPageProvider page={{ spaceId: context.space.id, pageId: page.id }}>
{contentHasUpdates ? (
@@ -112,11 +104,10 @@ export async function PageBody(props: {
) : null}
<main
id={MAIN_CONTENT_ID}
tabIndex={-1}
// Comments on the whole page target anywhere in it that isn't a block.
{...(withCommentAnchors ? { 'data-comment-page': '' } : {})}
className={tcls(
'relative min-w-0 flex-1 outline-none',
'relative min-w-0 flex-1',
'break-anywhere', // Allow words to break if they are too long.
'py-8',
'layout-wide:no-sidebar:lg:max-xl:pb-20', // Add padding to prevent overlap of minimised trademark
@@ -147,7 +138,32 @@ export async function PageBody(props: {
hasAPIBlocks={hasAPIBlocks}
asEmbeddable={insightsDisplayContext === SiteInsightsDisplayContext.Embed}
/>
{content}
{document && !isNodeEmpty(document) ? (
<OptionalSuspense
staticRoute={staticRoute}
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
>
<SuspenseLoadedHint />
<div className="contents" data-content-ref-root="">
<DocumentView
document={document}
style="flex flex-col [&>*+*]:mt-5"
context={{
mode: 'default',
contentContext: {
...context,
page,
},
withLinkPreviews,
withCommentAnchors,
isPageBody: true,
}}
/>
</div>
</OptionalSuspense>
) : (
<PageBodyBlankslate page={page} context={context} />
)}
</div>
{page.layout.pagination && customization.pagination.enabled ? (
@@ -1,34 +0,0 @@
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
import { DocumentView } from '../DocumentView';
import type { GitBookSiteContext } from '@/lib/context';
import { hasMoreThan } from '@/lib/document';
const LINK_PREVIEW_MAX_COUNT = 500;
export function PageBodyDocument(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
document: JSONDocument;
}) {
const { context, page, document } = props;
const withLinkPreviews = !hasMoreThan(
document,
(inline) => inline.object === 'inline' && inline.type === 'link',
LINK_PREVIEW_MAX_COUNT
);
return (
<DocumentView
document={document}
style="flex flex-col [&>*+*]:mt-5"
context={{
mode: 'default',
contentContext: { ...context, page },
withLinkPreviews,
withCommentAnchors: Boolean(context.changeRequest),
isPageBody: true,
}}
/>
);
}
@@ -1,19 +1,24 @@
import assertNever from 'assert-never';
import urlJoin from 'url-join';
import type {
RevisionPage,
RevisionPageDocument,
SiteSection,
SiteSectionGroup,
import {
CustomizationPageActionType,
type RevisionPage,
type RevisionPageDocument,
type SiteSection,
type SiteSectionGroup,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { SpacesDropdownMenuItems, type VariantSpace } from '../Header/SpacesDropdownMenuItem';
import { CONTENT_STYLE, CONTENT_STYLE_REDUCED } from '../layout';
import { hasConfiguredPageActions } from '../PageActions/pageActionsData';
import { PageActionsMenu } from '../PageActions/PageActionsMenu';
import {
PageActionsDropdown,
type PageActionsDropdownURLs,
} from '../PageActions/PageActionsDropdown';
import { PageAsideToggleButton } from '../PageAside/PageAsideButton';
import { PageIcon } from '../PageIcon';
import { getPDFURLSearchParams } from '../PDF';
import {
findBestTargetURL,
getTargetURLForSiteSpace,
@@ -22,9 +27,11 @@ import { categorizeVariants } from '../SpaceLayout/categorizeVariants';
import { BreadcrumbItemDropdown, type BreadcrumbSibling } from './BreadcrumbItemDropdown';
import { PageTags } from './PageTags';
import type { GitBookSiteContext, SiteStructureNode } from '@/lib/context';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { type AncestorRevisionPage, resolveFirstDocument } from '@/lib/pages';
import { getLocalizedTitle } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
export async function PageHeader(props: {
context: GitBookSiteContext;
@@ -139,8 +146,15 @@ export async function PageHeader(props: {
// Show page actions if *any* of the configured actions are enabled, or if the RSS feed is
// available. RSS is contextual (only on update/blog index pages) and is not part of the
// configured `items` list, so it is checked separately.
const hasPageActions =
pageActionsEnabled && (hasConfiguredPageActions(context.customization) || withRSSFeed);
const hasConfiguredPageActions = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
].some((type) => isPageActionEnabled(context.customization, type));
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions || withRSSFeed);
if (!page.layout.title && !page.layout.description && !hasPageActions) {
return null;
@@ -167,7 +181,19 @@ export async function PageHeader(props: {
]
)}
>
{hasPageActions ? <PageActionsMenu context={context} page={page} /> : null}
{hasPageActions ? (
<PageActionsDropdown
siteTitle={context.site.title}
urls={getPageActionsURLs({ context, page, withRSSFeed })}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
) : null}
<PageAsideToggleButton />
</div>
);
@@ -494,3 +520,67 @@ function BreadcrumbSeparator() {
/>
);
}
/**
* Return the URLs for the page actions.
*/
function getPageActionsURLs({
context,
page,
withRSSFeed,
}: {
context: GitBookSiteContext;
page: RevisionPageDocument;
withRSSFeed: boolean;
}): PageActionsDropdownURLs {
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
isPageActionEnabled(context.customization, CustomizationPageActionType.Git) &&
context.space.gitSync?.url &&
page.git
? {
provider: context.space?.gitSync?.installationProvider,
url: urlJoin(context.space.gitSync.url, page.git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Whether a given built-in page action is enabled.
*/
function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -63,7 +63,6 @@ export function SearchContainer({
query,
results,
resultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -179,7 +178,6 @@ export function SearchContainer({
query={query}
results={results}
resultsId={resultsId}
resultsQuery={resultsQuery}
resultsRef={resultsRef}
onResultSelect={onResultSelect}
onResultHover={onResultHover}
@@ -27,7 +27,6 @@ export function SearchFrame(props: {
query: string;
results: ResultType[];
resultsId: string;
resultsQuery: string;
resultsRef: React.Ref<SearchResultsRef>;
onResultSelect?: () => void;
/** Select the result under the mouse, so hover and keyboard share one highlight. */
@@ -51,7 +50,6 @@ export function SearchFrame(props: {
query,
results,
resultsId,
resultsQuery,
resultsRef,
onResultSelect,
onResultHover,
@@ -80,7 +78,7 @@ export function SearchFrame(props: {
fetching ? 'block animate-fade-in' : 'hidden animate-fade-out-slow'
)}
style={{
animationDelay: fetching && results.length === 0 ? '2s' : undefined,
animationDelay: fetching ? '2s' : undefined,
}}
>
<div
@@ -120,7 +118,7 @@ export function SearchFrame(props: {
) : (
<SearchResults
ref={resultsRef}
query={resultsQuery}
query={query}
id={resultsId}
fetching={fetching}
results={results}
@@ -135,7 +135,7 @@ export const SearchInput = React.forwardRef<HTMLDivElement, SearchInputProps>(
}
}
trailing={
!showAsk && !fetching && value && resultsCount > 0 ? (
!showAsk && value && resultsCount > 0 ? (
<div className="animate-blur-in mr-2 text-sm text-tint-subtle">
{t(language, 'search_results_count', resultsCount.toString())}
</div>
@@ -6,7 +6,7 @@ import { useResizeObserver } from '../hooks';
import { Tooltip } from '../primitives';
import { getPageResultPresentation } from './getPageResultHref';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedPageResult, SearchResultSource } from './search-types';
import type { ComputedPageResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
@@ -14,15 +14,13 @@ import { tcls } from '@/lib/tailwind';
export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem(
props: {
query: string;
item: ComputedPageResult & SearchResultSource;
position: number;
resultsCount: number;
item: ComputedPageResult;
active: boolean;
style?: React.CSSProperties;
},
ref: React.Ref<HTMLAnchorElement>
) {
const { query, item, active, position, resultsCount, style, ...rest } = props;
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
const { preview: bestSection, description, href } = getPageResultPresentation(item);
@@ -32,9 +30,7 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
const insights = {
type: 'search_open_result' as const,
...item.search,
position,
resultsCount,
query,
result: {
pageId: item.pageId,
spaceId: item.spaceId,
@@ -4,36 +4,24 @@ import { Icon } from '@gitbook/icons';
import { Favicon } from '../utils';
import { HighlightQuery } from './HighlightQuery';
import type { ComputedRecordResult, SearchResultSource } from './search-types';
import type { ComputedRecordResult } from './search-types';
import { SearchResultItem } from './SearchResultItem';
import { tString, useLanguage } from '@/intl/client';
export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem(
props: {
query: string;
item: ComputedRecordResult & SearchResultSource;
position: number;
resultsCount: number;
item: ComputedRecordResult;
active: boolean;
style?: React.CSSProperties;
},
ref: React.Ref<HTMLAnchorElement>
) {
const { query, item, active, position, resultsCount, style, ...rest } = props;
const { query, item, active, style, ...rest } = props;
const language = useLanguage();
const domain = getDomain(item.href);
const insights = {
type: 'search_open_result' as const,
...item.search,
position,
resultsCount,
result: {
recordId: item.id,
},
};
return (
<SearchResultItem
ref={ref}
@@ -48,7 +36,13 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
fallback={<Icon icon="memo" className="size-4" />}
/>
}
insights={insights}
insights={{
type: 'search_open_result',
query,
result: {
recordId: item.id,
},
}}
aria-label={tString(language, 'search_page_result_title', item.title)}
style={{ ...style }}
{...rest}
@@ -72,7 +72,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
const language = useLanguage();
const { siteSpaceId } = useCurrentContent();
const shouldAnimateResults = !query;
const shouldAnimateResults = !query || fetching;
const previousCursor = React.useRef<number | null>(cursor);
const seenResultKeys = React.useRef(new Set<string>());
const lastQuery = React.useRef(query);
@@ -228,8 +228,9 @@ export const SearchResults = React.forwardRef(function SearchResults(
// users should keep their place in it.
if (navigatesCurrentWindow(event)) {
event.currentTarget.blur();
onResultSelect?.();
}
onResultSelect?.();
};
const resultItemProps = {
'aria-posinset': index + 1,
@@ -271,8 +272,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
}}
query={query}
item={item}
position={index + 1}
resultsCount={results.length}
active={index === cursor}
style={{
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
@@ -342,8 +341,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
key={itemKey}
query={query}
item={item}
position={index + 1}
resultsCount={results.length}
active={index === cursor}
style={{
animationDelay: `${index * 25}ms,${100 + index * 25}ms`,
@@ -362,11 +359,15 @@ export const SearchResults = React.forwardRef(function SearchResults(
{!fetching && results.length === 0 ? noResults : null}
</>
)}
{fetching && results.length === 0 ? (
{fetching ? (
<div
role="status"
aria-busy="true"
className="flex animate-[fadeIn_150ms_ease-out_both,pulse_2.4s_ease-in-out_600ms_infinite] flex-col gap-1 motion-reduce:animate-none"
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'
)}
>
<SearchResultsPlaceholder />
</div>
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'bun:test';
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import type { OrderedComputedResult } from './search-types';
describe('computeFilterSiteSpaceIds', () => {
@@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => {
});
});
describe('getDisplayedSearchResults', () => {
describe('filterResultsBySiteSpaces', () => {
const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({
type: 'page',
id,
@@ -52,7 +52,7 @@ describe('getDisplayedSearchResults', () => {
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(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([
expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([
'a',
'c',
]);
@@ -60,24 +60,6 @@ describe('getDisplayedSearchResults', () => {
it('returns every result when the scope is unrestricted', () => {
const results = [page('b', 'other'), page('a', 'current')];
expect(getDisplayedSearchResults(results, undefined)).toBe(results);
});
it('caps the displayed list after applying the site space filter', () => {
const pages = Array.from({ length: 10 }, (_, index) => page(`page-${index}`, 'current'));
const records = Array.from({ length: 11 }, (_, index): OrderedComputedResult => ({
type: 'record',
id: `record-${index}`,
title: `Record ${index}`,
description: undefined,
href: `/record-${index}`,
score: 1,
}));
const results = [page('hidden', 'other'), ...pages, ...records];
expect(getDisplayedSearchResults(results, ['current'])).toEqual([
...pages,
...records.slice(0, 10),
]);
expect(filterResultsBySiteSpaces(results, undefined)).toBe(results);
});
});
@@ -1,9 +1,6 @@
import type { OrderedComputedResult } from './search-types';
import type { SearchScope } from './useSearch';
// Keep aligned with SiteInsightsSearchResultNumber in the GitBook API schema.
const MAX_DISPLAYED_SEARCH_RESULTS = 20;
/**
* Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction.
*
@@ -32,20 +29,20 @@ export function computeFilterSiteSpaceIds(
}
}
/** Keep the first results in server order within the selected site spaces. */
export function getDisplayedSearchResults<Result extends OrderedComputedResult>(
results: Result[],
/** Keep the server's order, dropping pages owned by a site space outside the scope. */
export function filterResultsBySiteSpaces(
results: OrderedComputedResult[],
allowedSiteSpaceIds: string[] | undefined
): Result[] {
const allowed = allowedSiteSpaceIds && new Set(allowedSiteSpaceIds);
const matching = allowed
? results.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
)
: results;
return matching.length > MAX_DISPLAYED_SEARCH_RESULTS
? matching.slice(0, MAX_DISPLAYED_SEARCH_RESULTS)
: matching;
): OrderedComputedResult[] {
if (!allowedSiteSpaceIds) {
return results;
}
const allowed = new Set(allowedSiteSpaceIds);
return results.filter(
(result) =>
result.type === 'record' ||
(result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId))
);
}
@@ -15,6 +15,8 @@ export function computeRemoteSearchScope(
}
switch (scope) {
case 'all':
return { mode: 'all' };
case 'default':
return { mode: 'current', siteSpaceId };
case 'extended':
@@ -1,15 +1,13 @@
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
import { SEARCH_FALLBACK_HEADER, createSearchPassStore } from './search-pass-store';
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 proxyURL = '/~gitbook/search-direct/orgs/org_1/sites/site_1';
const directSearch: DirectSearchProps = {
apiURL: 'https://api.gitbook.com',
organizationId: 'org_1',
siteId: 'site_1',
proxyURL,
linker: {
urlMode: 'url-host',
siteHost: 'docs.example.com',
@@ -62,150 +60,6 @@ describe('createSearchPassStore', () => {
let restore: (() => void) | undefined;
afterEach(() => restore?.());
it('switches to the site proxy after an API network failure', async () => {
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockImplementation(async () => Response.json({ items: [] }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
proxyURL,
]);
const init = fetchSpy.mock.calls[2]?.[1];
expect(init).toMatchObject({ mode: 'same-origin', credentials: 'same-origin' });
expect(init?.body).toBe(JSON.stringify({ query: 'tokens', mode: 'all' }));
const headers = new Headers(init?.headers);
expect(headers.get('x-gitbook-search-pass')).toBe('pass-1');
expect(headers.get(SEARCH_FALLBACK_HEADER)).toBe('network');
expect(headers.has('authorization')).toBe(false);
expect(new Headers(fetchSpy.mock.calls[3]?.[1]?.headers).has(SEARCH_FALLBACK_HEADER)).toBe(
false
);
});
it('switches to the site proxy after an API timeout', async () => {
const originalSetTimeout = globalThis.setTimeout;
const timeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation(((
fn: (...args: unknown[]) => void,
ms?: number,
...args: unknown[]
) => {
let delay = ms;
if (ms === 5_000) {
delay = 0;
}
return originalSetTimeout(fn, delay, ...args);
}) as typeof setTimeout);
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockImplementationOnce(
(_url, init) =>
new Promise((_, reject) => {
init?.signal?.addEventListener(
'abort',
() => reject(new DOMException('Aborted', 'AbortError')),
{ once: true }
);
})
)
.mockResolvedValueOnce(Response.json({ items: [] }));
restore = () => {
timeoutSpy.mockRestore();
fetchSpy.mockRestore();
};
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
expect(new Headers(fetchSpy.mock.calls[2]?.[1]?.headers).get(SEARCH_FALLBACK_HEADER)).toBe(
'timeout'
);
});
it('refreshes the pass on a 401 from the site proxy', async () => {
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(new Response(null, { status: 401 }))
.mockResolvedValueOnce(Response.json({ token: 'pass-2', expiresIn: 300_000 }))
.mockResolvedValueOnce(Response.json({ items: [] }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '401' });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
directSearch.passURL,
proxyURL,
]);
expect(new Headers(fetchSpy.mock.calls[4]?.[1]?.headers).get('x-gitbook-search-pass')).toBe(
'pass-2'
);
});
it('honors rate-limit headers on a 429 from the site proxy', async () => {
const resetAtSeconds = Math.ceil((Date.now() + 30_000) / 1000);
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(
new Response(null, {
status: 429,
headers: {
'x-ratelimit-scope': 'site',
'x-ratelimit-reset': String(resetAtSeconds),
},
})
);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
await expect(search(store)).rejects.toThrow('Search is rate limited');
await expect(search(store)).rejects.toThrow('Search is rate limited');
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
});
it('uses the server route after the site proxy also fails', async () => {
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(new Response(null, { status: 502 }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
});
it('stays on the route for the rest of the page after a 403', async () => {
const { authorizations, fetchSpy } = mockFetch([403]);
restore = () => fetchSpy.mockRestore();
@@ -233,11 +87,6 @@ describe('createSearchPassStore', () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(authorizations).toEqual(sent);
const refresh = store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: undefined });
await refresh;
expect(authorizations).toEqual(sent);
}
);
@@ -287,47 +136,4 @@ describe('createSearchPassStore', () => {
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(authorizations).toHaveLength(1);
});
it('falls back for an unknown space without latching later searches to the route', async () => {
let searchCalls = 0;
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (
input: RequestInfo | URL
) => {
if (String(input) === '/~gitbook/search-pass') {
return Response.json({ token: 'pass-1', expiresIn: 300_000 });
}
searchCalls += 1;
if (searchCalls === 1) {
return Response.json({
items: [
{
type: 'space',
id: 'space_unknown',
title: 'Unknown',
score: 1,
pages: [
{
id: 'page_1',
title: 'Page 1',
path: 'page-1',
score: 1,
rank: 1,
ancestors: [],
urls: { app: 'https://app.gitbook.com/o/org/s/space' },
},
],
},
],
});
}
return Response.json({ items: [] });
}) as typeof fetch);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: 'unknown_space' });
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(searchCalls).toBe(2);
});
});
@@ -32,11 +32,6 @@ type DirectSearchOutcome =
| { type: 'results'; results: OrderedComputedResult[] }
| { type: 'route'; reason?: string };
type SearchAttempt =
| { type: 'success'; body: string }
| { type: 'http'; response: Response }
| { type: 'failure'; reason: 'network' | 'timeout' };
export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
/**
@@ -44,7 +39,6 @@ export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
*/
export function createSearchPassStore(directSearch: DirectSearchProps | undefined) {
let state: SearchPassState = { status: 'none' };
let useProxy = false;
let pendingRequest: Promise<void> | null = null;
const sendPassRequest = async () => {
@@ -83,9 +77,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
(current.status === 'none' && current.reason === '401') ||
(current.status === 'ready' && current.replacesRejectedPass),
};
if (!useProxy) {
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
}
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
} else if (current.status === 'ready') {
state = { status: 'none' };
}
@@ -132,12 +124,11 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
const search = async (input: {
query: string;
searchId?: string;
scope: SearchSiteContentScope;
signal: AbortSignal;
asEmbeddable: boolean;
}): Promise<DirectSearchOutcome> => {
const { query, searchId, scope, signal, asEmbeddable } = input;
const { query, scope, signal, asEmbeddable } = input;
if (!directSearch) {
return { type: 'route' };
}
@@ -148,150 +139,83 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
return waitForCooldown(state, signal);
}
if (state.status !== 'ready') {
return { type: 'route', reason: state.reason === '401' ? undefined : state.reason };
return { type: 'route', reason: state.reason };
}
if (query.length <= 1) {
return { type: 'results', results: [] };
}
let pass = state;
const { apiURL, organizationId, siteId, proxyURL } = directSearch;
const usingProxy = useProxy;
let url = `${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`;
if (usingProxy) {
url = proxyURL;
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();
}
const body = JSON.stringify(toSearchSiteContentBody(query, scope, searchId));
let attempt = await sendSearch(url, usingProxy, pass.token, body, signal);
if (attempt.type === 'failure' && !usingProxy) {
const current = state as SearchPassState;
// TODO: timeout can mean a slow API rather than a blocked host, so consider not sticking to the proxy for the session.
if (current.status === 'ready') {
useProxy = true;
pass = current;
attempt = await sendSearch(
proxyURL,
true,
pass.token,
body,
signal,
attempt.reason
);
} else if (current.status === 'none') {
useProxy = true;
return { type: 'route', reason: attempt.reason };
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 (attempt.type === 'failure') {
const current = state as SearchPassState;
if (current.status === 'route') {
return waitForCooldown(current, signal);
}
return fallBack(attempt.reason);
if (response.status === 401) {
return replacesRejectedPass ? fallBack('401') : dropPass(token, '401');
}
if (attempt.type === 'http') {
const { response } = attempt;
if (response.status === 401) {
if (pass.replacesRejectedPass) {
return fallBack('401');
}
return dropPass(pass.token, '401');
}
if (response.status === 429) {
state = {
status: 'route',
reason: '429',
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
};
return waitForCooldown(state, signal);
}
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 } = JSON.parse(attempt.body) as {
const { items } = (await response.json()) as {
items: (SearchSpaceResult | SearchRecordResult)[];
};
let linker = createSiteLinker(directSearch.linker);
if (asEmbeddable) {
linker = getEmbeddableLinker(linker);
}
const results = computePublishedSearchResults({
const linker = createSiteLinker(directSearch.linker);
results = computePublishedSearchResults({
asEmbeddable,
linker,
linker: asEmbeddable ? getEmbeddableLinker(linker) : linker,
searchResults: items,
spaces: directSearch.spaces,
});
if (!results) {
return { type: 'route', reason: 'unknown_space' };
} catch (error) {
if (signal.aborted) {
throw error;
}
return { type: 'results', results };
} catch {
return fallBack('invalid');
return fallBack(request.signal.aborted ? 'timeout' : 'invalid');
} finally {
clearTimeout(timeout);
}
return results ? { type: 'results', results } : fallBack('unknown_space');
};
return { requestPass, search };
}
async function sendSearch(
url: string,
useProxy: boolean,
token: string,
body: string,
signal: AbortSignal,
fallbackReason?: 'network' | 'timeout'
): Promise<SearchAttempt> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
let mode: RequestMode | undefined;
let credentials: RequestCredentials = 'omit';
if (useProxy) {
mode = 'same-origin';
credentials = 'same-origin';
headers['x-gitbook-search-pass'] = token;
if (fallbackReason) {
headers[SEARCH_FALLBACK_HEADER] = fallbackReason;
}
} else {
headers.Authorization = `Bearer ${token}`;
}
const request = new AbortController();
const abort = () => request.abort();
if (signal.aborted) {
abort();
}
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, DIRECT_SEARCH_TIMEOUT_MS);
try {
const response = await fetch(url, {
method: 'POST',
headers,
body,
credentials,
mode,
signal: request.signal,
});
if (!response.ok) {
return { type: 'http', response };
}
return { type: 'success', body: await response.text() };
} catch (error) {
if (signal.aborted) {
throw error;
}
if (request.signal.aborted) {
return { type: 'failure', reason: 'timeout' };
}
return { type: 'failure', reason: 'network' };
} finally {
clearTimeout(timeout);
signal.removeEventListener('abort', abort);
}
}
/**
* 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.
@@ -132,13 +132,9 @@ export function getDirectSearchProps(context: GitBookSiteContext): DirectSearchP
return undefined;
}
const { organizationId, siteId } = context.directSearch;
return {
...context.directSearch,
spaces: getSearchSpaceLookup(context.structure),
passURL: context.linker.toPathInSite('~gitbook/search-pass'),
proxyURL: context.linker.toPathInSite(
`~gitbook/search-direct/orgs/${organizationId}/sites/${siteId}`
),
};
}
@@ -2,10 +2,6 @@ import type { IconName } from '@gitbook/icons';
export type OrderedComputedResult = ComputedPageResult | ComputedRecordResult;
export type SearchResultSource = {
search: { query: string; searchId: string | undefined };
};
export type BaseComputedResult = {
id: string;
title: string;
@@ -59,7 +55,6 @@ export type SearchSiteContentScope =
export interface SearchSiteContentRequest {
asEmbeddable?: boolean;
searchId?: string;
query: string;
scope: SearchSiteContentScope;
}
@@ -1,13 +1,6 @@
import { describe, expect, it } from 'bun:test';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { createElement } from 'react';
import { renderToString } from 'react-dom/server';
import { SearchContextProvider, shouldKeepSearchState, useSearchState } from './useSearch';
function SearchScopeValue() {
return useSearchState()?.scope ?? null;
}
import { shouldKeepSearchState } from './useSearch';
describe('shouldKeepSearchState', () => {
it('discards an empty default search state', () => {
@@ -30,25 +23,3 @@ describe('shouldKeepSearchState', () => {
).toBe(true);
});
});
it.each([
['scope=all', 'default'],
['global=true', 'default'],
['scope=current&global=true', 'current'],
['scope=extended&global=true', 'extended'],
])('resolves %s to %s for a linked search', (params, scope) => {
const search = createElement(
SearchContextProvider,
{ prewarmURL: '/~gitbook/search' },
createElement(SearchScopeValue)
);
expect(
renderToString(
createElement(NuqsTestingAdapter, {
searchParams: `q=setup&${params}`,
children: search,
})
)
).toBe(scope);
});
@@ -1,6 +1,12 @@
'use client';
import { type Values, parseAsString, parseAsStringLiteral, useQueryStates } from 'nuqs';
import {
type Values,
parseAsBoolean,
parseAsString,
parseAsStringLiteral,
useQueryStates,
} from 'nuqs';
import React from 'react';
import type { LinkProps } from '../primitives';
@@ -10,6 +16,8 @@ import { useSearchPrewarm } from './useSearchPrewarm';
import type { DirectSearchProps } from '@/lib/search-results';
export type SearchScope =
/** Search all content on the site */
| 'all'
/** Search the current section's variant + matched/default variant for other sections */
| 'default'
/** Search all variants of the current section */
@@ -33,8 +41,9 @@ export interface SearchState {
const keyMap = {
q: parseAsString,
ask: parseAsString,
scope: parseAsStringLiteral(['default', 'extended', 'current']).withDefault('default'),
scope: parseAsStringLiteral(['all', 'default', 'extended', 'current']).withDefault('default'),
section: parseAsString,
global: parseAsBoolean, // Legacy support for global=true
};
export type UpdateSearchState = (
@@ -53,6 +62,11 @@ function normalizeRawState(values: Values<typeof keyMap>) {
if (values.ask === 'true' && values.q) {
return { ...values, q: null, ask: values.q };
}
// Handle legacy global=true
if (values.global === true) {
return { ...values, scope: 'all' as const, global: null };
}
return values;
}
@@ -141,6 +141,7 @@ function useSearchKeyboardNavigation(props: {
requestKey: string;
flush: () => void;
resultsRef: React.RefObject<SearchResultsRef | null>;
abort: () => void;
askCount: number;
onAskSelect: (index: number) => void;
}) {
@@ -153,6 +154,7 @@ function useSearchKeyboardNavigation(props: {
requestKey,
flush,
resultsRef,
abort,
askCount,
onAskSelect,
} = props;
@@ -188,6 +190,8 @@ function useSearchKeyboardNavigation(props: {
}
if (resultsRef.current?.select()) {
// Stop any in-flight search request only when activating a result.
abort();
return;
}
@@ -203,6 +207,7 @@ function useSearchKeyboardNavigation(props: {
results.length,
onAskSelect,
resultsRef,
abort,
query,
fetching,
requestKey,
@@ -224,11 +229,13 @@ function useSearchKeyboardNavigation(props: {
}
pendingOpenRef.current = null;
if (results.length > 0) {
resultsRef.current?.selectFirst();
if (resultsRef.current?.selectFirst()) {
abort();
}
} else if (!error && askCount > 0) {
onAskSelect(0);
}
}, [isOpen, requestKey, fetching, error, results, resultsRef, askCount, onAskSelect]);
}, [isOpen, requestKey, fetching, error, results, resultsRef, abort, askCount, onAskSelect]);
return {
cursor,
@@ -372,10 +379,9 @@ export function useSearchController(
const selectedSection = state?.section ? findSearchSection(sections, state.section) : undefined;
const { consumeImmediate, flushRef, inputHandlers } = useSearchInputIntent();
const { results, resultsQuery, fetching, error, requestKey, flush, abort } = useSearchResults({
const { results, fetching, error, requestKey, flush, abort } = useSearchResults({
asEmbeddable,
disabled: options.requestsEnabled === false || showAsk || !(normalizedQuery || withAI),
retainPreviousResults: Boolean(state?.open),
disabled: options.requestsEnabled === false || !(normalizedQuery || withAI),
query: normalizedQuery,
siteSpaceId: siteSpace.id,
siteSpaceIds,
@@ -436,6 +442,7 @@ export function useSearchController(
requestKey,
flush,
resultsRef,
abort,
askCount,
onAskSelect: askInAssistant,
});
@@ -456,7 +463,6 @@ export function useSearchController(
query: normalizedQuery,
results,
resultsId: searchResultsId,
resultsQuery,
resultsRef,
searchValue,
setQuery,
@@ -8,36 +8,22 @@ import {
createRecommendedQuestionResult,
getEmptySearchResults,
} from './empty-search-results';
import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter';
import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter';
import { useRecentSearchQueries } from './recent-queries';
import { computeRemoteSearchScope } from './remote-scope';
import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store';
import type {
OrderedComputedResult,
SearchResultSource,
SearchSiteContentScope,
} from './search-types';
import type { OrderedComputedResult, SearchSiteContentScope } from './search-types';
import { streamRecommendedQuestions } from './server-actions';
import { type SearchScope, useSearchPass } from './useSearch';
import { useAI } from '@/components/AI';
export type ResultType = RemoteSearchResult | RecommendedQuestionResult;
const SEARCH_ID_BYTES = 16;
type RemoteSearchResult = OrderedComputedResult & SearchResultSource;
type SearchAnswer = {
scopeKey: string;
query: string;
results: RemoteSearchResult[];
};
export type ResultType = OrderedComputedResult | RecommendedQuestionResult;
type RemoteSearchState =
| { status: 'idle' }
| { status: 'loading'; requestKey: string; answer?: SearchAnswer }
| { status: 'ready'; requestKey: string; answer: SearchAnswer }
| { status: 'error'; requestKey: string };
| { status: 'loading' }
| { status: 'ready'; requestKey: string; results: OrderedComputedResult[] }
| { status: 'error' };
/**
* We cache the recommended questions globally to avoid calling the API multiple times
@@ -51,7 +37,6 @@ export function useSearchResults(props: {
asEmbeddable?: boolean;
disabled: boolean;
query: string;
retainPreviousResults: boolean;
siteSpaceId: string;
siteSpaceIds: string[];
selectedSectionSiteSpaceIds?: string[];
@@ -68,7 +53,6 @@ export function useSearchResults(props: {
asEmbeddable,
disabled,
query,
retainPreviousResults,
siteSpaceId,
siteSpaceIds,
selectedSectionSiteSpaceIds,
@@ -99,15 +83,8 @@ export function useSearchResults(props: {
computeRemoteSearchScope(scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds),
[scope, siteSpaceId, siteSpaceIds, selectedSectionSiteSpaceIds]
);
const scopeKey = JSON.stringify([
searchURL,
asEmbeddable,
siteSpaceId,
scope,
remoteScope,
filterSiteSpaceIds,
]);
const requestKey = JSON.stringify([scopeKey, query]);
// 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 [remoteState, setRemoteState] = React.useState<RemoteSearchState>({ status: 'idle' });
@@ -123,7 +100,6 @@ export function useSearchResults(props: {
React.useEffect(() => {
if (disabled) {
setRemoteState({ status: 'idle' });
return;
}
if (!query) {
@@ -150,7 +126,7 @@ export function useSearchResults(props: {
// We currently have a bug where the same question can be returned multiple times.
// This is a workaround to avoid that.
const questions = new Set<string>();
let recommendedQuestions: RecommendedQuestionResult[] = [];
const recommendedQuestions: RecommendedQuestionResult[] = [];
if (suggestions && suggestions.length > 0) {
suggestions.forEach((question) => {
@@ -177,10 +153,7 @@ export function useSearchResults(props: {
}
questions.add(question);
recommendedQuestions = [
...recommendedQuestions,
createRecommendedQuestionResult(question, question),
];
recommendedQuestions.push(createRecommendedQuestionResult(question, question));
cachedRecommendedQuestions.set(siteSpaceId, recommendedQuestions);
if (!cancelled) {
@@ -195,19 +168,14 @@ export function useSearchResults(props: {
clearTimeout(timeout);
};
}
setRemoteState((state) => {
const answer = 'answer' in state ? state.answer : undefined;
return answer?.scopeKey === scopeKey
? { status: 'loading', requestKey, answer }
: { status: 'loading', requestKey };
});
setRemoteState({ status: 'loading' });
let cancelled = false;
const abortController = new AbortController();
const send = async () => {
flushRef.current = null;
const fetchSearch = (
scope: Parameters<typeof fetchSearchResults>[1]
): Promise<RemoteSearchResult[]> =>
): Promise<OrderedComputedResult[]> =>
fetchSearchResults(
searchURL,
scope,
@@ -220,29 +188,25 @@ export function useSearchResults(props: {
try {
const resultsPromise = fetchSearch(remoteScope);
const onResults = (results: RemoteSearchResult[]) => {
const onResults = (results: OrderedComputedResult[]) => {
if (cancelled) {
return;
}
if (!results) {
// Can happen when the route cannot be found and returns the page's html.
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
return;
}
setRemoteState({
status: 'ready',
requestKey,
answer: { scopeKey, query, results },
});
setRemoteState({ status: 'ready', requestKey, results });
trackEvent({ type: 'search_type_query', query });
};
const onError = () => {
if (cancelled) {
return;
}
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
};
await resultsPromise.then(onResults, onError);
@@ -251,10 +215,10 @@ export function useSearchResults(props: {
if (cancelled) {
return;
}
setRemoteState({ status: 'error', requestKey });
setRemoteState({ status: 'error' });
}
};
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 100);
const timeout = setTimeout(send, consumeImmediate?.(query) ? 0 : 150);
flushRef.current = () => {
clearTimeout(timeout);
void send();
@@ -277,7 +241,6 @@ export function useSearchResults(props: {
query,
remoteScope,
requestKey,
scopeKey,
trackEvent,
withAI,
siteSpaceId,
@@ -289,16 +252,6 @@ export function useSearchResults(props: {
searchPass,
]);
React.useEffect(() => {
if (!retainPreviousResults) {
setRemoteState((state) =>
state.status === 'loading' && state.answer
? { status: 'loading', requestKey: state.requestKey }
: state
);
}
}, [retainPreviousResults, requestKey]);
const flush = React.useCallback(() => {
flushRef.current?.();
}, []);
@@ -309,20 +262,10 @@ export function useSearchResults(props: {
setRemoteState((prev) => (prev.status === 'loading' ? { status: 'idle' } : prev));
}, []);
const answer = 'answer' in remoteState ? remoteState.answer : undefined;
const visibleAnswer =
query &&
!disabled &&
answer?.scopeKey === scopeKey &&
(answer.query === query || retainPreviousResults)
? answer
: undefined;
const streamedQuestions = cachedRecommendedQuestions.get(siteSpaceId);
const results = React.useMemo<ResultType[]>(() => {
if (!query) {
const recommendedQuestions =
streamedQuestions ??
cachedRecommendedQuestions.get(siteSpaceId) ??
suggestions?.map((question, index) =>
createRecommendedQuestionResult(`recommended-question-${index}`, question)
) ??
@@ -335,32 +278,27 @@ export function useSearchResults(props: {
});
}
return visibleAnswer
? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds)
return remoteState.status === 'ready' && remoteState.requestKey === requestKey
? filterResultsBySiteSpaces(remoteState.results, filterSiteSpaceIds)
: [];
}, [
visibleAnswer,
remoteState,
requestKey,
query,
filterSiteSpaceIds,
withAI,
streamedQuestions,
siteSpaceId,
suggestions,
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,
resultsQuery: visibleAnswer?.query ?? query,
fetching:
Boolean(query) &&
!disabled &&
(remoteState.status === 'loading' ||
(remoteState.status !== 'idle' && remoteState.requestKey !== requestKey)),
error:
Boolean(query) &&
!disabled &&
remoteState.status === 'error' &&
remoteState.requestKey === requestKey,
fetching: remoteState.status === 'loading' || (Boolean(query) && isOutdated),
error: remoteState.status === 'error',
requestKey,
flush,
abort,
@@ -377,21 +315,17 @@ async function fetchSearchResults(
signal: AbortSignal,
asEmbeddable: boolean | undefined,
searchPass: SearchPassStore | null
): Promise<RemoteSearchResult[]> {
const directSearchId = generateSearchId();
): Promise<OrderedComputedResult[]> {
const direct = await searchPass?.search({
query,
searchId: directSearchId,
scope,
signal,
asEmbeddable: Boolean(asEmbeddable),
});
if (direct?.type === 'results') {
const search = { query, searchId: directSearchId };
return direct.results.map((result) => ({ ...result, search }));
return direct.results;
}
const searchId = direct ? generateSearchId() : directSearchId;
const response = await fetch(searchURL, {
method: 'POST',
headers: {
@@ -401,7 +335,6 @@ async function fetchSearchResults(
body: JSON.stringify({
asEmbeddable,
query,
searchId,
scope,
}),
signal,
@@ -411,12 +344,5 @@ async function fetchSearchResults(
throw new Error(`Search request failed: ${response.status}`);
}
const results: OrderedComputedResult[] = await response.json();
const search = { query, searchId };
return results.map((result) => ({ ...result, search }));
}
function generateSearchId() {
const bytes = globalThis.crypto?.getRandomValues(new Uint8Array(SEARCH_ID_BYTES));
return bytes && Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
return response.json() as Promise<OrderedComputedResult[]>;
}
@@ -17,11 +17,9 @@ export function useSearchResultsCursor(props: {
}, [query]);
React.useEffect(() => {
if (fetching) {
if (resultCount === 0) {
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
setCursor(null);
}
if (fetching && resultCount === 0) {
// Nothing is highlighted while results load, so Enter can't open the Ask row instead.
setCursor(null);
return;
}
@@ -1,25 +1,17 @@
import type { GitBookSiteContext } from '@/lib/context';
import { getAdvertisedMcpEndpoint, getLLMsTxtURL } from '@/lib/llms-directive';
import { getLLMsTxtURL } from '@/lib/llms-directive';
/**
* Agent-facing pointer to the site index, the Markdown versions of pages and the MCP server.
* Agent-facing pointer to the site index and the Markdown versions of pages.
*/
export function LLMsTxtDirective(props: { context: GitBookSiteContext }) {
const { context } = props;
const mcpEndpoint = getAdvertisedMcpEndpoint(context);
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.
{mcpEndpoint ? (
<>
{' '}
Agents can also search and read this documentation through its{' '}
<a href={mcpEndpoint}>MCP server</a>.
</>
) : null}
</div>
);
}
@@ -6,7 +6,6 @@ import {
CustomizationHeaderPreset,
SiteInsightsDisplayContext,
type TranslationLanguage,
type RevisionTag,
} from '@gitbook/api';
import { IconsProvider } from '@gitbook/icons';
@@ -19,43 +18,34 @@ import {
} from './fetch';
import { PageClientLayout } from './PageClientLayout';
import { getPageFullTitle } from './title';
import { PaginatedUpdatesProvider } from '@/components/DocumentView/PaginatedUpdates';
import { UpdatesFilterProvider } from '@/components/DocumentView/UpdatesFilter';
import { UpdatesFilterScript } from '@/components/DocumentView/UpdatesFilterScript';
import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody';
import type { GitBookSiteContext } from '@/lib/context';
import { getDataOrNull, getPageDocument } from '@/lib/data';
import { hasTopLevelBlock } from '@/lib/document';
import {
getContentInlineIconSourceRequests,
getCustomizationIconStyle,
getInlineIconSources,
} from '@/lib/icons/inline';
import { getResizedImageURL } from '@/lib/images';
import { getLogger } from '@/lib/logger';
import { getPagePath } from '@/lib/pages';
import { resolveContentRef } from '@/lib/references';
import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import {
countDocumentUpdates,
generateUpdatesFilterCSS,
getUpdatesPageRange,
paginateUpdatesDocument,
UPDATES_PAGINATION_THRESHOLD,
getDocumentFilterableTags,
updatesFilterStyleHref,
} from '@/lib/updates';
import { UPDATES_PAGE_SEARCH_PARAM } from '@/lib/updates-url';
export { getPageFullTitle } from './title';
export type SitePageProps = {
context: GitBookSiteContext;
pageParams: PagePathParams;
updatesPage?: number;
};
type AlternateLinkSpace = {
@@ -95,18 +85,11 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
withTopHeader,
pageMetaLinks,
iconSources,
filterableTags,
contentHasUpdates,
pagination,
pageHref,
} = await getSitePageData(props);
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
const filterableTags = document ? getDocumentFilterableTags(document, context.revision) : [];
const filterableTagSlugs = filterableTags.map((tag) => tag.slug);
let updatesBaseHref: string | undefined;
if (pagination) {
updatesBaseHref = pageHref;
}
let content = (
const content = (
<>
{/* Using `contents` makes the children of this div according to its parent — which keeps them in a single flex row with the TOC by default.
If there's a page cover, we use `flex flex-col` to lay out the PageCover above the PageBody + PageAside instead. */}
@@ -136,7 +119,6 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
page={page}
document={document}
filterableTags={filterableTags}
withUpdatesPagination={Boolean(pagination)}
withHeaderOffset={headerOffset}
withFullPageCover={withFullPageCover}
withPageFeedback={withPageFeedback}
@@ -150,8 +132,6 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Site}
staticRoute={props.staticRoute}
contentHasUpdates={contentHasUpdates}
updatesBaseHref={updatesBaseHref}
/>
</div>
<PageClientLayout pageMetaLinks={pageMetaLinks} />
@@ -159,34 +139,18 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
</>
);
if (pagination) {
content = (
<PaginatedUpdatesProvider
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
pageId={page.id}
revisionId={context.revisionId}
isEmbeddable={false}
tagSlugs={filterableTagSlugs}
initialPagination={pagination}
>
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</PaginatedUpdatesProvider>
);
} else if (filterableTagSlugs.length > 0) {
content = (
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</UpdatesFilterProvider>
);
}
return (
<IconsProvider iconSources={iconSources}>
<PageContextProvider pageId={page.id} spaceId={context.space.id} title={page.title}>
{content}
{filterableTagSlugs.length > 0 ? (
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</UpdatesFilterProvider>
) : (
content
)}
</PageContextProvider>
</IconsProvider>
);
@@ -240,7 +204,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
const { page, ancestors } = pageTarget;
const { customization, revision, linker, imageResizer } = context;
let canonical = (
const canonical = (
pageMetaLinks?.canonical
? new URL(
// If the canonical link is an absolute URL, use it as is.
@@ -252,23 +216,6 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
linker.toAbsoluteURL(linker.toPathForPage({ pages: revision.pages, page }))
).replace(/\/+$/, ''); // Trim trailing slashes in canonical URL to match the redirect behavior
let title = getPageFullTitle(context, page);
if (props.updatesPage) {
const document = await getPageDocument(context, page);
if (document) {
const count = countDocumentUpdates(document);
if (count > UPDATES_PAGINATION_THRESHOLD) {
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
title = `${title} (Page ${pageNumber})`;
if (!pageMetaLinks?.canonical) {
const url = new URL(canonical);
url.searchParams.set(UPDATES_PAGE_SEARCH_PARAM, String(pageNumber));
canonical = url.toString();
}
}
}
}
const alternates = pageMetaLinks?.alternates.reduce<{
languages: Record<string, string>;
generic: {
@@ -292,9 +239,8 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
);
return {
title,
title: getPageFullTitle(context, page),
description: page.description ?? '',
keywords: page.keywords?.length ? page.keywords : undefined,
alternates: {
canonical,
languages: alternates?.languages,
@@ -380,44 +326,7 @@ export async function getSitePageData(props: SitePageProps) {
const withSections = Boolean(visibleSections && visibleSections.list.length > 0);
const fullDocument = await getPageDocument(context, page);
const pageHref = context.linker.toPathForPagePath({ path: rawPathname });
let contentHasUpdates = false;
let filterableTags: RevisionTag[] = [];
let document = fullDocument;
let pagination = null;
if (fullDocument) {
contentHasUpdates = hasTopLevelBlock(fullDocument, (block) => block.type === 'updates');
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
page: props.updatesPage ?? 1,
}));
}
if (pagination || props.updatesPage) {
const logger = getLogger().subLogger('updatesPagination', {
labels: { siteId: context.site.id, pageId: page.id },
});
if (props.updatesPage && (!pagination || pagination.isClamped)) {
const targetPage = pagination?.page ?? 1;
logger.info('Redirected out-of-range updates page', {
requestedPage: props.updatesPage,
targetPage,
});
if (targetPage > 1) {
redirect(`${pageHref}?${UPDATES_PAGE_SEARCH_PARAM}=${targetPage}`);
}
redirect(pageHref);
}
if (pagination) {
logger.info('Rendered updates page', {
page: pagination.page,
totalItems: pagination.totalItems,
totalPages: pagination.totalPages,
});
}
}
const document = await getPageDocument(context, page);
const iconStyle = getCustomizationIconStyle(customization);
const iconSources = await getInlineIconSources(
getContentInlineIconSourceRequests({
@@ -437,10 +346,6 @@ export async function getSitePageData(props: SitePageProps) {
withTopHeader,
pageMetaLinks,
iconSources,
contentHasUpdates,
filterableTags,
pagination,
pageHref,
};
}
@@ -1,13 +1,17 @@
import { describe, expect, it, mock } from 'bun:test';
import type { RevisionPageDocument, SiteRedirectDestination } from '@gitbook/api';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
await import('./fetch');
const {
fetchPageData,
getLowercasePathnameRedirect,
resolveMissingPagePath,
resolveSitePageFromURL,
} = await import('./fetch');
const { normalizeURL } = await import('@/lib/data/urls');
const { createLinker } = await import('@/lib/links');
@@ -21,30 +25,92 @@ const page = {
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revision: { pages: [page] },
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('fetchPageData', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result.pageTarget?.page.git).toEqual(git);
expect(result.context.page?.git).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
});
describe('resolveMissingPagePath', () => {
function createRedirectContext(options: {
siteRedirect?: {
source?: string;
target: string;
permanent?: boolean;
destination?: SiteRedirectDestination;
};
siteRedirect?: { source?: string; target: string; permanent?: boolean };
spaceRedirectPageId?: string;
contextId?: string;
structure?: GitBookSiteContext['structure'];
revisionsBySpace?: Record<string, RevisionPageDocument[]>;
}) {
const getSiteRedirectBySource = mock(async ({ source }: { source: string }) =>
options.siteRedirect && source === (options.siteRedirect.source ?? '/old')
? {
data: {
target: options.siteRedirect.target,
redirect: {
permanent: options.siteRedirect.permanent ?? false,
...(options.siteRedirect.destination
? { destination: options.siteRedirect.destination }
: {}),
},
redirect: { permanent: options.siteRedirect.permanent ?? false },
},
}
: { error: { code: 404, message: 'Not found' } }
@@ -54,35 +120,19 @@ describe('resolveMissingPagePath', () => {
? { data: { id: options.spaceRedirectPageId } }
: { error: { code: 404, message: 'Not found' } }
);
const getRevision = mock(async ({ spaceId }: { spaceId: string }) =>
options.revisionsBySpace?.[spaceId]
? { data: { pages: options.revisionsBySpace[spaceId] } }
: { error: { code: 404, message: 'Not found' } }
);
const defaultSiteSpace = {
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
};
return {
organizationId: 'org-1',
site: { id: 'site-1' },
siteSpace: defaultSiteSpace,
structure: options.structure ?? {
type: 'siteSpaces',
structure: [defaultSiteSpace],
},
space: { id: 'space-1', revision: 'revision-1' },
revisionId: 'revision-1',
revision: { pages: [page] },
contextId: options.contextId,
linker: {
toPathInSpace: (path: string) => path,
toRelativePathInSite: (path: string) => path,
toLinkForContent: (url: string) => new URL(url).pathname,
},
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath, getRevision },
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath },
} as unknown as GitBookSiteContext;
}
@@ -116,224 +166,6 @@ describe('resolveMissingPagePath', () => {
});
});
it('ignores a site redirect that targets the current path', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/release-notes/restricted',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a site redirect that targets the current path with trailing slash, case, or query differences', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/release-notes/restricted',
target: 'https://docs.example.com/Release-Notes/Restricted/?tab=1#top',
},
});
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
});
it('ignores a space-relative redirect that resolves back to the current section path', async () => {
const context = {
...createRedirectContext({
siteRedirect: {
source: '/v3/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
},
}),
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/docs/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'v3/getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden site space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/getting-started',
target: 'https://docs.example.com/docs/v3/getting-started',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-hidden',
pageId: 'page-v3',
},
},
});
expect(await resolveMissingPagePath(context, 'getting-started')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden section on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-visible',
siteSpaces: [
{
id: 'site-space-1',
space: { id: 'space-1', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
siteRedirect: {
source: '/old-section',
target: 'https://docs.example.com/hidden-section',
destination: {
kind: 'site-section',
siteSectionId: 'section-hidden',
},
},
});
expect(await resolveMissingPagePath(context, 'old-section')).toBeUndefined();
});
it('ignores a site redirect targeting a hidden page in the current space on an adaptive site', async () => {
const context = createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/release-notes/restricted.html',
target: 'https://docs.example.com/release-notes/restricted',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-1',
pageId: 'hidden-page',
},
},
});
expect(
await resolveMissingPagePath(context, 'release-notes/restricted.html')
).toBeUndefined();
});
it('checks target page visibility in another accessible space on an adaptive site', async () => {
const otherSpace = {
id: 'site-space-2',
space: { id: 'space-2', revision: 'revision-2' },
};
const structure = {
type: 'siteSpaces',
structure: [
{ id: 'site-space-1', space: { id: 'space-1', revision: 'revision-1' } },
otherSpace,
],
} as unknown as GitBookSiteContext['structure'];
const hiddenContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(hiddenContext, 'old')).toBeUndefined();
const visibleContext = createRedirectContext({
contextId: 'adaptive-ctx',
structure,
revisionsBySpace: { 'space-2': [{ ...page, id: 'page-secret', path: 'secret' }] },
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/other/secret',
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-2',
pageId: 'page-secret',
},
},
});
expect(await resolveMissingPagePath(visibleContext, 'old')).toEqual({
type: 'redirect',
destination: '/other/secret',
permanent: false,
});
});
it('ignores a site redirect targeting the reassigned default variant path of the current space', async () => {
const context = {
...createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/guide/missing',
target: 'https://docs.example.com/guide/v3/missing',
destination: {
kind: 'site-space',
siteSpaceId: 'site-space-v3',
},
},
structure: {
type: 'sections',
structure: [
{
object: 'site-section',
id: 'section-guide',
siteSpaces: [
{
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
],
},
],
} as unknown as GitBookSiteContext['structure'],
}),
siteSpace: {
id: 'site-space-v3',
path: 'v3',
default: true,
space: { id: 'space-v3', revision: 'revision-1' },
},
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/guide/',
}),
} as unknown as GitBookSiteContext;
expect(await resolveMissingPagePath(context, 'missing')).toBeUndefined();
});
it('keeps a redirect whose current path contains a literal question mark', async () => {
const context = createRedirectContext({
siteRedirect: {
source: '/foo/bar%3Fbaz',
target: 'https://docs.example.com/foo/bar',
},
});
expect(await resolveMissingPagePath(context, 'foo/bar?baz')).toEqual({
type: 'redirect',
destination: '/foo/bar',
permanent: false,
});
});
it('resolves a space redirect to a page', async () => {
const context = createRedirectContext({ spaceRedirectPageId: page.id });
@@ -1,8 +1,8 @@
import { permanentRedirect, redirect } from 'next/navigation';
import {
CustomizationPageActionType,
type RevisionPageDocument,
type SiteRedirect,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
@@ -11,12 +11,7 @@ import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/con
import { getDataOrNull } from '@/lib/data';
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
import { withLeadingSlash } from '@/lib/paths';
import {
findSiteSpaceBy,
findSiteSpaceByUrl,
getSiteStructureSections,
resolveSiteSpacePagePath,
} from '@/lib/sites';
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
const MAX_PAGE_URL_REDIRECTS = 5;
@@ -35,7 +30,34 @@ export type PageParams = PagePathParams | PageIdParams;
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
const pageTarget = await resolvePage(context, params);
let pageTarget = await resolvePage(context, params);
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
if (
pageTarget &&
!pageTarget.page.git &&
context.space.gitSync?.url &&
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
) {
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: pageTarget.page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
pageTarget = {
...pageTarget,
page: {
...pageTarget.page,
git: pageWithMetadata.git,
},
};
}
}
return {
context: {
@@ -119,14 +141,6 @@ export async function resolveMissingPagePath(
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
);
const currentPath = linker.toPathInSpace(redirectPathname);
let currentPathWithDefaultVariant: string | null = null;
if (context.siteSpace.default && context.siteSpace.path) {
currentPathWithDefaultVariant = linker.toPathInSpace(
`/${context.siteSpace.path}${redirectPathname}`
);
}
for (const source of redirectSources) {
// We try to resolve the site redirect
const resolvedSiteRedirect =
@@ -140,18 +154,6 @@ export async function resolveMissingPagePath(
})
));
if (resolvedSiteRedirect) {
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
// Skip self-redirects (including default-variant canonical aliases) and hidden adaptive targets.
const targetsCurrentPath =
isSameRedirectPath(currentPath, destination) ||
(currentPathWithDefaultVariant !== null &&
isSameRedirectPath(currentPathWithDefaultVariant, destination));
if (
targetsCurrentPath ||
!(await isRedirectDestinationAccessible(context, resolvedSiteRedirect.redirect))
) {
break;
}
const isPublicLiveContext =
!shareKey &&
!context.changeRequest &&
@@ -160,7 +162,7 @@ export async function resolveMissingPagePath(
!context.isLoggedInVisitor;
return {
type: 'redirect',
destination,
destination: linker.toLinkForContent(resolvedSiteRedirect.target),
permanent: Boolean(
resolvedSiteRedirect.redirect?.permanent &&
!resolvedSiteRedirect.redirect.draft &&
@@ -228,17 +230,6 @@ export async function resolveSitePageFromURL(
return null;
}
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
if (!destination.startsWith('/') || destination.startsWith('//')) {
return false;
}
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
return (
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
);
}
/**
* Transform a pathname into a candidate source for site redirect matching.
* The pathname is already percent-encoded, so each segment is decoded before being encoded
@@ -263,60 +254,6 @@ function safeDecodeURIComponent(segment: string): string {
}
}
async function isRedirectDestinationAccessible(
context: GitBookSiteContext,
siteRedirect: SiteRedirect | null
): Promise<boolean> {
if (!context.contextId || !siteRedirect?.destination) {
return true;
}
const { destination } = siteRedirect;
switch (destination.kind) {
case 'external':
return true;
case 'site-section':
return getSiteStructureSections(context.structure, { ignoreGroups: true }).some(
(section) => section.id === destination.siteSectionId
);
case 'site-space':
return Boolean(
findSiteSpaceBy(context.structure, (entry) => entry.id === destination.siteSpaceId)
);
case 'site-page': {
const target = findSiteSpaceBy(
context.structure,
(entry) => entry.id === destination.siteSpaceId
);
if (!target) {
return false;
}
if (destination.siteSpaceId === context.siteSpace.id) {
return Boolean(resolvePageId(context.revision.pages, destination.pageId));
}
const targetRevision = await getDataOrNull(
context.dataFetcher.getRevision({
spaceId: target.siteSpace.space.id,
revisionId: target.siteSpace.space.revision,
})
);
if (!targetRevision) {
return false;
}
return Boolean(resolvePageId(targetRevision.pages, destination.pageId));
}
}
}
function normalizeRedirectPathname(pathname: string): string {
const normalized = pathname
.split('/')
.filter(Boolean)
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
.join('/');
return `/${normalized}`;
}
/**
* Get the page path from the params.
*/
+2 -2
View File
@@ -36,11 +36,11 @@ export function Tag(props: { tag: RevisionTag; className?: string }) {
export function TagIcon(props: { tag: RevisionTag }) {
const { tag } = props;
if ('emoji' in tag && tag.emoji !== undefined) {
if ('emoji' in tag) {
return <Emoji code={tag.emoji} style="shrink-0" />;
}
if ('icon' in tag && tag.icon) {
if (tag.icon) {
return <Icon icon={tag.icon as IconName} className={tcls('size-[1em]', 'shrink-0')} />;
}
@@ -98,10 +98,7 @@ export const activeClasses = {
export const Button = React.forwardRef<
HTMLButtonElement | HTMLAnchorElement,
ButtonProps &
React.ButtonHTMLAttributes<HTMLButtonElement> & {
target?: React.HTMLAttributeAnchorTarget;
rel?: string;
}
React.ButtonHTMLAttributes<HTMLButtonElement> & { target?: React.HTMLAttributeAnchorTarget }
>(
(
{
@@ -167,11 +164,6 @@ export const Button = React.forwardRef<
}
}
let trailingElement = null;
if (trailing) {
trailingElement = <span className="button-trailing-icon ms-auto">{trailing}</span>;
}
const content = (
<>
{iconElement}
@@ -185,7 +177,6 @@ export const Button = React.forwardRef<
{children ?? label}
</span>
)}
{trailingElement}
</>
);
@@ -216,6 +207,7 @@ export const Button = React.forwardRef<
{...rest}
>
{content}
{trailing ? <span className="button-trailing-icon ms-auto">{trailing}</span> : null}
</button>
);
@@ -46,8 +46,6 @@ export const ar: TranslationLanguage = {
on_this_page: 'في هذه الصفحة',
next_page: 'التالي',
previous_page: 'السابق',
updates_pagination_navigation: 'التنقل بين الصفحات',
updates_pagination_range: '${1} - ${2} من أصل ${3} تحديثات',
toc_back_to_space: 'العودة إلى ${1}',
page_last_modified: 'آخر تحديث ${1}',
was_this_helpful: 'هل كان هذا مفيدا؟',
@@ -46,8 +46,6 @@ export const bg: TranslationLanguage = {
on_this_page: 'На тази страница',
next_page: 'Следваща',
previous_page: 'Предишна',
updates_pagination_navigation: 'Навигация между страниците',
updates_pagination_range: '${1} - ${2} от ${3} актуализации',
toc_back_to_space: 'Обратно към ${1}',
page_last_modified: 'Последна актуализация ${1}',
was_this_helpful: 'Беше ли полезно?',
@@ -46,8 +46,6 @@ export const cs: TranslationLanguage = {
on_this_page: 'Na této stránce',
next_page: 'Další',
previous_page: 'Předchozí',
updates_pagination_navigation: 'Navigace mezi stránkami',
updates_pagination_range: '${1} - ${2} z ${3} aktualizací',
toc_back_to_space: 'Zpět na ${1}',
page_last_modified: 'Poslední aktualizace ${1}',
was_this_helpful: 'Bylo to užitečné?',
@@ -46,8 +46,6 @@ export const da: TranslationLanguage = {
on_this_page: 'På denne side',
next_page: 'Næste',
previous_page: 'Forrige',
updates_pagination_navigation: 'Sidenavigation',
updates_pagination_range: '${1} - ${2} af ${3} opdateringer',
toc_back_to_space: 'Tilbage til ${1}',
page_last_modified: 'Sidst opdateret ${1}',
was_this_helpful: 'Var dette nyttigt?',
@@ -47,8 +47,6 @@ export const de: TranslationLanguage = {
on_this_page: 'Auf dieser Seite',
next_page: 'Nächste',
previous_page: 'Vorherige',
updates_pagination_navigation: 'Seitennavigation',
updates_pagination_range: '${1} - ${2} von ${3} Updates',
toc_back_to_space: 'Zurück zu ${1}',
page_last_modified: 'Zuletzt aktualisiert ${1}',
was_this_helpful: 'War das hilfreich?',
@@ -46,8 +46,6 @@ export const el: TranslationLanguage = {
on_this_page: 'Σε αυτήν τη σελίδα',
next_page: 'Επόμενη',
previous_page: 'Προηγούμενη',
updates_pagination_navigation: 'Πλοήγηση σελίδων',
updates_pagination_range: '${1} - ${2} από ${3} ενημερώσεις',
toc_back_to_space: 'Επιστροφή σε ${1}',
page_last_modified: 'Τελευταία ενημέρωση ${1}',
was_this_helpful: 'Ήταν χρήσιμο αυτό;',
@@ -44,8 +44,6 @@ export const en = {
on_this_page: 'On this page',
next_page: 'Next',
previous_page: 'Previous',
updates_pagination_navigation: 'Pagination Navigation',
updates_pagination_range: '${1} - ${2} of ${3} updates',
toc_back_to_space: 'Back to ${1}',
page_last_modified: 'Last updated ${1}',
was_this_helpful: 'Was this helpful?',
@@ -47,8 +47,6 @@ export const es: TranslationLanguage = {
on_this_page: 'En esta página',
next_page: 'Siguiente',
previous_page: 'Anterior',
updates_pagination_navigation: 'Navegación entre páginas',
updates_pagination_range: '${1} - ${2} de ${3} actualizaciones',
toc_back_to_space: 'Volver a ${1}',
page_last_modified: 'Última actualización ${1}',
was_this_helpful: '¿Te fue útil?',

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