Compare commits

..

3 Commits

Author SHA1 Message Date
github-actions[bot] 470c0e823b Version Packages 2026-11-26 20:57:47 +00:00
conico974 36cde8779f Emit a navigate event from the Docs Embed (#4850)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:57:16 +01:00
Nolann B. b1cfef2862 Keep each OpenAPI spec's server choice separate (#4854) 2026-11-26 21:51:40 +01:00
102 changed files with 881 additions and 702 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep links in generated Markdown usable outside the source page.
@@ -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
---
Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer Assistant questions with medium reasoning instead of low, matching AI search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump Next.js to 16.4.6 and OpenNext (Cloudflare 1.20.17, AWS 4.1.16), keeping the dev-mode OOM patch.
-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.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix horizontal page scroll caused by card carousels bleeding past the viewport.
@@ -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.
-6
View File
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render Heading 4 blocks.
-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
---
Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Remove duplicated declarations from the global stylesheet.
@@ -1,5 +0,0 @@
---
"@gitbook/icons": minor
---
Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep inline code and highlighted text readable when a paragraph crosses the bottom edge of a background page cover.
@@ -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.
@@ -1,6 +0,0 @@
---
"gitbook": patch
"@gitbook/icons": patch
---
Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Apply the default language-aware search scope to legacy search links.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load the OpenAPI stylesheet only on pages with OpenAPI blocks.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
-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.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
-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
---
Limit the MCP `searchDocumentation` tool to one language: the one the client passes in the new optional `language` argument, or else the language of the site variant the MCP endpoint is served from.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Flush insights events when the page is hidden, preload the search index at low priority and prioritize the dark page cover on dark-default sites.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published revision URLs out of search results.
@@ -1,5 +0,0 @@
---
"@gitbook/react-openapi": patch
---
Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
List the operations of an OpenAPI tag page after its description.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show H3 headings in the page outline.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render a page's search keywords in its metadata.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": minor
---
Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Respect disabled change request previews on published sites.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the search button accessible name, hoverable link previews, IME-safe Enter on Safari, cookie banner semantics, active outline item announcement and textarea shrinking.
@@ -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,6 +0,0 @@
---
"gitbook": patch
"@gitbook/embed": patch
---
Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send only the site origin as referrer to third parties, and only let the embedding page open the embed messaging channel.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Remove the ChatGPT-specific plain text response for Markdown and llms.txt routes; these now always serve `text/markdown`.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Remove the MCP server link from the screen-reader-only agent directive in page HTML.
@@ -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
---
Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show loading rows shaped like search results while search waits for the server.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Stop caching site search results in the framework cache, so every search reaches the API.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show one server-ordered search list and open its top result on Enter.
@@ -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
---
Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render small cards in a responsive four-column grid and carousel.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Ignore tag category references when displaying assigned tags and update filters.
@@ -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.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Restrict updates pagination to single top-level Updates blocks.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix Updates tag loading skeleton and scroll to top on pagination.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Paginate published Updates pages with more than 50 entries into 20-entry pages.
+32 -32
View File
@@ -49,7 +49,7 @@
},
"packages/embed": {
"name": "@gitbook/embed",
"version": "0.7.0",
"version": "0.8.0",
"dependencies": {
"@gitbook/api": "catalog:",
"bidc": "catalog:",
@@ -109,7 +109,7 @@
},
"packages/gitbook": {
"name": "gitbook",
"version": "0.28.2",
"version": "0.29.0",
"dependencies": {
"@base-ui/react": "catalog:",
"@cloudflare/workers-types": "^4.20251011.0",
@@ -228,7 +228,7 @@
},
"packages/icons": {
"name": "@gitbook/icons",
"version": "0.5.0",
"version": "0.6.0",
"bin": {
"gitbook-icons": "./bin/gitbook-icons.js",
},
@@ -266,7 +266,7 @@
},
"packages/react-contentkit": {
"name": "@gitbook/react-contentkit",
"version": "0.7.18",
"version": "0.7.19",
"dependencies": {
"@gitbook/api": "catalog:",
"@gitbook/icons": "workspace:*",
@@ -309,7 +309,7 @@
},
"packages/react-openapi": {
"name": "@gitbook/react-openapi",
"version": "2.0.1",
"version": "2.0.2",
"dependencies": {
"@base-ui/react": "catalog:",
"@gitbook/expr": "workspace:*",
@@ -1025,43 +1025,43 @@
"@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dlI5SY7XYQCiCBafntWagCR6HcAJB/NpsLtdlPx8x08+Osz8Ok1HHz1GZuusegCe/VoJ6pAnF5a4pd5OZAq7qQ=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.93.0", "", { "os": "android", "cpu": "arm" }, "sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.95.0", "", { "os": "android", "cpu": "arm" }, "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.93.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.95.0", "", { "os": "android", "cpu": "arm64" }, "sha512-uAIGZQ9uJVUeogeWOSboI3F7twOuM4mNuZcHXD9+LdYLcWp7J6kbtRUXJ6GVqcs5E0Cjb4emmSBK9FNrkGuhqQ=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.93.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.95.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Ogh1vfHO5vshKRop/He46r+WqC5BTqonYwhB4fp9e2gvOFvg1Xi6XsHTuM/lBSH85ZcaG+DS99EMAy9GcwDong=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.93.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.95.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-kTrE1xfpQUBMMS50Ws6KY92N8OsJ8LE6JqxKqkHEY3KdsmguQ6kKVGSjzyt1HLwsSi0fQCvNRog8YRBBovD1AA=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.93.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.95.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ho7E1VCInK0VnpneRaI1BEpe1ceJE8VjxP2O9THWdReV6bth1Q4+80kYVGGK47mHRyZ2NGztQZ2dWRo6j1lavA=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-94afnouMHcnHr/OtRh07gG5LehC9M0GjiSoik3xxTtrmq6cWxXOTAhYlBtxa67u/GlycbnHlDoGJfYlTshcr/w=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LEeclqV1/fafxPgJWN21Bri6HBBBZpEFluq/ZH7Avvu9HjJh/XOn6WwogJqX9X7pG2aITZ2nRH39+sUKEQt2WA=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.93.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.95.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-EpXpEQKmgtkvc6RyU84LM1e3CrVDWQkgghVzf1hMGgwjBzgKAJ/QntHgnzmu5cNeLBfa7GPCY+gGXxEll8Adcg=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.93.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.95.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-+96Md8c2BAgFp8nWHrUrpqba87DoU+HVJYIun6qA+QKFoeNd3xAWq1JYE6da4nVli9GgwRpfncfRePcgmQQaIQ=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.93.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.95.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-6yG99vsXct3Uv536w6Z1s03w2makRKnE0q3eJSmf+W/IwPmO56QLk8XUA6ebu/R5peCbJ67HmcWqACH+kg/6Bg=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.93.0", "", { "os": "linux", "cpu": "none" }, "sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.95.0", "", { "os": "linux", "cpu": "none" }, "sha512-Eir0Z4ldh55AsQUqVDlLF4Pw3lSFXIdAl8ZNgU8tp/gTwT9JVCzWY0o3+ys9pCcpTN0vCqBwwuQfAUxzbIgvcQ=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.93.0", "", { "os": "linux", "cpu": "none" }, "sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.95.0", "", { "os": "linux", "cpu": "none" }, "sha512-ceRx+K2WJ7C3tIv+XjZS28oAoZ7DY29ZcWChPdXG5M100phI72FRDYwGRlWZEeDfmkROnarLTMKnnrQAtsC42Q=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.93.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.95.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-WbD3sM08ZDk2QE6060wK/omihQKbRm+LVzKIg4W5zNTbEhYJChciqX49UZuqW59RGF+wBUxzAup7egUIESTjUA=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.93.0", "", { "os": "linux", "cpu": "x64" }, "sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.95.0", "", { "os": "linux", "cpu": "x64" }, "sha512-F4ST2ZkFIiLL9OKyRCyC0KQQpwM5WIv0GTcMiZuYVa6xSRJHR05iVRqst+arOVudEPkhP47EnbuoC9UfVCYDyg=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.93.0", "", { "os": "linux", "cpu": "x64" }, "sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.95.0", "", { "os": "linux", "cpu": "x64" }, "sha512-hEpYDZatpuxLrWlTlkwhHZ1e8QkL02aFS55BPQX1XA9iOd+yUEADGFF1iY6z+xkw6RkpzXFrtnDFe4/JNOLSRA=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.93.0", "", { "os": "none", "cpu": "arm64" }, "sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.95.0", "", { "os": "none", "cpu": "arm64" }, "sha512-+JwIH9/uLgQXfxBvOAKzvp616m5i0fBR5ELEBHm5D+++fStBZ+74T7YW4xBpX13zNU2blr52Swoe3GTF1JyqRg=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.93.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.95.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-pzJgcp3WkOSchukg5y5pn5mVIQ6P83RDI79YJ9gQZKed1pOgjhrmlc5AMizjuq6/P8VifhxzBsMqYI6LLjO2TA=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.93.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.95.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-54MeQvLRXkJqF1nEFs7wb73SrnurZJQy9fVK4NdEwumNKVwyUUxpGHhvfDMIY2NqJZS7kz0pY9uVty5664Gt1Q=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.93.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.95.0", "", { "os": "win32", "cpu": "x64" }, "sha512-I/Fn+Fed1qzb1k2uRjMe2VRtRN1+ZObyU+E76B6v/Ul3Z6JdeAW5zBHSe0n5d8a0ZyU4iorzVy0Rw9LYgo3MSQ=="],
"@panzoom/panzoom": ["@panzoom/panzoom@4.6.1", "", {}, "sha512-ogf/KhHHjj+DYAvHfaf3TXMQ8OE36pJtKpabLlx1OmpjcgtpCvkUoCiNONA8kuVRPGJdLiqMf0n8LRFXj1OyuA=="],
@@ -1367,17 +1367,17 @@
"@tsconfig/strictest": ["@tsconfig/strictest@2.0.6", "", {}, "sha512-tPOhmDhIUcDjvpDDYyiUdssP84Eqm7n5KxJe5J3/g+s6xoDIPAf+SIn06dhw7VkhxIvLOnhDDrX7tsqMHNEhDg=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.11.11", "", { "os": "darwin", "cpu": "x64" }, "sha512-HMMeUIEAsmyIbSYn1ySvF/4gGMa0joiTMq4dQDuloIAnOpbtFT3JEiVsYnASdTWDXvplbRbZlqjU1EBeSR9G1A=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.11.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-5IT29i4j55E5O66+la7L8Y46ut7dFaNZqrgUIYYNtcpMt9Ql7aYnSQb/6tZ+prE2AfX1RBCAtRJE41txS2rG3w=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.11.11", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+8iySNgqYWY6PZYUQzYu6zn0C04z2OEq1vQ6oMGsJ9sxN6wOpg1gzi1AJ5VKDHviWvMUjhqng51hTEQZOuiqYQ=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.11.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-YFJPayVNlhSPRIZSeERiZYGKKqPs6N6qGhim8J3GtBdv5ZjUNF1ixfnAAyCVTqFEnMSkn1W7F0Y07kca8EjWsg=="],
"@turbo/linux-64": ["@turbo/linux-64@2.11.11", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-uImTKFYCFKsoFxjaXeJXlMPv4uU3OIIDjyzoIwYVqOtu9LnCZ/5/fzu/WP6+G9YfwGAPRplTHkKFfcI5t97RGw=="],
"@turbo/linux-64": ["@turbo/linux-64@2.11.13", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-R5RIQflV4ffBDNuUwjmtmzIr6Y2UeyeeHTtultYF7cnFn3tG1RZ4GRBlpjUhHB6JxuR7l1B450hlbzdtlD3ghg=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.11.11", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-Y7xffSVfyyYRGzNy6PLdrFL4xXN6iTuR3W0SyJvH/yd3d4defA6dansZwJpPDVnIpD8a2Qn256DwY/Qin4Ip4g=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.11.13", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-AwV8pVO/cH/lwx1B7SGfzUA/3e6vmPaygFp9NOSRESs6t3Wr63zrBuXlluDogAOIxIMlHDB2ZbBueDsBnQxh2Q=="],
"@turbo/windows-64": ["@turbo/windows-64@2.11.11", "", { "os": "win32", "cpu": "x64" }, "sha512-e2WqNtkPGo3QDwNNwwBo89Dx3PtSJ9Wp9QuRNzn80rrRnSHB+1mfBMZTpdHjA8/G/sG9rl76TdWdpgVsimjRdg=="],
"@turbo/windows-64": ["@turbo/windows-64@2.11.13", "", { "os": "win32", "cpu": "x64" }, "sha512-PGXYTaFaN3FZloe4RffNGJmfB+TIWlqQgKK1PVyKwPN+PUzxGa+byxHBWFHredMaVbnUc6L/F6/QR4iHyM/wug=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.11.11", "", { "os": "win32", "cpu": "arm64" }, "sha512-LURivfmgv34Osm8NR1gZGx4vdlux9KAgRM+FoooXNG0838ff0+akWZ76iPSke0NS2rsf7Z4Gw+YSaygzNTZuRA=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.11.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-YdRHWstBUHWt/eChOEM4f9LT0dPiWK5SNgtV77bLCr3JNke9M5E7metqelNYj+tXe36dH0BZrk2CMnFlWqHKng=="],
"@tusbar/cache-control": ["@tusbar/cache-control@1.0.2", "", {}, "sha512-PXfjYTYBVvMPYCLDWj+xIOA9ITFbbhWCHzLcqUCJ5TPGm4JO4cxpGb7x3K8Q1K1ADgNgfBxLsDcTMVRydtZB9A=="],
@@ -2691,7 +2691,7 @@
"oxfmt": ["oxfmt@0.62.0", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.62.0", "@oxfmt/binding-android-arm64": "0.62.0", "@oxfmt/binding-darwin-arm64": "0.62.0", "@oxfmt/binding-darwin-x64": "0.62.0", "@oxfmt/binding-freebsd-x64": "0.62.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.62.0", "@oxfmt/binding-linux-arm-musleabihf": "0.62.0", "@oxfmt/binding-linux-arm64-gnu": "0.62.0", "@oxfmt/binding-linux-arm64-musl": "0.62.0", "@oxfmt/binding-linux-ppc64-gnu": "0.62.0", "@oxfmt/binding-linux-riscv64-gnu": "0.62.0", "@oxfmt/binding-linux-riscv64-musl": "0.62.0", "@oxfmt/binding-linux-s390x-gnu": "0.62.0", "@oxfmt/binding-linux-x64-gnu": "0.62.0", "@oxfmt/binding-linux-x64-musl": "0.62.0", "@oxfmt/binding-openharmony-arm64": "0.62.0", "@oxfmt/binding-win32-arm64-msvc": "0.62.0", "@oxfmt/binding-win32-ia32-msvc": "0.62.0", "@oxfmt/binding-win32-x64-msvc": "0.62.0" }, "peerDependencies": { "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-vxgGHTmnDU9j4CX7dDBLzxgmHxfda/yPcgJkGCMUSCwRmz+euo/V08xXLNgXTeqAB9Fhf3Pe2nO1RNKLCVgphQ=="],
"oxlint": ["oxlint@1.93.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.93.0", "@oxlint/binding-android-arm64": "1.93.0", "@oxlint/binding-darwin-arm64": "1.93.0", "@oxlint/binding-darwin-x64": "1.93.0", "@oxlint/binding-freebsd-x64": "1.93.0", "@oxlint/binding-linux-arm-gnueabihf": "1.93.0", "@oxlint/binding-linux-arm-musleabihf": "1.93.0", "@oxlint/binding-linux-arm64-gnu": "1.93.0", "@oxlint/binding-linux-arm64-musl": "1.93.0", "@oxlint/binding-linux-ppc64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-musl": "1.93.0", "@oxlint/binding-linux-s390x-gnu": "1.93.0", "@oxlint/binding-linux-x64-gnu": "1.93.0", "@oxlint/binding-linux-x64-musl": "1.93.0", "@oxlint/binding-openharmony-arm64": "1.93.0", "@oxlint/binding-win32-arm64-msvc": "1.93.0", "@oxlint/binding-win32-ia32-msvc": "1.93.0", "@oxlint/binding-win32-x64-msvc": "1.93.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2005", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA=="],
"oxlint": ["oxlint@1.95.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.95.0", "@oxlint/binding-android-arm64": "1.95.0", "@oxlint/binding-darwin-arm64": "1.95.0", "@oxlint/binding-darwin-x64": "1.95.0", "@oxlint/binding-freebsd-x64": "1.95.0", "@oxlint/binding-linux-arm-gnueabihf": "1.95.0", "@oxlint/binding-linux-arm-musleabihf": "1.95.0", "@oxlint/binding-linux-arm64-gnu": "1.95.0", "@oxlint/binding-linux-arm64-musl": "1.95.0", "@oxlint/binding-linux-ppc64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-musl": "1.95.0", "@oxlint/binding-linux-s390x-gnu": "1.95.0", "@oxlint/binding-linux-x64-gnu": "1.95.0", "@oxlint/binding-linux-x64-musl": "1.95.0", "@oxlint/binding-openharmony-arm64": "1.95.0", "@oxlint/binding-win32-arm64-msvc": "1.95.0", "@oxlint/binding-win32-ia32-msvc": "1.95.0", "@oxlint/binding-win32-x64-msvc": "1.95.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA=="],
"p-filter": ["p-filter@2.1.0", "", { "dependencies": { "p-map": "^2.0.0" } }, "sha512-ZBxxZ5sL2HghephhpGAQdoskxplTwr7ICaehZwLIlfL6acuVgZPm8yBNuRAFBGEqtD/hmUeq9eqLg2ys9Xr/yw=="],
@@ -3123,7 +3123,7 @@
"tsx": ["tsx@4.21.0", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"turbo": ["turbo@2.11.11", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.11", "@turbo/darwin-arm64": "2.11.11", "@turbo/linux-64": "2.11.11", "@turbo/linux-arm64": "2.11.11", "@turbo/windows-64": "2.11.11", "@turbo/windows-arm64": "2.11.11" }, "bin": { "turbo": "bin/turbo" } }, "sha512-AI4UJbUE/2cVZdoXJ4PODc8qvrjhQQX9Fa93eKGOI6Ims/w7+kUIb9T1jhlgSnZcf+gtUruci/ohSwqtNNC5Yw=="],
"turbo": ["turbo@2.11.13", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.13", "@turbo/darwin-arm64": "2.11.13", "@turbo/linux-64": "2.11.13", "@turbo/linux-arm64": "2.11.13", "@turbo/windows-64": "2.11.13", "@turbo/windows-arm64": "2.11.13" }, "bin": { "turbo": "bin/turbo" } }, "sha512-2EZ8StW6tqaj71HGF60oUOmJrPQHidmZ5dcwv2VORofya9JthVrfZhxbzRMx/QxjPwYi754i2h5RFsZSDzpnaQ=="],
"type": ["type@2.7.3", "", {}, "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ=="],
+2 -2
View File
@@ -7,8 +7,8 @@
"devDependencies": {
"@changesets/cli": "^2.31.1",
"oxfmt": "^0.62.0",
"oxlint": "^1.93.0",
"turbo": "^2.11.11",
"oxlint": "^1.95.0",
"turbo": "^2.11.13",
"vercel": "50.37.3"
},
"packageManager": "bun@1.3.7",
+1 -1
View File
@@ -1,2 +1,2 @@
dist/
standalone/
/standalone/
+12
View File
@@ -1,5 +1,17 @@
# @gitbook/embed
## 0.8.0
### Minor Changes
- a9535cd: Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
- 36cde87: Emit a `navigate` event from the Docs Embed when the reader opens a page or switches tab, with the page's path, URL and title. Listen to it, and to `close` and `escape`, with `GitBook('on', ...)` in the standalone script or the `onNavigate`, `onClose` and `onEscape` props of `<GitBookFrame>`.
- 6b2e806: Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
### Patch Changes
- 65210b7: Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
## 0.7.0
### Minor Changes
+41 -3
View File
@@ -72,6 +72,19 @@ GitBook('configure', {
See the [Configuration](#configuration) section for all available options.
### Example: Listening to events
```javascript
// The reader opened a page in the docs tab, or switched to the assistant or search tab
GitBook('on', 'navigate', (event) => {
if (event.tab === 'docs') {
console.log('Reading', event.title, event.path, event.url);
}
});
```
`GitBook('on', ...)` returns a function that removes the listener once the script has loaded. See [Events](#events).
## As a package from NPM
Install the package: `npm install @gitbook/embed` and import it in your web application:
@@ -132,6 +145,11 @@ frame.on('close', () => {
frame.on('escape', () => {
closeHelpPanel();
});
// The reader opened a page in the docs tab, or switched to another tab
const unsubscribe = frame.on('navigate', (event) => {
console.log('Navigated to:', event.tab === 'docs' ? event.path : event.tab);
});
```
## As React components
@@ -162,6 +180,12 @@ import { GitBookProvider, GitBookFrame } from '@gitbook/embed/react';
]}
tools={[/* ... */]}
closeButton
onNavigate={(event) => {
if (event.tab === 'docs') {
setCurrentDocsPage(event.path);
}
}}
onClose={() => setHelpPanelOpen(false)}
/>
</GitBookProvider>
```
@@ -194,7 +218,7 @@ function MyComponent() {
| **Post message** | `GitBook('postUserMessage', message)` | `frame.postUserMessage(message)` | Via frame client |
| **Clear chat** | `GitBook('clearChat')` | `frame.clearChat()` | Via frame client |
| **Configure** | `GitBook('configure', settings)` | `frame.configure(settings)` | Props on `<GitBookFrame>` |
| **Event listeners** | ❌ | `frame.on(event, listener)` | Via frame client |
| **Event listeners** | `GitBook('on', event, listener)` | `frame.on(event, listener)` | `onNavigate`, `onClose`, `onEscape` props |
| **Unload** | `GitBook('unload')` | ❌ | ❌ |
## Method Signatures
@@ -212,6 +236,7 @@ function MyComponent() {
- `GitBook('postUserMessage', message: string)` - Post message to chat
- `GitBook('clearChat')` - Clear chat history
- `GitBook('configure', settings: {...})` - Configure widget
- `GitBook('on', event: string, listener: Function)` → `() => void` - Listen to an [event](#events); returns a function that removes the listener (once the script has loaded)
- `GitBook('unload')` - Unload widget
### NPM Package
@@ -227,17 +252,30 @@ function MyComponent() {
- `frame.postUserMessage(message: string)` → `void`
- `frame.clearChat()` → `void`
- `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void`
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). Events: `close`, `escape`
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). See [Events](#events)
### React Components
**Components:**
- `<GitBookProvider siteURL: string>` - Provider component
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props)
- `<GitBookFrame {...props}>` - Frame component (accepts all config options as props, and `onNavigate`, `onClose`, `onEscape` callbacks for the [events](#events))
**Hooks:**
- `useGitBook()` → `GitBookClient` (must be used within `<GitBookProvider>`)
## Events
| Event | Listener | When |
|-------|----------|------|
| `navigate` | `(event: GitBookNavigateEvent) => void` | The reader opened a page in the docs tab, or switched to another tab. Also sent for the tab the embed first opens on. |
| `close` | `() => void` | The built-in close button was clicked. |
| `escape` | `() => void` | Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it. |
`GitBookNavigateEvent` is one of:
- `{ tab: 'docs', path: string, url: string, title: string }`: `path` is the page's path from the root of the site (e.g. `/getting-started/quickstart`) and can be passed back to `navigateToPage`; `url` is its published URL, without query parameters; `title` is the page's title.
- `{ tab: 'assistant' }` or `{ tab: 'search' }`
# Configuration
Configuration options are available across usage methods as follows:
+1 -1
View File
@@ -13,7 +13,7 @@
}
},
"sideEffects": false,
"version": "0.7.0",
"version": "0.8.0",
"license": "Apache-2.0",
"dependencies": {
"@gitbook/api": "catalog:",
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import type { FrameToParentMessage } from './protocol';
// The frame talks to the iframe over postMessage; capture the receive handler to play the frame.
let receive: (message: FrameToParentMessage) => void = () => {};
mock.module('bidc', () => ({
createChannel: () => ({
send: () => {},
receive: (handler: typeof receive) => {
receive = handler;
},
}),
}));
const { createGitBookFrame } = await import('./createGitBookFrame');
function createFrame() {
return createGitBookFrame({ contentWindow: {}, allow: '' } as unknown as HTMLIFrameElement);
}
describe('createGitBookFrame.on', () => {
beforeEach(() => {
receive = () => {};
});
it('calls navigate listeners with the page the reader moved to', () => {
const frame = createFrame();
const events: unknown[] = [];
frame.on('navigate', (event) => events.push(event));
receive({
type: 'navigate',
tab: 'docs',
path: '/getting-started/quickstart',
url: 'https://example.com/docs/getting-started/quickstart',
title: 'Quickstart',
});
expect(events).toEqual([
{
tab: 'docs',
path: '/getting-started/quickstart',
url: 'https://example.com/docs/getting-started/quickstart',
title: 'Quickstart',
},
]);
});
it('calls navigate listeners when the reader switches to another tab', () => {
const frame = createFrame();
const events: unknown[] = [];
frame.on('navigate', (event) => events.push(event));
receive({ type: 'navigate', tab: 'assistant' });
expect(events).toEqual([{ tab: 'assistant' }]);
});
it('only calls the listeners of the event that was received', () => {
const frame = createFrame();
const calls: string[] = [];
frame.on('close', () => calls.push('close'));
frame.on('escape', () => calls.push('escape'));
frame.on('navigate', () => calls.push('navigate'));
receive({ type: 'escape' });
expect(calls).toEqual(['escape']);
});
it('stops calling a listener once it is unsubscribed', () => {
const frame = createFrame();
const calls: string[] = [];
const unsubscribe = frame.on('navigate', () => calls.push('navigate'));
unsubscribe();
receive({ type: 'navigate', tab: 'search' });
expect(calls).toEqual([]);
});
});
@@ -3,6 +3,7 @@ import { createChannel } from 'bidc';
import type {
FrameToParentMessage,
GitBookEmbeddableConfiguration,
GitBookFrameEvents,
ParentToFrameMessage,
} from './protocol';
@@ -42,8 +43,11 @@ export type GitBookFrameClient = {
*
* - `close`: the built-in close button was clicked.
* - `escape`: Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it.
* - `navigate`: the reader opened a page in the docs tab, or switched to another tab.
*/
on: (event: string, listener: (...args: any[]) => void) => () => void;
on<E extends keyof GitBookFrameEvents>(event: E, listener: GitBookFrameEvents[E]): () => void;
// Kept so callers typed against the earlier `string` signature still compile.
on(event: string, listener: (...args: any[]) => void): () => void;
};
/**
@@ -67,9 +71,16 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
channel.receive((message: FrameToParentMessage) => {
console.log('[gitbook:embed] received message', message);
if (message.type === 'close' || message.type === 'escape') {
const listeners = events.get(message.type) || [];
listeners.forEach((listener) => listener());
switch (message.type) {
case 'close':
case 'escape':
emit(message.type);
break;
case 'navigate': {
const { type: _type, ...event } = message;
emit('navigate', event);
break;
}
}
});
@@ -79,6 +90,12 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
};
const events = new Map<string, ((...args: any[]) => void)[]>();
const emit = <E extends keyof GitBookFrameEvents>(
event: E,
...args: Parameters<GitBookFrameEvents[E]>
) => {
(events.get(event) || []).forEach((listener) => listener(...args));
};
const configuration: GitBookEmbeddableConfiguration = {
tabs: ['assistant', 'search', 'docs'],
@@ -102,7 +119,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
sendToFrame({ type: 'configure', settings: configuration });
},
clearChat: () => sendToFrame({ type: 'clearChat' }),
on: (event, listener) => {
on: (event: string, listener: (...args: any[]) => void) => {
const listeners = events.get(event) || [];
listeners.push(listener);
events.set(event, listeners);
+36 -1
View File
@@ -134,6 +134,38 @@ export type ParentToFrameMessage =
type: 'navigateToAssistant';
};
/**
* Where the reader is in the embed, sent with the `navigate` event.
*/
export type GitBookNavigateEvent =
| {
tab: 'docs';
/**
* Path of the page from the root of the site (e.g. `/getting-started/quickstart`),
* in the form `navigateToPage` accepts.
*/
path: string;
/** Published URL of the page, without query parameters. */
url: string;
/** Title of the page. */
title: string;
}
| {
tab: 'assistant' | 'search';
};
/**
* Events emitted by the frame, and the arguments their listeners receive.
*/
export type GitBookFrameEvents = {
/** The built-in close button was clicked. */
close: () => void;
/** Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it. */
escape: () => void;
/** The reader opened a page in the docs tab, or switched to another tab. */
navigate: (event: GitBookNavigateEvent) => void;
};
/**
* Messages sent from the frame to the parent.
*/
@@ -144,4 +176,7 @@ export type FrameToParentMessage =
| {
/** Escape was pressed inside the frame and nothing in the frame handled it. */
type: 'escape';
};
}
| ({
type: 'navigate';
} & GitBookNavigateEvent);
+31
View File
@@ -6,11 +6,21 @@ import type {
GetFrameURLOptions,
GitBookEmbeddableConfiguration,
GitBookFrameClient,
GitBookNavigateEvent,
} from '../client';
import { useGitBook } from './GitBookProvider';
export type GitBookFrameProps = {
className?: string;
/** Called when the reader opens a page in the docs tab, or switches to another tab. */
onNavigate?: (event: GitBookNavigateEvent) => void;
/** Called when the built-in close button is clicked. */
onClose?: () => void;
/** Called when Escape is pressed inside the frame and nothing in it (a menu, a dialog) used it. */
onEscape?: () => void;
} & GetFrameURLOptions &
Partial<GitBookEmbeddableConfiguration>;
@@ -32,6 +42,9 @@ export function GitBookFrame(props: GitBookFrameProps) {
trademark = true,
closeButton = false,
assistantName,
onNavigate,
onClose,
onEscape,
} = props;
const frameRef = useRef<HTMLIFrameElement>(null);
@@ -49,6 +62,24 @@ export function GitBookFrame(props: GitBookFrameProps) {
}
}, [gitbook]);
// Read through a ref so inline callbacks don't resubscribe on every render.
const handlers = useRef({ onNavigate, onClose, onEscape });
useEffect(() => {
handlers.current = { onNavigate, onClose, onEscape };
});
useEffect(() => {
if (!gitbookFrame) {
return;
}
const unsubscribes = [
gitbookFrame.on('navigate', (event) => handlers.current.onNavigate?.(event)),
gitbookFrame.on('close', () => handlers.current.onClose?.()),
gitbookFrame.on('escape', () => handlers.current.onEscape?.()),
];
return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
}, [gitbookFrame]);
useEffect(() => {
gitbookFrame?.configure({
tabs,
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'bun:test';
import type { GitBookFrameClient, GitBookFrameEvents } from '../client';
import { createFrameEventRelay } from './events';
type Listeners = { [E in keyof GitBookFrameEvents]?: GitBookFrameEvents[E][] };
/** A frame client that only records listeners, so a test can emit events from the frame. */
function createFakeFrame() {
const listeners: Listeners = {};
const frame = {
on: (event: keyof GitBookFrameEvents, listener: (...args: any[]) => void) => {
(listeners[event] ??= []).push(listener);
return () => {
listeners[event] = listeners[event]?.filter((l) => l !== listener) as any;
};
},
} as unknown as GitBookFrameClient;
const emit = (event: keyof GitBookFrameEvents, ...args: any[]) =>
listeners[event]?.forEach((listener) => (listener as any)(...args));
return { frame, emit };
}
describe('createFrameEventRelay', () => {
it('forwards events from the attached frame to listeners registered before it existed', () => {
const relay = createFrameEventRelay();
const events: unknown[] = [];
relay.on('navigate', (event) => events.push(event));
const { frame, emit } = createFakeFrame();
relay.attach(frame);
emit('navigate', { tab: 'search' });
expect(events).toEqual([{ tab: 'search' }]);
});
it('keeps listeners when the frame is replaced, and ignores the old frame', () => {
const relay = createFrameEventRelay();
const events: unknown[] = [];
relay.on('navigate', (event) => events.push(event));
const first = createFakeFrame();
relay.attach(first.frame);
const second = createFakeFrame();
relay.attach(second.frame);
first.emit('navigate', { tab: 'search' });
second.emit('navigate', { tab: 'assistant' });
expect(events).toEqual([{ tab: 'assistant' }]);
});
it('stops calling a listener once it is unsubscribed', () => {
const relay = createFrameEventRelay();
const calls: string[] = [];
const unsubscribe = relay.on('close', () => calls.push('close'));
const { frame, emit } = createFakeFrame();
relay.attach(frame);
unsubscribe();
emit('close');
expect(calls).toEqual([]);
});
it('stops forwarding once detached', () => {
const relay = createFrameEventRelay();
const calls: string[] = [];
relay.on('escape', () => calls.push('escape'));
const { frame, emit } = createFakeFrame();
relay.attach(frame);
relay.detach();
emit('escape');
expect(calls).toEqual([]);
});
});
+40
View File
@@ -0,0 +1,40 @@
import type { GitBookFrameClient, GitBookFrameEvents } from '../client';
const FRAME_EVENTS: (keyof GitBookFrameEvents)[] = ['close', 'escape', 'navigate'];
/**
* Hold the host's listeners outside any one frame: the widget rebuilds its iframe on a new `init`
* and only creates it once opened, but `GitBook('on', …)` can be called at any time.
*/
export function createFrameEventRelay() {
const listeners = new Map<keyof GitBookFrameEvents, Set<(...args: any[]) => void>>();
let detachFrame: (() => void) | undefined;
const detach = () => {
detachFrame?.();
detachFrame = undefined;
};
return {
on<E extends keyof GitBookFrameEvents>(event: E, listener: GitBookFrameEvents[E]) {
const set = listeners.get(event) ?? new Set();
set.add(listener);
listeners.set(event, set);
return () => {
set.delete(listener);
};
},
attach(frame: GitBookFrameClient) {
detach();
const unsubscribes = FRAME_EVENTS.map((event) =>
frame.on(event, (...args: any[]) => {
listeners.get(event)?.forEach((listener) => listener(...args));
})
);
detachFrame = () => unsubscribes.forEach((unsubscribe) => unsubscribe());
},
detach,
};
}
+16 -4
View File
@@ -1,13 +1,14 @@
import './style.css';
import {
type CreateGitBookOptions,
type GetFrameURLOptions,
type GitBookClient,
type GitBookEmbeddableConfiguration,
type GitBookFrameClient,
type GitBookFrameEvents,
createGitBook,
} from '../client';
import { createFrameEventRelay } from './events';
export type GitBook = () => void;
@@ -35,7 +36,11 @@ type StandaloneCalls =
// Navigate to a page
| ['navigateToPage', string]
// Navigate to the assistant
| ['navigateToAssistant'];
| ['navigateToAssistant']
// Listen to an event from the embed, returns a function to stop listening
| {
[E in keyof GitBookFrameEvents]: ['on', E, GitBookFrameEvents[E]];
}[keyof GitBookFrameEvents];
type StandaloneConfiguration = {
/** Configure the button to open the embed */
@@ -47,7 +52,7 @@ type StandaloneConfiguration = {
};
};
export type GitBookStandalone = ((...args: StandaloneCalls) => void) & {
export type GitBookStandalone = ((...args: StandaloneCalls) => void | (() => void)) & {
q?: StandaloneCalls[];
};
@@ -56,6 +61,7 @@ let _client: GitBookClient | undefined;
let _frame: GitBookFrameClient | undefined;
let frameOptions: GetFrameURLOptions | undefined;
let frameConfigured = false;
const frameEvents = createFrameEventRelay();
let frameConfiguration: GitBookEmbeddableConfiguration & StandaloneConfiguration = {
button: {
label: 'Ask',
@@ -152,6 +158,7 @@ function getIframe() {
widgetWindow.classList.add('hidden');
widgetButton.classList.remove('open');
});
frameEvents.attach(_frame);
// A new frame starts from the site's own defaults, so replay whatever the host configured.
if (frameConfigured) {
_frame.configure(frameConfiguration);
@@ -160,7 +167,7 @@ function getIframe() {
return { iframe: widgetIframe, frame: _frame };
}
const GitBook = (...args: StandaloneCalls) => {
const GitBook = (...args: StandaloneCalls): void | (() => void) => {
switch (args[0]) {
case 'init': {
// `~gitbook/embed/script.js` already calls `init`, so an integrator following the docs
@@ -185,6 +192,7 @@ const GitBook = (...args: StandaloneCalls) => {
widgetIframe.remove();
widgetIframe = undefined;
_frame = undefined;
frameEvents.detach();
if (wasOpen) {
getIframe();
}
@@ -194,6 +202,7 @@ const GitBook = (...args: StandaloneCalls) => {
case 'unload':
_client = undefined;
_frame = undefined;
frameEvents.detach();
widgetIframe?.remove();
widgetIframe = undefined;
frameOptions = undefined;
@@ -272,6 +281,9 @@ const GitBook = (...args: StandaloneCalls) => {
case 'navigateToAssistant':
getIframe().frame.navigateToAssistant();
break;
case 'on':
// Not `getIframe()`: listening shouldn't load the frame before the reader opens it.
return frameEvents.on(args[1], args[2]);
}
};
+87
View File
@@ -1,5 +1,92 @@
# gitbook
## 0.29.0
### Minor Changes
- 7ad3fff: Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
### Patch Changes
- 4eb32b1: Keep links in generated Markdown usable outside the source page.
- 13c0ff0: Handle optional emoji and icon values when rendering tags.
- 5755e6d: Point agents to the site MCP server from Markdown pages, the page HTML, llms.txt and llms-full.txt.
- bd38317: Serve the site AI Catalog as specification version 0.9, with identifiers in its `urn:air:{publisher}:{name}:{kind}` format.
- 960d7ec: Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
- 818cbbe: Answer Assistant questions with medium reasoning instead of low, matching AI search.
- ddccd3d: Bump Next.js to 16.4.6 and OpenNext (Cloudflare 1.20.17, AWS 4.1.16), keeping the dev-mode OOM patch.
- b0f3822: Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
- a3d37f3: Bump @opennextjs/aws to 4.2.1 and @opennextjs/cloudflare to 1.20.19.
- 0c3a51e: Fix horizontal page scroll caused by card carousels bleeding past the viewport.
- 68e3dac: Retry direct site search on the site's own domain after a network error or timeout.
- 22df281: 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.
- a9535cd: Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
- 36cde87: Emit a `navigate` event from the Docs Embed when the reader opens a page or switches tab, with the page's path, URL and title. Listen to it, and to `close` and `escape`, with `GitBook('on', ...)` in the standalone script or the `onNavigate`, `onClose` and `onEscape` props of `<GitBookFrame>`.
- 6b2e806: Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
- fa87151: Render Heading 4 blocks.
- 7e2658a: Reduce the wait after typing in site search to 100 ms.
- 7af524a: Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
- ae1e370: Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
- c85d84f: Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
- 5997a66: Remove duplicated declarations from the global stylesheet.
- c3df458: Keep inline code and highlighted text readable when a paragraph crosses the bottom edge of a background page cover.
- 1ecd2ca: Keep published pages available when an integration block needs its connection or settings checked.
- 7cee30e: Keep published site search results visible while visitors refine a query.
- 265ca4b: Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
- 76e1abd: Apply the default language-aware search scope to legacy search links.
- 9fcde5f: Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle.
- 9b5b8c8: Load the OpenAPI stylesheet only on pages with OpenAPI blocks.
- a3b5ce5: Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
- 21b96e1: Count only MCP tool calls in the MCP request insights event.
- adbc358: Answer GET requests to the MCP endpoint with an `Allow: POST` header.
- fa7d4a9: Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
- 596b8c5: Support MCP protocol version 2025-11-25 on published site MCP servers.
- adfd921: Limit the MCP `searchDocumentation` tool to one language: the one the client passes in the new optional `language` argument, or else the language of the site variant the MCP endpoint is served from.
- 19660ed: Flush insights events when the page is hidden, preload the search index at low priority and prioritize the dark page cover on dark-default sites.
- a035d19: Keep published revision URLs out of search results.
- 867da7b: Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
- 43df49c: List the operations of an OpenAPI tag page after its description.
- 506aa78: Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
- c09da2e: Show H3 headings in the page outline.
- d2be885: Render a page's search keywords in its metadata.
- 6cdbafc: Respect disabled change request previews on published sites.
- 19660ed: Fix the search button accessible name, hoverable link previews, IME-safe Enter on Safari, cookie banner semantics, active outline item announcement and textarea shrinking.
- d2c56e5: 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.
- 65210b7: Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
- 3e86382: Send only the site origin as referrer to third parties, and only let the embedding page open the embed messaging channel.
- 7d1cd9f: Remove the ChatGPT-specific plain text response for Markdown and llms.txt routes; these now always serve `text/markdown`.
- e237a74: Remove the MCP server link from the screen-reader-only agent directive in page HTML.
- 3ec61a7: Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
- 63a4a98: Track the displayed position and search request ID when a visitor opens a search result.
- cf8c3d5: Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
- 48fe81b: Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
- adbec4c: Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
- 8f5175e: Show loading rows shaped like search results while search waits for the server.
- 386a5c1: Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
- b145bfc: Stop caching site search results in the framework cache, so every search reaches the API.
- 7856e08: Show one server-ordered search list and open its top result on Enter.
- a10eff9: Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
- 1c71849: Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
- 7f08fb1: Show site revision previews as their site revision pins them, including OpenAPI specs.
- b5f7e55: Render small cards in a responsive four-column grid and carousel.
- 8dd308b: Ignore tag category references when displaying assigned tags and update filters.
- 4cbbda7: Update the GitBook API SDK for site revision responses.
- 060f1f6: Fix wide content in Updates blocks overflowing into the page outline.
- 7a025d6: Fix Updates tag loading skeleton and scroll to top on pagination.
- 22f3778: Paginate published Updates pages with more than 50 entries into 20-entry pages.
- Updated dependencies [a9535cd]
- Updated dependencies [36cde87]
- Updated dependencies [6b2e806]
- Updated dependencies [9fcde5f]
- Updated dependencies [265ca4b]
- Updated dependencies [262749a]
- Updated dependencies [b1cfef2]
- Updated dependencies [65210b7]
- @gitbook/embed@0.8.0
- @gitbook/icons@0.6.0
- @gitbook/react-openapi@2.0.2
- @gitbook/react-contentkit@0.7.19
## 0.28.2
### Patch Changes
+36 -1
View File
@@ -15,7 +15,7 @@ import {
GitBookAPI,
SiteSocialAccountPlatform,
} from '@gitbook/api';
import type { GitBookStandalone } from '@gitbook/embed';
import type { GitBookNavigateEvent, GitBookStandalone } from '@gitbook/embed';
import { getContentTestURL, getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
import {
@@ -3560,6 +3560,41 @@ const testCases: TestsCase[] = [
);
},
},
{
name: 'API - navigate event',
url: '',
screenshot: false,
run: async (page) => {
await page.evaluate(() => {
const GitBook = window.GitBook as unknown as GitBookStandalone;
const host = window as unknown as {
navigateEvents: GitBookNavigateEvent[];
};
host.navigateEvents = [];
GitBook('on', 'navigate', (event) => host.navigateEvents.push(event));
GitBook('navigateToPage', '/text-page');
});
const navigateEvents = () =>
page.evaluate(
() =>
(window as unknown as { navigateEvents: GitBookNavigateEvent[] })
.navigateEvents
);
await expect.poll(navigateEvents, { timeout: 20000 }).toContainEqual({
tab: 'docs',
path: '/text-page',
url: expect.stringMatching(/^[^?#]+\/text-page$/),
title: 'Text page',
});
const iframe = page.frameLocator('#gitbook-widget-iframe');
await iframe.getByTestId('embed-tab-assistant').click();
await expect
.poll(navigateEvents, { timeout: 20000 })
.toContainEqual({ tab: 'assistant' });
},
},
{
name: 'API - postUserMessage',
url: '',
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "0.28.2",
"version": "0.29.0",
"private": true,
"dependencies": {
"@base-ui/react": "catalog:",
@@ -1,4 +1,5 @@
import { EmbeddableAIChat } from './EmbeddableAIChat';
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
type EmbeddableAssistantPageProps = {
baseURL: string;
@@ -9,5 +10,10 @@ type EmbeddableAssistantPageProps = {
* Reusable page component for the embed assistant page.
*/
export async function EmbeddableAssistantPage(props: EmbeddableAssistantPageProps) {
return <EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />;
return (
<>
<EmbeddableNavigateEvent tab="assistant" />
<EmbeddableAIChat baseURL={props.baseURL} siteTitle={props.siteTitle} />
</>
);
}
@@ -25,7 +25,9 @@ import {
EmbeddableIframeButtons,
EmbeddableIframeCloseButton,
EmbeddableIframeTabs,
EmbeddableNavigateEvent,
} from './EmbeddableIframeAPI';
import { getEmbeddableDocsNavigateEvent, getEmbeddablePagePublishedPath } from './navigate-event';
import { type PagePathParams, getSitePageData } from '@/components/SitePage';
import type { GitBookSiteContext } from '@/lib/context';
@@ -81,9 +83,11 @@ export async function EmbeddableDocsPage(
}
const variants = categorizeVariants(context);
const pageInput = { linker: context.linker, pages: context.revision.pages, page };
return (
<EmbeddableFrame className="site-background">
<EmbeddableNavigateEvent {...getEmbeddableDocsNavigateEvent(pageInput)} />
<EmbeddableFrameSidebar>
<EmbeddableIframeTabs
active="docs"
@@ -105,12 +109,7 @@ export async function EmbeddableDocsPage(
</EmbeddableFrameHeaderMain>
<EmbeddableFrameButtons>
<EmbeddableDocsPageControlButtons
href={context.linker
.toPathForPage({
pages: context.revision.pages,
page,
})
.replace(/~gitbook\/embed\/page\/?/, '')}
href={getEmbeddablePagePublishedPath(pageInput)}
/>
</EmbeddableFrameButtons>
</EmbeddableFrameHeader>
@@ -8,6 +8,7 @@ import type { GitBookIntegrationTool } from '@gitbook/browser-types';
import type {
FrameToParentMessage,
GitBookEmbeddableConfiguration,
GitBookNavigateEvent,
ParentToFrameMessage,
} from '@gitbook/embed';
@@ -181,6 +182,22 @@ export function EmbeddableIframeAPI(props: { baseURL: string }) {
return null;
}
/**
* Tell the parent window where the reader is, each time it changes.
*/
export function EmbeddableNavigateEvent(props: GitBookNavigateEvent) {
// Compared by value: a server re-render passes a new object for the same page.
const event = JSON.stringify(props);
useEffect(() => {
getChannel()?.send({
type: 'navigate',
...(JSON.parse(event) as GitBookNavigateEvent),
} satisfies FrameToParentMessage);
}, [event]);
return null;
}
/**
* Hook to get the configuration from the parent window.
*/
@@ -1,3 +1,4 @@
import { EmbeddableNavigateEvent } from './EmbeddableIframeAPI';
import { EmbeddableSearch } from './EmbeddableSearch';
import { getSearchBaseProps } from '@/components/Search/search-props';
import type { GitBookSiteContext } from '@/lib/context';
@@ -13,10 +14,13 @@ export function EmbeddableSearchPage(props: EmbeddableSearchPageProps) {
const { context } = props;
return (
<EmbeddableSearch
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
siteTitle={context.site.title}
searchProps={getSearchBaseProps(context)}
/>
<>
<EmbeddableNavigateEvent tab="search" />
<EmbeddableSearch
baseURL={context.linker.toPathInSite('~gitbook/embed/')}
siteTitle={context.site.title}
searchProps={getSearchBaseProps(context)}
/>
</>
);
}
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'bun:test';
import type { RevisionPageDocument } from '@gitbook/api';
import { getEmbeddableDocsNavigateEvent } from './navigate-event';
import { getEmbeddableLinker } from '@/lib/embeddable-linker';
import { type GitBookLinker, createLinker } from '@/lib/links';
const pages = [
{ id: 'home', type: 'document', title: 'Home', path: 'home', pages: [] },
{ id: 'slack', type: 'document', title: 'Slack', path: 'integrations/slack', pages: [] },
] as unknown as RevisionPageDocument[];
const [home, slack] = pages as [RevisionPageDocument, RevisionPageDocument];
function embedLinker(servedOn: Parameters<typeof createLinker>[0]): GitBookLinker {
return getEmbeddableLinker(createLinker(servedOn));
}
describe('getEmbeddableDocsNavigateEvent', () => {
it('describes the page by its path from the site root and its published URL', () => {
const linker = embedLinker({
host: 'example.com',
siteBasePath: '/docs/',
spaceBasePath: '/docs/help-center/',
});
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: slack })).toEqual({
tab: 'docs',
path: '/help-center/integrations/slack',
url: 'https://example.com/docs/help-center/integrations/slack',
title: 'Slack',
});
});
it('describes the first page of a space by the space root', () => {
const linker = embedLinker({
host: 'example.com',
siteBasePath: '/docs/',
spaceBasePath: '/docs/help-center/',
});
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
path: '/help-center',
url: 'https://example.com/docs/help-center',
});
});
it('describes the home page of a single-space site as the root', () => {
const linker = embedLinker({ host: 'example.com', siteBasePath: '/', spaceBasePath: '/' });
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
path: '/',
url: 'https://example.com/',
});
});
it('describes the home page of a site on a subdirectory as the root', () => {
const linker = embedLinker({
host: 'example.com',
siteBasePath: '/docs/',
spaceBasePath: '/docs/',
});
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: home })).toMatchObject({
path: '/',
url: 'https://example.com/docs',
});
});
it('leaves out query parameters and anchors', () => {
const base = embedLinker({ host: 'example.com', siteBasePath: '/', spaceBasePath: '/' });
const linker: GitBookLinker = {
...base,
toPathForPage: () => '/~gitbook/embed/page/integrations/slack?jwt_token=secret#setup',
};
expect(getEmbeddableDocsNavigateEvent({ linker, pages, page: slack })).toMatchObject({
path: '/integrations/slack',
url: 'https://example.com/integrations/slack',
});
});
});
@@ -0,0 +1,45 @@
import type { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import type { GitBookNavigateEvent } from '@gitbook/embed';
import type { GitBookLinker } from '@/lib/links';
import { withLeadingSlash } from '@/lib/paths';
type PageInput = {
/** The embed's linker. */
linker: GitBookLinker;
pages: RevisionPage[];
page: RevisionPageDocument | RevisionPageGroup;
};
/**
* Path of a page on the published site, outside the embed.
*/
export function getEmbeddablePagePublishedPath({ linker, pages, page }: PageInput): string {
return linker.toPathForPage({ pages, page }).replace(/~gitbook\/embed\/page\/?/, '');
}
function trimTrailingSlash(pathname: string): string {
return pathname.replace(/(.)\/$/, '$1');
}
/**
* Describe a docs page for the `navigate` event sent to the host of the embed.
*/
export function getEmbeddableDocsNavigateEvent(
input: PageInput
): Extract<GitBookNavigateEvent, { tab: 'docs' }> {
const { linker, page } = input;
// Query parameters can carry the visitor's token; the host only gets the page.
const { pathname } = new URL(getEmbeddablePagePublishedPath(input), 'https://gitbook.local');
// Relative before trimming: the site base path ends with a slash, so `/docs` wouldn't match it.
const path = trimTrailingSlash(withLeadingSlash(linker.toRelativePathInSite(pathname)));
const url = linker.toAbsoluteURL(trimTrailingSlash(pathname));
return {
tab: 'docs',
path,
// Joining paths drops the slash of a root URL (`https://example.com`).
url: URL.canParse(url) ? new URL(url).href : url,
title: page.title,
};
}
@@ -39,10 +39,11 @@ import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import {
countDocumentUpdates,
generateUpdatesFilterCSS,
getUpdatesPageRange,
getUpdatesPaginationEligibility,
paginateUpdatesDocument,
UPDATES_PAGINATION_THRESHOLD,
getDocumentFilterableTags,
updatesFilterStyleHref,
} from '@/lib/updates';
@@ -248,12 +249,9 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
if (props.updatesPage) {
const document = await getPageDocument(context, page);
if (document) {
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status === 'eligible') {
const { page: pageNumber } = getUpdatesPageRange(
props.updatesPage,
eligibility.updates.length
);
const count = countDocumentUpdates(document);
if (count > UPDATES_PAGINATION_THRESHOLD) {
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
title = `${title} (Page ${pageNumber})`;
if (!pageMetaLinks?.canonical) {
const url = new URL(canonical);
@@ -380,29 +378,17 @@ export async function getSitePageData(props: SitePageProps) {
let filterableTags: RevisionTag[] = [];
let document = fullDocument;
let pagination = null;
let eligibility = null;
if (fullDocument) {
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
({ document, pagination, eligibility } = paginateUpdatesDocument(
fullDocument,
context.revision,
{
page: props.updatesPage ?? 1,
}
));
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
page: props.updatesPage ?? 1,
}));
}
if (eligibility?.status === 'skipped' || pagination || props.updatesPage) {
if (pagination || props.updatesPage) {
const logger = getLogger().subLogger('updatesPagination', {
labels: { siteId: context.site.id, pageId: page.id },
});
if (eligibility?.status === 'skipped') {
logger.info('Skipped updates pagination', {
reason: eligibility.reason,
totalUpdates: eligibility.totalUpdates,
updatesBlocks: eligibility.updatesBlocks,
});
}
if (props.updatesPage && (!pagination || pagination.isClamped)) {
const targetPage = pagination?.page ?? 1;
logger.info('Redirected out-of-range updates page', {
+81 -162
View File
@@ -1,10 +1,6 @@
import { describe, expect, it } from 'bun:test';
import {
type DocumentBlockHeading,
type DocumentBlockParagraph,
type DocumentBlockUpdate,
type DocumentBlockUpdates,
DocumentTextColor,
type JSONDocument,
type Revision,
@@ -14,9 +10,8 @@ import {
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
import {
UPDATES_TAG_FILTER_CAP,
type UpdatesPaginationEligibility,
countDocumentUpdates,
findUpdateAnchorPage,
getUpdatesPaginationEligibility,
paginateUpdatesDocument,
parseUpdatesPageParam,
getDocumentFilterableTags,
@@ -102,119 +97,63 @@ describe('normalizeUpdatesFilterTags', () => {
});
describe('updates pagination', () => {
it('paginates a single top-level updates block and keeps the surrounding blocks', () => {
const document = createDocument([
createHeading('intro'),
createParagraph(),
createUpdatesBlock(createUpdateEntries(260)),
createParagraph(),
]);
it('keeps a 50-entry document intact and paginates 51 entries across two blocks', () => {
const short = createUpdatesDocument(Array.from({ length: 50 }, () => []));
expect(paginateUpdatesDocument(short, undefined, { page: 2 })).toEqual({
document: short,
pagination: null,
});
expect(paginateUpdatesDocument(short, undefined, { page: 2 }).document).toBe(short);
const long = createUpdatesDocument(
Array.from({ length: 51 }, () => []),
25
);
expect(countDocumentUpdates(long)).toBe(51);
for (const [page, start, end, blockTypes] of [
[1, 1, 20, ['updates', 'paragraph']],
[2, 21, 40, ['updates', 'paragraph', 'updates']],
[3, 41, 51, ['paragraph', 'updates']],
] as const) {
const result = paginateUpdatesDocument(long, undefined, { page });
expect(result.pagination).toEqual({
page,
totalPages: 3,
totalItems: 51,
pageSize: 20,
start,
end,
isClamped: false,
});
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: end - start + 1 }, (_, i) => `update-${start + i}`)
);
expect(result.document.nodes.map((block) => block.type)).toEqual([...blockTypes]);
}
});
it('keeps the first and seventh slices of a 260-entry changelog to 20 entries each', () => {
const document = createUpdatesDocument(
Array.from({ length: 260 }, () => []),
135
);
for (const [page, start] of [
[1, 1],
[7, 121],
] as const) {
const result = paginateUpdatesDocument(document, undefined, { page });
expect(result.pagination).toEqual({
expect(result.pagination).toMatchObject({
page,
totalPages: 13,
totalItems: 260,
pageSize: 20,
start,
end: start + 19,
isClamped: false,
});
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: 20 }, (_, i) => `update-${start + i}`)
);
expect(result.document.nodes.map((block) => block.type)).toEqual([
'heading-1',
'paragraph',
'updates',
'paragraph',
]);
}
});
it('keeps 50 entries intact and paginates 51', () => {
const short = createDocument([createUpdatesBlock(createUpdateEntries(50))]);
expect(getUpdatesPaginationEligibility(short)).toEqual({ status: 'below-threshold' });
const shortResult = paginateUpdatesDocument(short, undefined, { page: 2 });
expect(shortResult.pagination).toBeNull();
expect(shortResult.document).toBe(short);
const long = createDocument([createUpdatesBlock(createUpdateEntries(51))]);
const eligibility = getUpdatesPaginationEligibility(long);
expect(eligibility.status).toBe('eligible');
if (eligibility.status === 'eligible') {
expect(eligibility.updates).toHaveLength(51);
}
const result = paginateUpdatesDocument(long, undefined, { page: 3 });
expect(result.pagination).toMatchObject({ page: 3, totalPages: 3, start: 41, end: 51 });
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: 11 }, (_, i) => `update-${41 + i}`)
);
});
it.each([
[25, 26],
[60, 10],
])('does not paginate two top-level updates blocks of %i and %i entries', (first, second) => {
const entries = createUpdateEntries(first + second);
const document = createDocument([
createUpdatesBlock(entries.slice(0, first)),
createParagraph(),
createUpdatesBlock(entries.slice(first)),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'multiple-updates-blocks',
totalUpdates: first + second,
updatesBlocks: 2,
});
});
it('does not paginate when another updates block is nested inside a container', () => {
const entries = createUpdateEntries(62);
const document = createDocument([
createUpdatesBlock(entries.slice(0, 60)),
wrapInIf(createUpdatesBlock(entries.slice(60))),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'nested-updates-block',
totalUpdates: 62,
updatesBlocks: 2,
});
});
it('does not paginate an updates block that is only nested', () => {
const document = createDocument([wrapInIf(createUpdatesBlock(createUpdateEntries(60)))]);
expectNotPaginated(document, { status: 'below-threshold' });
});
it('does not paginate an updates block with non-update entries', () => {
const entries = createUpdateEntries(60);
const document = createDocument([
createUpdatesBlock([
...entries.slice(0, 30),
{
object: 'block',
type: 'if',
data: { expression: 'visitor.claims.beta' },
isVoid: false,
nodes: entries.slice(30, 32),
},
...entries.slice(32),
]),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'non-update-entries',
totalUpdates: 59,
updatesBlocks: 1,
});
});
it('filters by any selected tag before calculating page bounds and clamps to the last match', () => {
const revision = {
tags: [createTag('odd', 'Odd'), createTag('even', 'Even')],
@@ -228,7 +167,8 @@ describe('updates pagination', () => {
return ['even'];
}
return [];
})
}),
30
);
const result = paginateUpdatesDocument(document, revision, {
@@ -244,6 +184,7 @@ describe('updates pagination', () => {
isClamped: true,
});
expect(getUpdateIds(result.document)).toEqual(['update-61']);
expect(countDocumentUpdates(document)).toBe(61);
});
it('finds a nested anchor on the filtered page or clears a filter that excludes it', () => {
@@ -254,7 +195,8 @@ describe('updates pagination', () => {
return ['fixes'];
}
return [];
})
}),
26
);
expect(
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
@@ -321,68 +263,45 @@ function getUpdateIds(document: JSONDocument) {
});
}
function expectNotPaginated(document: JSONDocument, eligibility: UpdatesPaginationEligibility) {
expect(getUpdatesPaginationEligibility(document)).toEqual(eligibility);
const result = paginateUpdatesDocument(document, undefined, { page: 2 });
expect(result).toEqual({
document,
pagination: null,
eligibility,
});
expect(result.document).toBe(document);
expect(findUpdateAnchorPage(document, undefined, { anchor: 'update-1' })).toEqual({
found: false,
});
}
function createUpdatesDocument(entryTags: string[][]): JSONDocument {
return createDocument([createUpdatesBlock(createUpdateEntries(entryTags.length, entryTags))]);
}
function createDocument(nodes: JSONDocument['nodes']): JSONDocument {
return { object: 'document', data: { schemaVersion: 2 }, nodes };
}
function createUpdateEntries(count: number, entryTags: string[][] = []): DocumentBlockUpdate[] {
return Array.from({ length: count }, (_, index) => ({
object: 'block',
type: 'update',
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
const entries = entryTags.map((tags, index) => ({
object: 'block' as const,
type: 'update' as const,
data: {
date: '2026-05-01',
tags: (entryTags[index] ?? []).map((tag) => ({ kind: 'tag', tag })),
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
},
isVoid: false,
nodes: [createHeading(`update-${index + 1}`)],
isVoid: false as const,
nodes: [
{
object: 'block' as const,
type: 'heading-1' as const,
meta: { id: `update-${index + 1}` },
data: {},
isVoid: false as const,
nodes: [],
},
],
}));
}
const updates = (nodes: typeof entries) => ({
object: 'block' as const,
type: 'updates' as const,
data: { format: 'full' as const },
isVoid: false as const,
nodes,
});
const nodes: JSONDocument['nodes'] = [updates(entries)];
if (splitAt !== undefined) {
nodes.splice(
0,
1,
updates(entries.slice(0, splitAt)),
{ object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] },
updates(entries.slice(splitAt))
);
}
function createUpdatesBlock(nodes: DocumentBlockUpdates['nodes']): DocumentBlockUpdates {
return { object: 'block', type: 'updates', data: { format: 'full' }, isVoid: false, nodes };
}
function wrapInIf(block: DocumentBlockUpdates): JSONDocument['nodes'][number] {
return {
object: 'block',
type: 'if',
data: { expression: 'visitor.claims.beta' },
isVoid: false,
nodes: [block],
};
}
function createHeading(id: string): DocumentBlockHeading {
return {
object: 'block',
type: 'heading-1',
meta: { id },
data: {},
isVoid: false,
nodes: [],
};
}
function createParagraph(): DocumentBlockParagraph {
return { object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] };
return { object: 'document', data: { schemaVersion: 2 }, nodes };
}
function createTag(slug: string, label: string): RevisionTag {
+28 -95
View File
@@ -1,7 +1,6 @@
import type {
DocumentBlock,
DocumentBlockUpdate,
DocumentBlockUpdates,
DocumentInline,
JSONDocument,
Revision,
@@ -31,21 +30,6 @@ export type UpdatesPageRange = {
isClamped: boolean;
};
export type UpdatesPaginationSkipReason =
| 'multiple-updates-blocks'
| 'nested-updates-block'
| 'non-update-entries';
export type UpdatesPaginationEligibility =
| { status: 'eligible'; block: DocumentBlockUpdates; updates: DocumentBlockUpdate[] }
| { status: 'below-threshold' }
| {
status: 'skipped';
reason: UpdatesPaginationSkipReason;
totalUpdates: number;
updatesBlocks: number;
};
/** Attribute on `<html>` with the active filter's tag slugs, space-separated (e.g. `"a b"`). */
export const UPDATES_TAG_FILTER_ATTR = 'data-updates-tag-filter';
@@ -133,100 +117,38 @@ export function getDocumentFilterableTags(
return tags;
}
/**
* Pagination only slices a document with a single top-level `updates` block made of more than
* `UPDATES_PAGINATION_THRESHOLD` direct `update` entries.
*/
export function getUpdatesPaginationEligibility(
document: JSONDocument
): UpdatesPaginationEligibility {
let topLevelBlock: DocumentBlockUpdates | undefined;
let topLevelBlockCount = 0;
let totalUpdates = 0;
for (const block of document.nodes) {
if (block.type !== 'updates') {
continue;
}
topLevelBlock ??= block;
topLevelBlockCount++;
totalUpdates += block.nodes.length;
}
if (!topLevelBlock || totalUpdates <= UPDATES_PAGINATION_THRESHOLD) {
return { status: 'below-threshold' };
}
if (topLevelBlockCount > 1) {
return {
status: 'skipped',
reason: 'multiple-updates-blocks',
totalUpdates,
updatesBlocks: topLevelBlockCount,
};
}
const updates: DocumentBlockUpdate[] = [];
for (const entry of topLevelBlock.nodes) {
if (entry.type !== 'update') {
return {
status: 'skipped',
reason: 'non-update-entries',
totalUpdates,
updatesBlocks: 1,
};
}
updates.push(entry);
}
const allUpdatesBlocks = getBlocksByType(document, 'updates');
if (allUpdatesBlocks.length > 1) {
let allUpdatesCount = 0;
for (const updatesBlock of allUpdatesBlocks) {
allUpdatesCount += updatesBlock.nodes.length;
}
return {
status: 'skipped',
reason: 'nested-updates-block',
totalUpdates: allUpdatesCount,
updatesBlocks: allUpdatesBlocks.length,
};
}
return { status: 'eligible', block: topLevelBlock, updates };
export function countDocumentUpdates(document: JSONDocument): number {
return getDocumentUpdates(document).length;
}
export function paginateUpdatesDocument(
document: JSONDocument,
revision: Revision | undefined,
{ page, tags }: { page: number; tags?: string[] }
): {
document: JSONDocument;
pagination: UpdatesPageRange | null;
eligibility: UpdatesPaginationEligibility;
} {
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { document, pagination: null, eligibility };
): { document: JSONDocument; pagination: UpdatesPageRange | null } {
const updates = getDocumentUpdates(document);
if (updates.length <= UPDATES_PAGINATION_THRESHOLD) {
return { document, pagination: null };
}
const matching = filterUpdates(eligibility.updates, document, revision, tags);
const matching = filterUpdates(updates, document, revision, tags);
const pagination = getUpdatesPageRange(page, matching.length);
const entries = matching.slice(pagination.start - 1, pagination.end);
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
const nodes: JSONDocument['nodes'] = [];
for (const block of document.nodes) {
if (block !== eligibility.block) {
if (block.type !== 'updates') {
nodes.push(block);
continue;
}
const entries = block.nodes.filter((entry) => entry.type === 'update' && slice.has(entry));
if (entries.length > 0) {
nodes.push({ ...block, nodes: entries });
}
}
return { document: { ...document, nodes }, pagination, eligibility };
return { document: { ...document, nodes }, pagination };
}
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
@@ -253,12 +175,7 @@ export function findUpdateAnchorPage(
revision: Revision | undefined,
{ anchor, tags }: { anchor: string; tags?: string[] }
): { found: true; page: number; clearTags: boolean } | { found: false } {
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { found: false };
}
const { updates } = eligibility;
const updates = getDocumentUpdates(document);
const index = updates.findIndex((update) =>
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
);
@@ -292,6 +209,22 @@ function matchesUpdateAnchor(node: DocumentBlock | DocumentInline, anchor: strin
return false;
}
function getDocumentUpdates(document: JSONDocument): DocumentBlockUpdate[] {
const updates: DocumentBlockUpdate[] = [];
for (const block of document.nodes) {
if (block.type !== 'updates') {
continue;
}
for (const entry of block.nodes) {
if (entry.type === 'update') {
updates.push(entry);
}
}
}
return updates;
}
function filterUpdates(
updates: DocumentBlockUpdate[],
document: JSONDocument,
+10
View File
@@ -1,5 +1,15 @@
# @gitbook/icons
## 0.6.0
### Minor Changes
- 9fcde5f: Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
### Patch Changes
- 265ca4b: Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
## 0.5.0
### Minor Changes
+1 -1
View File
@@ -39,7 +39,7 @@
}
},
"sideEffects": false,
"version": "0.5.0",
"version": "0.6.0",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^7.2.0",
"@gitbook/fontawesome-pro": "1.0.23"
+8
View File
@@ -1,5 +1,13 @@
# @gitbook/react-contentkit
## 0.7.19
### Patch Changes
- Updated dependencies [9fcde5f]
- Updated dependencies [265ca4b]
- @gitbook/icons@0.6.0
## 0.7.18
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@gitbook/react-contentkit",
"version": "0.7.18",
"version": "0.7.19",
"type": "module",
"exports": {
".": {
+7
View File
@@ -1,5 +1,12 @@
# @gitbook/react-openapi
## 2.0.2
### Patch Changes
- 262749a: Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
- b1cfef2: Keep the selected server separate for each OpenAPI spec, so a server from a previously visited API page no longer shows or gets copied on another spec's endpoints.
## 2.0.1
### Patch Changes
+1 -1
View File
@@ -7,7 +7,7 @@
"default": "./dist/index.js"
}
},
"version": "2.0.1",
"version": "2.0.2",
"sideEffects": false,
"dependencies": {
"@base-ui/react": "catalog:",

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