mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-26 02:02:32 +00:00
Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c50ba2d5d | |||
| 84ba78bd4d | |||
| 5d60c2a7c7 | |||
| bca0b711d8 | |||
| ea375ecefc | |||
| fa7d4a94f6 | |||
| a9535cdc0e | |||
| 506aa78375 | |||
| 6b2e806e9e | |||
| 7ad3fff118 | |||
| 386a5c18eb | |||
| a3b5ce5b7e | |||
| 818cbbeb38 | |||
| 629916b96f | |||
| be6e324327 | |||
| ae1e370c48 | |||
| adbec4c832 | |||
| 8f5175e69e | |||
| 7856e08c15 | |||
| e0b512e689 | |||
| 6cdbafcda6 | |||
| d55e8f90c2 | |||
| 960d7ec6e2 | |||
| cf8c3d52f3 | |||
| 4eb32b1534 | |||
| b5f7e55818 | |||
| 262749a0b1 | |||
| b145bfcdff | |||
| 1c718491bd | |||
| 8dd308bd90 | |||
| c09da2ec1a | |||
| 9fcde5f487 | |||
| c85d84fc1d | |||
| c3df458378 | |||
| ddccd3d4f0 | |||
| adfd921b3a | |||
| 5997a66638 | |||
| 65210b7d1d | |||
| 265ca4bd9d | |||
| 3e86382cdc | |||
| 19660edf91 | |||
| e3d22380fc | |||
| 9b5b8c85ec | |||
| 0c3a51eca4 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep links in generated Markdown usable outside the source page.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Answer Assistant questions with medium reasoning instead of low, matching AI search.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix horizontal page scroll caused by card carousels bleeding past the viewport.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"@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.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"@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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Remove duplicated declarations from the global stylesheet.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gitbook/icons": minor
|
||||
---
|
||||
|
||||
Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep inline code and highlighted text readable when a paragraph crosses the bottom edge of a background page cover.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Load the OpenAPI stylesheet only on pages with OpenAPI blocks.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"gitbook": minor
|
||||
"@gitbook/react-openapi": minor
|
||||
---
|
||||
|
||||
Replace the Scalar API client behind "Test it" with a lightweight Try it panel.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gitbook/react-openapi": patch
|
||||
---
|
||||
|
||||
Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Show H3 headings in the page outline.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Respect disabled change request previews on published sites.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Send only the site origin as referrer to third parties, and only let the embedding page open the embed messaging channel.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Show loading rows shaped like search results while search waits for the server.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Stop caching site search results in the framework cache, so every search reaches the API.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Show one server-ordered search list and open its top result on Enter.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Render small cards in a responsive four-column grid and carousel.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Ignore tag category references when displaying assigned tags and update filters.
|
||||
@@ -4,6 +4,11 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
# A newer run for the same PR supersedes the previous one. Each push to main gets a group of its
|
||||
# own, so main runs are never queued behind or cancelled by another run.
|
||||
concurrency:
|
||||
group: ${{ github.event_name == 'pull_request_target' && format('preview-pr-{0}', github.event.pull_request.number) || format('preview-run-{0}', github.run_id) }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request_target' }}
|
||||
jobs:
|
||||
approval:
|
||||
# Ensure that external contributors' PRs are manually approved before deployment
|
||||
@@ -18,8 +23,9 @@ jobs:
|
||||
deploy-v2-vercel:
|
||||
name: Deploy v2 to Vercel (preview)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
needs: approval
|
||||
if: ${{ always() && (needs.approval.result == 'success' || needs.approval.result == 'skipped') }}
|
||||
if: ${{ !cancelled() && (needs.approval.result == 'success' || needs.approval.result == 'skipped') }}
|
||||
environment:
|
||||
name: 2v-preview
|
||||
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||
@@ -44,8 +50,9 @@ jobs:
|
||||
deploy-v2-cloudflare:
|
||||
name: Deploy v2 to Cloudflare Worker (preview)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
needs: approval
|
||||
if: ${{ always() && (needs.approval.result == 'success' || needs.approval.result == 'skipped') }}
|
||||
if: ${{ !cancelled() && (needs.approval.result == 'success' || needs.approval.result == 'skipped') }}
|
||||
environment:
|
||||
name: 2c-preview
|
||||
url: ${{ steps.deploy.outputs.deployment-url }}
|
||||
@@ -82,7 +89,7 @@ jobs:
|
||||
comment-deployments:
|
||||
runs-on: ubuntu-latest
|
||||
name: Comment Deployments (preview)
|
||||
if: always() && github.event_name != 'push'
|
||||
if: ${{ !cancelled() && github.event_name != 'push' }}
|
||||
needs:
|
||||
- deploy-v2-vercel
|
||||
- deploy-v2-cloudflare
|
||||
@@ -95,6 +102,25 @@ jobs:
|
||||
comment-author: 'github-actions[bot]'
|
||||
body-includes: 'Summary of the deployments'
|
||||
|
||||
# A deploy that didn't succeed has no URL (e.g. a re-run hitting Vercel's "deploymentId
|
||||
# already exists"), so keep the URL the comment already shows instead of blanking it.
|
||||
- name: Resolve deployment URLs
|
||||
id: urls
|
||||
env:
|
||||
PREVIOUS_COMMENT: ${{ steps.fc.outputs.comment-body }}
|
||||
VERCEL_RESULT: ${{ needs.deploy-v2-vercel.result }}
|
||||
VERCEL_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
|
||||
CLOUDFLARE_RESULT: ${{ needs.deploy-v2-cloudflare.result }}
|
||||
CLOUDFLARE_URL: ${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}
|
||||
run: |
|
||||
previous_url() {
|
||||
sed -n "s/^| $1 | \[\([^]]*\)\].*/\1/p" <<<"$PREVIOUS_COMMENT" | head -n 1
|
||||
}
|
||||
if [ "$VERCEL_RESULT" != success ]; then VERCEL_URL=$(previous_url Vercel); fi
|
||||
if [ "$CLOUDFLARE_RESULT" != success ]; then CLOUDFLARE_URL=$(previous_url Cloudflare); fi
|
||||
echo "vercel=$VERCEL_URL" >> "$GITHUB_OUTPUT"
|
||||
echo "cloudflare=$CLOUDFLARE_URL" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create or update GitHub comment
|
||||
uses: peter-evans/create-or-update-comment@v4
|
||||
with:
|
||||
@@ -105,21 +131,21 @@ jobs:
|
||||
|
||||
| Version | URL | Status |
|
||||
| --- | --- | --- |
|
||||
| Vercel | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}](${{ needs.deploy-v2-vercel.outputs.deployment-url }}) | ${{ needs.deploy-v2-vercel.result == 'success' && '✅' || '❌' }} |
|
||||
| Cloudflare | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}) | ${{ needs.deploy-v2-cloudflare.result == 'success' && '✅' || '❌' }} |
|
||||
| Vercel | [${{ steps.urls.outputs.vercel }}](${{ steps.urls.outputs.vercel }}) | ${{ needs.deploy-v2-vercel.result == 'success' && '✅' || '❌' }} |
|
||||
| Cloudflare | [${{ steps.urls.outputs.cloudflare }}](${{ steps.urls.outputs.cloudflare }}) | ${{ needs.deploy-v2-cloudflare.result == 'success' && '✅' || '❌' }} |
|
||||
|
||||
### Test content
|
||||
|
||||
| Site | `2v` | `2c` |
|
||||
| --- | --- | --- |
|
||||
| GitBook | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.com/docs](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.com/docs) | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.com/docs](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.com/docs) |
|
||||
| E2E | [${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open) | [${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open](${{ needs.deploy-v2-cloudflare.outputs.deployment-url }}/url/gitbook.gitbook.io/test-gitbook-open) |
|
||||
| GitBook | [${{ steps.urls.outputs.vercel }}/url/gitbook.com/docs](${{ steps.urls.outputs.vercel }}/url/gitbook.com/docs) | [${{ steps.urls.outputs.cloudflare }}/url/gitbook.com/docs](${{ steps.urls.outputs.cloudflare }}/url/gitbook.com/docs) |
|
||||
| E2E | [${{ steps.urls.outputs.vercel }}/url/gitbook.gitbook.io/test-gitbook-open](${{ steps.urls.outputs.vercel }}/url/gitbook.gitbook.io/test-gitbook-open) | [${{ steps.urls.outputs.cloudflare }}/url/gitbook.gitbook.io/test-gitbook-open](${{ steps.urls.outputs.cloudflare }}/url/gitbook.gitbook.io/test-gitbook-open) |
|
||||
edit-mode: replace
|
||||
visual-testing-v2-vercel:
|
||||
runs-on: ubuntu-latest
|
||||
name: Visual Testing v2
|
||||
needs: deploy-v2-vercel
|
||||
if: ${{ always() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -143,7 +169,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Visual Testing v2 (Cloudflare)
|
||||
needs: deploy-v2-cloudflare
|
||||
if: ${{ always() && needs.deploy-v2-cloudflare.result == 'success' }}
|
||||
if: ${{ !cancelled() && needs.deploy-v2-cloudflare.result == 'success' }}
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -167,7 +193,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Visual Testing Customers v2
|
||||
needs: deploy-v2-vercel
|
||||
if: ${{ always() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -191,7 +217,7 @@ jobs:
|
||||
# Style recalc depends on the client bundle, not the host, so this runs here only and
|
||||
# not in the Cloudflare job. Kept out of `e2e-customers`, which is a visual suite.
|
||||
- name: Run style invalidation tests
|
||||
if: always()
|
||||
if: ${{ !cancelled() }}
|
||||
working-directory: packages/gitbook
|
||||
run: bun run e2e-style-perf
|
||||
env:
|
||||
@@ -200,7 +226,7 @@ jobs:
|
||||
|
||||
# Runs on failure too: a blown style budget is exactly when the numbers are worth seeing.
|
||||
- name: Build style invalidation report
|
||||
if: always() && github.event_name != 'push'
|
||||
if: ${{ !cancelled() && github.event_name != 'push' }}
|
||||
id: style-perf
|
||||
working-directory: packages/gitbook
|
||||
run: |
|
||||
@@ -219,7 +245,7 @@ jobs:
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Find style invalidation comment
|
||||
if: always() && github.event_name != 'push' && steps.style-perf.outputs.body != ''
|
||||
if: ${{ !cancelled() && github.event_name != 'push' && steps.style-perf.outputs.body != '' }}
|
||||
uses: peter-evans/find-comment@v3
|
||||
id: fc-style-perf
|
||||
with:
|
||||
@@ -228,7 +254,7 @@ jobs:
|
||||
body-includes: 'Style invalidation on a large API reference'
|
||||
|
||||
- name: Create or update style invalidation comment
|
||||
if: always() && github.event_name != 'push' && steps.style-perf.outputs.body != ''
|
||||
if: ${{ !cancelled() && github.event_name != 'push' && steps.style-perf.outputs.body != '' }}
|
||||
uses: peter-evans/create-or-update-comment@v4
|
||||
with:
|
||||
comment-id: ${{ steps.fc-style-perf.outputs.comment-id }}
|
||||
@@ -239,7 +265,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Visual Testing Customers v2 (Cloudflare)
|
||||
needs: deploy-v2-cloudflare
|
||||
if: ${{ always() && needs.deploy-v2-cloudflare.result == 'success' }}
|
||||
if: ${{ !cancelled() && needs.deploy-v2-cloudflare.result == 'success' }}
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -263,7 +289,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Browserless Testing v2 (Vercel)
|
||||
needs: deploy-v2-vercel
|
||||
if: ${{ always() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -51,3 +51,31 @@ jobs:
|
||||
- name: Outputs
|
||||
run: |
|
||||
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||
linear-release:
|
||||
name: Track the production release in Linear
|
||||
needs: [deploy-v2-vercel, deploy-v2-cloudflare]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
# Release tracking must never fail a deployment that already succeeded.
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
LINEAR_ACCESS_KEY: ${{ secrets.PRODUCTION_LINEAR_RELEASE_ACCESS_KEY }}
|
||||
steps:
|
||||
- name: Skip release tracking without an access key
|
||||
if: env.LINEAR_ACCESS_KEY == ''
|
||||
run: echo "::warning::No Linear pipeline access key is configured, skipped tracking the release."
|
||||
- name: Checkout
|
||||
if: env.LINEAR_ACCESS_KEY != ''
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# The Linear CLI scans commit metadata since the last release, so it needs history but no blobs.
|
||||
fetch-depth: 0
|
||||
filter: blob:none
|
||||
persist-credentials: false
|
||||
- name: Sync the release to Linear
|
||||
if: env.LINEAR_ACCESS_KEY != ''
|
||||
uses: linear/linear-release-action@dd4fc407f860b9460d2cf0b3fb1edd8985cf443f # v0.18.2
|
||||
with:
|
||||
access_key: ${{ env.LINEAR_ACCESS_KEY }}
|
||||
|
||||
@@ -59,6 +59,36 @@ Run a specific test file:
|
||||
cd packages/gitbook && bun test src/lib/cache.test.ts
|
||||
```
|
||||
|
||||
## Changes customers see on their live site
|
||||
|
||||
Published sites are our customers' product. If a change alters how their content looks or behaves without them changing anything, it needs a comms decision before it merges.
|
||||
|
||||
It counts if it ships on by default and any of these are true:
|
||||
- It changes structure or navigation: outline/"On this page", sidebar, TOC, headings, breadcrumbs, pagination, header or footer.
|
||||
- Something new appears on every page (or every page of a type), or something existing disappears or moves.
|
||||
- Layout or typography shifts enough that a customer would notice in a screenshot.
|
||||
- URLs, anchors, redirects, SEO/meta tags or search/Ask behaviour change.
|
||||
- A default changes for existing sites.
|
||||
|
||||
It does not count when:
|
||||
- It's behind a flag, a site setting or opt-in that stays off for existing sites until comms go out.
|
||||
- It's a bug fix that restores the intended behaviour.
|
||||
- It only affects the editor/app, not published content.
|
||||
|
||||
When it counts:
|
||||
1. Warn the engineer before the PR is opened: "This changes customers' live sites. Have the support and sales leads agreed the rollout and announcement?"
|
||||
2. Suggest a flag or staged rollout if there isn't one, so it can ship dark and be turned on after the notice goes out.
|
||||
|
||||
## Bumping Next.js or OpenNext
|
||||
|
||||
Type checks and unit tests miss runtime regressions: OpenNext 4.1.15 changed the composable cache key format, and every `'use cache'` call silently missed for days. Before committing a bump of `next`, `@opennextjs/aws` or `@opennextjs/cloudflare`, run both runtimes locally from `packages/gitbook`:
|
||||
|
||||
1. **Next**: `bun run build:local && bun run start`, then load several distinct pages under `http://localhost:3000/url/gitbook.com/docs`.
|
||||
2. **OpenNext**: `bun run build:cloudflare`, delete `openNext/customWorkers/.wrangler` (stale cache hits otherwise skip the server), then run `bun run dev:cf:server` and `bun run dev:cf:middleware` and load several distinct pages under `http://127.0.0.1:8771/url/gitbook.com/docs`.
|
||||
3. Diff the changed OpenNext versions' adapters that call our overrides in `openNext/` (incremental, composable and tag cache, queue), e.g. with `npm pack` of the old and new versions.
|
||||
|
||||
The bump is safe when every page returns 200 on both runtimes and the server logs show no cache errors (grep `Failed to` and `regional cache`). Report the pages checked and the log result in the PR.
|
||||
|
||||
## Changesets
|
||||
|
||||
After committing code changes, create a changeset for the affected package:
|
||||
|
||||
+2
-3
@@ -48,8 +48,7 @@
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.208.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",
|
||||
@@ -68,7 +67,7 @@
|
||||
"decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch",
|
||||
"@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch",
|
||||
"mermaid@11.16.1": "patches/mermaid@11.16.1.patch",
|
||||
"next@16.4.5": "patches/next@16.4.5.patch",
|
||||
"next@16.4.6": "patches/next@16.4.6.patch",
|
||||
"@shikijs/langs@3.21.0": "patches/@shikijs%2Flangs@3.21.0.patch"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,11 @@ frame.configure({
|
||||
frame.on('close', () => {
|
||||
console.log('Frame closed');
|
||||
});
|
||||
|
||||
// Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it
|
||||
frame.on('escape', () => {
|
||||
closeHelpPanel();
|
||||
});
|
||||
```
|
||||
|
||||
## As React components
|
||||
@@ -222,7 +227,7 @@ function MyComponent() {
|
||||
- `frame.postUserMessage(message: string)` → `void`
|
||||
- `frame.clearChat()` → `void`
|
||||
- `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void`
|
||||
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe)
|
||||
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). Events: `close`, `escape`
|
||||
|
||||
### React Components
|
||||
|
||||
@@ -394,6 +399,8 @@ Available in: Standalone script, NPM package, React components
|
||||
|
||||
Suggested questions displayed in the [Assistant](https://gitbook.com/docs/publishing-documentation/gitbook-ai-assistant) welcome screen.
|
||||
|
||||
Omit `suggestions` when creating the embed or pass an empty array to use the site's suggested questions. If the site has no suggested questions, the Assistant shows generic questions. Later `configure` calls keep the current setting unless you pass `suggestions`. To restore the site's questions, remove the React prop or pass `{ suggestions: [] }` or `{ suggestions: undefined }` to `configure`.
|
||||
|
||||
- **Type**: `string[]`
|
||||
|
||||
```javascript
|
||||
|
||||
@@ -38,7 +38,10 @@ export type GitBookFrameClient = {
|
||||
configure: (settings: Partial<GitBookEmbeddableConfiguration>) => void;
|
||||
|
||||
/**
|
||||
* Register an event listener.
|
||||
* Register an event listener and get back a function that removes it.
|
||||
*
|
||||
* - `close`: the built-in close button was clicked.
|
||||
* - `escape`: Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it.
|
||||
*/
|
||||
on: (event: string, listener: (...args: any[]) => void) => () => void;
|
||||
};
|
||||
@@ -64,11 +67,9 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
|
||||
channel.receive((message: FrameToParentMessage) => {
|
||||
console.log('[gitbook:embed] received message', message);
|
||||
if (message.type === 'close') {
|
||||
const listeners = events.get('close') || [];
|
||||
if (listeners) {
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
if (message.type === 'close' || message.type === 'escape') {
|
||||
const listeners = events.get(message.type) || [];
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
});
|
||||
|
||||
@@ -83,7 +84,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
tabs: ['assistant', 'search', 'docs'],
|
||||
actions: [],
|
||||
greeting: { title: '', subtitle: '' },
|
||||
suggestions: [],
|
||||
suggestions: undefined,
|
||||
tools: [],
|
||||
trademark: true,
|
||||
};
|
||||
@@ -108,7 +109,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
|
||||
return () => {
|
||||
events.set(
|
||||
event,
|
||||
listeners.filter((l) => l !== listener)
|
||||
(events.get(event) || []).filter((l) => l !== listener)
|
||||
);
|
||||
};
|
||||
},
|
||||
|
||||
@@ -94,8 +94,8 @@ export type GitBookEmbeddableConfiguration = {
|
||||
*/
|
||||
assistantName?: string;
|
||||
|
||||
/** Suggestions of questions to be displayed in the welcome page. */
|
||||
suggestions: string[];
|
||||
/** Welcome questions. Omit or pass [] to inherit the site's questions. */
|
||||
suggestions?: string[] | undefined;
|
||||
|
||||
/** Tools to be provided to the assistant. */
|
||||
tools: GitBookToolDefinition[];
|
||||
@@ -137,6 +137,11 @@ export type ParentToFrameMessage =
|
||||
/**
|
||||
* Messages sent from the frame to the parent.
|
||||
*/
|
||||
export type FrameToParentMessage = {
|
||||
type: 'close';
|
||||
};
|
||||
export type FrameToParentMessage =
|
||||
| {
|
||||
type: 'close';
|
||||
}
|
||||
| {
|
||||
/** Escape was pressed inside the frame and nothing in the frame handled it. */
|
||||
type: 'escape';
|
||||
};
|
||||
|
||||
@@ -24,7 +24,7 @@ export function GitBookFrame(props: GitBookFrameProps) {
|
||||
visitor,
|
||||
actions = [],
|
||||
greeting,
|
||||
suggestions = [],
|
||||
suggestions,
|
||||
tools = [],
|
||||
tabs = ['assistant', 'search', 'docs'],
|
||||
defaultTab,
|
||||
|
||||
@@ -63,7 +63,6 @@ let frameConfiguration: GitBookEmbeddableConfiguration & StandaloneConfiguration
|
||||
},
|
||||
actions: [],
|
||||
greeting: { title: '', subtitle: '' },
|
||||
suggestions: [],
|
||||
tools: [],
|
||||
tabs: ['assistant', 'search', 'docs'],
|
||||
trademark: true,
|
||||
|
||||
@@ -158,6 +158,8 @@
|
||||
z-index: 9998;
|
||||
width: calc(min(var(--gitbook-widget-window-width), calc(100vw - var(--gitbook-widget-right) - var(--gitbook-widget-left))));
|
||||
height: calc(min(var(--gitbook-widget-window-height), calc(100vh - var(--gitbook-widget-window-bottom) - var(--gitbook-widget-top))));
|
||||
/* stylelint-disable-next-line plugin/no-unsupported-browser-features -- the `vh` declaration above is the fallback on host pages whose browser lacks `dvh` */
|
||||
height: calc(min(var(--gitbook-widget-window-height), calc(100dvh - var(--gitbook-widget-window-bottom) - var(--gitbook-widget-top))));
|
||||
background-color: var(--gitbook-widget-background-translucent);
|
||||
backdrop-filter: blur(48px);
|
||||
border: 1px solid var(--gitbook-widget-border-color);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Page, expect } from '@playwright/test';
|
||||
import { type Page, type Request, type Route, expect, test } from '@playwright/test';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import {
|
||||
@@ -12,11 +12,12 @@ import {
|
||||
CustomizationIconsStyle,
|
||||
CustomizationPageActionType,
|
||||
CustomizationSidebarListStyle,
|
||||
GitBookAPI,
|
||||
SiteSocialAccountPlatform,
|
||||
} from '@gitbook/api';
|
||||
import type { GitBookStandalone } from '@gitbook/embed';
|
||||
|
||||
import { getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
|
||||
import { getContentTestURL, getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
|
||||
import {
|
||||
type Test,
|
||||
type TestsCase,
|
||||
@@ -41,16 +42,15 @@ import {
|
||||
import { VISITOR_TOKEN_COOKIE } from '@/lib/visitors';
|
||||
|
||||
// Kept as deterministic as possible to reduce visual flakiness: no preamble, a
|
||||
// single fixed search, a concise answer, and a fixed number of follow-ups. The
|
||||
// model is never perfectly deterministic, so `overrideAIResponse` still
|
||||
// normalizes the rendered content below — this prompt just narrows the variance.
|
||||
// single fixed search, and a concise answer. The model is never perfectly
|
||||
// deterministic, so `overrideAIResponse` still normalizes the rendered content
|
||||
// below — this prompt just narrows the variance.
|
||||
const AI_PROMPT = [
|
||||
"You're being invoked by the GitBook CI/CD pipeline for automated visual testing.",
|
||||
'Follow these instructions exactly and do not deviate:',
|
||||
'1. Do not write any preamble, commentary, or reasoning before acting.',
|
||||
'2. Perform a single search for exactly "Lorem ipsum".',
|
||||
'3. Reply with only the first sentence of the first page you find, and nothing else.',
|
||||
'4. Always end by proposing exactly 3 follow-up suggestions.',
|
||||
].join('\n');
|
||||
|
||||
// `InsightsProvider` debounces its flushes by 1.5s.
|
||||
@@ -74,6 +74,62 @@ function trackInsightsEvents(page: Page, type: string) {
|
||||
return collected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold the page's search requests until the test answers them, and find a held one by query.
|
||||
*/
|
||||
async function holdSearchRequests(page: Page) {
|
||||
// Without a pass every search goes through the route, whether or not the site's flag gives one.
|
||||
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
|
||||
const held: Route[] = [];
|
||||
await page.route('**/~gitbook/search', (route) => {
|
||||
held.push(route);
|
||||
});
|
||||
|
||||
return async (query: string) => {
|
||||
await expect
|
||||
.poll(() => held.some((route) => route.request().postDataJSON().query === query))
|
||||
.toBe(true);
|
||||
const index = held.findIndex((route) => route.request().postDataJSON().query === query);
|
||||
const [route] = held.splice(index, 1);
|
||||
if (!route) {
|
||||
throw new Error(`No held search for "${query}"`);
|
||||
}
|
||||
return route;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer a held search request with the server's own answer, and return its top result.
|
||||
*/
|
||||
async function answerSearch(route: Route) {
|
||||
const response = await route.fetch();
|
||||
const [topResult]: { title: string; href: string }[] = await response.json();
|
||||
await route.fulfill({ response });
|
||||
if (!topResult) {
|
||||
throw new Error('The search answer has no results');
|
||||
}
|
||||
return topResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a page result for a search answer given by the test.
|
||||
*/
|
||||
function searchPageResult(route: Route, siteSpaceId: string, title: string, path: string) {
|
||||
const sitePath = new URL(route.request().url()).pathname.replace('~gitbook/search', '');
|
||||
return {
|
||||
type: 'page',
|
||||
id: `space/${title}`,
|
||||
pageId: title,
|
||||
spaceId: 'space',
|
||||
siteSpaceId,
|
||||
title,
|
||||
description: '',
|
||||
href: `${sitePath}${path}`,
|
||||
score: 1,
|
||||
rank: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const overrideAIInitialState = () => {
|
||||
const greeting = document.querySelector('[data-testid="ai-chat-greeting-title"]');
|
||||
if (greeting) {
|
||||
@@ -158,6 +214,29 @@ const searchTestCases: Test[] = [
|
||||
await expect(page.getByTestId('search-input')).toBeFocused();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Loading rows cannot be activated',
|
||||
url: getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
}),
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForCookiesDialog(page);
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
await heldSearch('gitbook');
|
||||
|
||||
const searchPopup = page.getByTestId('search-popover');
|
||||
await expect(searchPopup.locator('[aria-busy="true"]').first()).toBeVisible();
|
||||
await expect(searchPopup.getByTestId('search-page-result')).toHaveCount(0);
|
||||
await expect(searchPopup.getByRole('link')).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Keyboard focus exits to the next page control',
|
||||
url: getCustomizationURL({
|
||||
@@ -209,6 +288,48 @@ const searchTestCases: Test[] = [
|
||||
await expect(searchInput).toHaveValue('getting started');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Retry after a failed search sends the query once',
|
||||
url: getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.None,
|
||||
},
|
||||
}),
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForCookiesDialog(page);
|
||||
// Keep the search on the failing route whether or not the site gives search passes.
|
||||
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
|
||||
let failing = true;
|
||||
await page.route('**/~gitbook/search', (route) =>
|
||||
failing ? route.fulfill({ status: 500 }) : route.continue()
|
||||
);
|
||||
const sentQueries: string[] = [];
|
||||
page.on('request', (request) => {
|
||||
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
|
||||
sentQueries.push(request.postDataJSON().query);
|
||||
}
|
||||
});
|
||||
|
||||
const searchInput = page.getByTestId('search-input').locator('visible=true');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
const retry = page.getByRole('button', { name: 'Try again' }).locator('visible=true');
|
||||
await expect(retry).toBeVisible();
|
||||
|
||||
failing = false;
|
||||
sentQueries.length = 0;
|
||||
await retry.click();
|
||||
await expect(searchInput).toHaveValue('gitbook');
|
||||
await expect(page.getByTestId('search-results').locator('visible=true')).toBeVisible();
|
||||
await page.waitForTimeout(1000);
|
||||
expect(sentQueries).toEqual(['gitbook']);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - AI Mode: None - URL query (Initial)',
|
||||
url: `${getCustomizationURL({
|
||||
@@ -286,6 +407,68 @@ const searchTestCases: Test[] = [
|
||||
expect(top).toBeLessThanOrEqual(150);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter while results load opens the top result of the last query',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
})}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForCookiesDialog(page);
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const startPath = new URL(page.url()).pathname;
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
const firstSearch = await heldSearch('gitbook');
|
||||
await searchInput.selectText();
|
||||
await searchInput.pressSequentially('files');
|
||||
const lastSearch = await heldSearch('files');
|
||||
|
||||
await page.keyboard.press('Enter');
|
||||
await answerSearch(firstSearch).catch(() => {});
|
||||
await page.waitForTimeout(1000);
|
||||
await expect(page.getByTestId('search-popover')).toBeVisible();
|
||||
await expect(searchInput).toBeFocused();
|
||||
expect(new URL(page.url()).pathname).toBe(startPath);
|
||||
|
||||
const topResult = await answerSearch(lastSearch);
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: topResult.title, exact: true })
|
||||
).toBeVisible({ timeout: 20000 });
|
||||
expect(new URL(page.url()).pathname).toBe(new URL(topResult.href, page.url()).pathname);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Enter opens the result under the mouse',
|
||||
url: `blocks/lists${getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
})}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForCookiesDialog(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
await searchInput.pressSequentially('gitbook');
|
||||
|
||||
const searchPopup = page.getByTestId('search-popover');
|
||||
const hovered = searchPopup.getByTestId('search-page-result').nth(1);
|
||||
await hovered.hover();
|
||||
await expect(hovered).toHaveClass(/is-active/);
|
||||
await expect(searchPopup.locator('[role="option"].is-active')).toHaveCount(1);
|
||||
|
||||
const href = await hovered.getAttribute('href');
|
||||
await page.keyboard.press('Enter');
|
||||
await expect
|
||||
.poll(() => new URL(page.url()).pathname, { timeout: 20000 })
|
||||
.toBe(new URL(href ?? '', page.url()).pathname);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Ask - AI Mode: Assistant - Complete flow',
|
||||
url: getCustomizationURL({
|
||||
@@ -306,10 +489,9 @@ const searchTestCases: Test[] = [
|
||||
await expect(page.getByTestId('ai-chat')).toBeVisible();
|
||||
await expect(page.getByTestId('ai-chat-message-user').first()).toHaveText(AI_PROMPT);
|
||||
await expect(page.getByTestId('ai-chat-message-assistant').first()).toBeVisible();
|
||||
// Wait for the full response (incl. follow-up suggestions) to settle before
|
||||
// asserting/screenshotting, rather than racing a fixed suggestion count.
|
||||
// Wait for the stream, follow-up phase included, to finish before screenshotting.
|
||||
// Follow-ups aren't asserted: the API can return none for this prompt.
|
||||
await waitForAIChatResponse(page);
|
||||
await expect(page.getByTestId('ai-chat-followup-suggestion').first()).toBeVisible();
|
||||
},
|
||||
// Re-applied per viewport so the replacement survives resize-driven re-renders.
|
||||
normalizeBeforeScreenshot: (page) => page.evaluate(overrideAIResponse),
|
||||
@@ -377,16 +559,553 @@ const searchTestCases: Test[] = [
|
||||
await expect(page.getByTestId('ai-chat')).toBeVisible();
|
||||
await expect(page.getByTestId('ai-chat-message-user').first()).toHaveText(AI_PROMPT);
|
||||
await expect(page.getByTestId('ai-chat-message-assistant').first()).toBeVisible();
|
||||
// Wait for the full response (incl. follow-up suggestions) to settle before
|
||||
// asserting/screenshotting, rather than racing a fixed suggestion count.
|
||||
// Wait for the stream, follow-up phase included, to finish before screenshotting.
|
||||
// Follow-ups aren't asserted: the API can return none for this prompt.
|
||||
await waitForAIChatResponse(page);
|
||||
await expect(page.getByTestId('ai-chat-followup-suggestion').first()).toBeVisible();
|
||||
},
|
||||
// Re-applied per viewport so the replacement survives resize-driven re-renders.
|
||||
normalizeBeforeScreenshot: (page) => page.evaluate(overrideAIResponse),
|
||||
},
|
||||
];
|
||||
|
||||
const SEARCH_API_URL = /\/v1\/orgs\/[^/]+\/sites\/[^/]+\/search$/;
|
||||
const SEARCH_PASS_RECORD = {
|
||||
type: 'record',
|
||||
id: 'search-pass-record',
|
||||
title: 'Answered by the search API',
|
||||
description: 'A search made with a search pass',
|
||||
url: 'https://example.com/search-pass',
|
||||
score: 1,
|
||||
};
|
||||
|
||||
/**
|
||||
* Answer the page's search pass requests as the API does when passes are switched on.
|
||||
*/
|
||||
async function giveSearchPasses(page: Page, lifetimesMs: number[] = []) {
|
||||
let passes = 0;
|
||||
await page.route('**/~gitbook/search-pass', async (route) => {
|
||||
passes += 1;
|
||||
await route.fulfill({
|
||||
json: {
|
||||
token: `test-search-pass-${passes}`,
|
||||
expiresIn: lifetimesMs.shift() ?? 300_000,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer each search API call with the next status, and with a record when it succeeds.
|
||||
*/
|
||||
async function answerSearchAPI(page: Page, statuses: number[] = []) {
|
||||
const calls: Request[] = [];
|
||||
await page.route(SEARCH_API_URL, async (route) => {
|
||||
calls.push(route.request());
|
||||
const status = statuses.shift() ?? 200;
|
||||
await route.fulfill({
|
||||
status,
|
||||
headers: { 'access-control-allow-origin': '*' },
|
||||
json: status === 200 ? { items: [SEARCH_PASS_RECORD] } : { error: { code: status } },
|
||||
});
|
||||
});
|
||||
return calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the searches the page sends to the site's search route.
|
||||
*/
|
||||
function trackRouteSearches(page: Page) {
|
||||
const searches: Request[] = [];
|
||||
page.on('request', (request) => {
|
||||
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
|
||||
searches.push(request);
|
||||
}
|
||||
});
|
||||
return searches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open search and wait for the page to receive its search pass.
|
||||
*/
|
||||
async function openSearchWithPass(page: Page) {
|
||||
const passReply = page.waitForResponse('**/~gitbook/search-pass');
|
||||
await page.getByTestId('search-input').focus();
|
||||
await passReply;
|
||||
}
|
||||
|
||||
async function typeSearch(page: Page, text: string) {
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
await searchInput.pressSequentially(text);
|
||||
}
|
||||
|
||||
const searchPassTestCases: Test[] = [
|
||||
{
|
||||
name: 'No pass: searches go through the site route',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await page.route('**/~gitbook/search-pass', (route) => route.fulfill({ status: 204 }));
|
||||
const passReply = page.waitForResponse('**/~gitbook/search-pass');
|
||||
const apiCalls: Request[] = [];
|
||||
page.on('request', (request) => {
|
||||
if (SEARCH_API_URL.test(request.url())) {
|
||||
apiCalls.push(request);
|
||||
}
|
||||
});
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await typeSearch(page, 'gitbook');
|
||||
expect((await passReply).status()).toBe(204);
|
||||
await expect
|
||||
.poll(() => routeSearches.length, { timeout: 30_000 })
|
||||
.toBeGreaterThanOrEqual(1);
|
||||
expect((await routeSearches[0]?.response())?.status()).toBe(200);
|
||||
expect(apiCalls).toHaveLength(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'With a pass: searches go straight to the API',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
expect((await apiCalls[0]?.allHeaders())?.authorization).toBe(
|
||||
'Bearer test-search-pass-1'
|
||||
);
|
||||
expect(routeSearches).toHaveLength(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Expired pass: the search uses the route, then the next pass searches the API',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page, [1_000]);
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('expired');
|
||||
expect(apiCalls).toHaveLength(0);
|
||||
|
||||
await typeSearch(page, ' editor');
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
expect((await apiCalls[0]?.allHeaders())?.authorization).toBe(
|
||||
'Bearer test-search-pass-2'
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Refused pass: the page stays on the route',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const apiCalls = await answerSearchAPI(page, [403]);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
await typeSearch(page, ' editor');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
|
||||
|
||||
expect(
|
||||
routeSearches.map((request) => request.headers()['x-gitbook-search-fallback'])
|
||||
).toEqual(['403', '403']);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
expect((await routeSearches.at(-1)?.response())?.status()).toBe(200);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Dropped API request: the search falls back to the route after its time limit',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await page.clock.install();
|
||||
await giveSearchPasses(page);
|
||||
const apiCalls: Request[] = [];
|
||||
await page.route(SEARCH_API_URL, (route) => {
|
||||
apiCalls.push(route.request());
|
||||
});
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
await page.clock.fastForward(5_000);
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('timeout');
|
||||
expect((await routeSearches[0]?.response())?.status()).toBe(200);
|
||||
|
||||
await typeSearch(page, ' editor');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Withdrawn pass: a no-pass reply stops the page using the earlier pass',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
let passReplies = 0;
|
||||
await page.route('**/~gitbook/search-pass', async (route) => {
|
||||
passReplies += 1;
|
||||
await (passReplies === 1
|
||||
? route.fulfill({ json: { token: 'test-search-pass-1', expiresIn: 300_000 } })
|
||||
: route.fulfill({ status: 204 }));
|
||||
});
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, ' editor');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Rejected replacement pass: the page stays on the route after one refresh',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const passRequests: Request[] = [];
|
||||
page.on('request', (request) => {
|
||||
if (request.url().endsWith('/~gitbook/search-pass')) {
|
||||
passRequests.push(request);
|
||||
}
|
||||
});
|
||||
const apiCalls = await answerSearchAPI(page, [401, 401, 401, 401]);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
for (const [index, text] of ['gitbook', ' editor', ' blocks', ' lists'].entries()) {
|
||||
await typeSearch(page, text);
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(index + 1);
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
expect(apiCalls).toHaveLength(2);
|
||||
expect(passRequests).toHaveLength(2);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Rate limited: the next query waits for the cooldown before using the route',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const apiCalls = await answerSearchAPI(page, [429]);
|
||||
const routeSearchTimes: number[] = [];
|
||||
page.on('request', (request) => {
|
||||
if (request.method() === 'POST' && request.url().endsWith('/~gitbook/search')) {
|
||||
routeSearchTimes.push(Date.now());
|
||||
}
|
||||
});
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
const rateLimited = page.waitForResponse(SEARCH_API_URL);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await rateLimited;
|
||||
const rateLimitedAt = Date.now();
|
||||
await typeSearch(page, ' editor');
|
||||
|
||||
await expect.poll(() => routeSearchTimes.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(routeSearchTimes[0]! - rateLimitedAt).toBeGreaterThanOrEqual(1_500);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Renewing pass: a search typed before the reply goes to the route',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
let releaseRenewal = () => {};
|
||||
const renewalHeld = new Promise<void>((resolve) => {
|
||||
releaseRenewal = resolve;
|
||||
});
|
||||
let passReplies = 0;
|
||||
await page.route('**/~gitbook/search-pass', async (route) => {
|
||||
passReplies += 1;
|
||||
if (passReplies === 1) {
|
||||
await route.fulfill({
|
||||
json: { token: 'test-search-pass-1', expiresIn: 300_000 },
|
||||
});
|
||||
return;
|
||||
}
|
||||
await renewalHeld;
|
||||
await route.fulfill({ status: 204 }).catch(() => undefined);
|
||||
});
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
const renewal = page.waitForRequest('**/~gitbook/search-pass');
|
||||
await typeSearch(page, ' editor');
|
||||
await renewal;
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
releaseRenewal();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Rate limited by a shared limit: searches fail at once until its reset',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const apiCalls: Request[] = [];
|
||||
await page.route(SEARCH_API_URL, async (route) => {
|
||||
apiCalls.push(route.request());
|
||||
await route.fulfill({
|
||||
status: 429,
|
||||
headers: {
|
||||
'access-control-allow-origin': '*',
|
||||
'access-control-expose-headers': 'x-ratelimit-reset, x-ratelimit-scope',
|
||||
'x-ratelimit-reset': String(Math.ceil(Date.now() / 1000) + 60),
|
||||
'x-ratelimit-scope': 'tenant-operation',
|
||||
},
|
||||
json: { error: { code: 429 } },
|
||||
});
|
||||
});
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
await typeSearch(page, ' editor');
|
||||
await expect(page.getByRole('button', { name: 'Try again' })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await page.waitForTimeout(3_000);
|
||||
expect(routeSearches).toHaveLength(0);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Cancelled search: a late API answer never replaces the newer query',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
const staleTitle = 'Late answer for an older query';
|
||||
await page.route(SEARCH_API_URL, async (route) => {
|
||||
const { query } = route.request().postDataJSON() as { query: string };
|
||||
const stale = query === 'gitbook';
|
||||
if (stale) {
|
||||
await page.waitForTimeout(3_000);
|
||||
}
|
||||
await route
|
||||
.fulfill({
|
||||
headers: { 'access-control-allow-origin': '*' },
|
||||
json: {
|
||||
items: [
|
||||
stale
|
||||
? { ...SEARCH_PASS_RECORD, title: staleTitle }
|
||||
: SEARCH_PASS_RECORD,
|
||||
],
|
||||
},
|
||||
})
|
||||
.catch(() => undefined);
|
||||
});
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForCookiesDialog(page);
|
||||
|
||||
const firstSearch = page.waitForRequest(
|
||||
(request) =>
|
||||
SEARCH_API_URL.test(request.url()) &&
|
||||
(request.postDataJSON() as { query: string }).query === 'gitbook'
|
||||
);
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'gitbook');
|
||||
await firstSearch;
|
||||
await typeSearch(page, ' editor');
|
||||
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(4_000);
|
||||
await expect(page.getByText(staleTitle)).toHaveCount(0);
|
||||
expect(routeSearches).toHaveLength(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Embedded search goes straight to the API',
|
||||
url: '~gitbook/embed/search',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveSearchPasses(page);
|
||||
await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
// The embedded page keeps <html> hidden, so wait for hydration without visibility.
|
||||
await page.locator('html.hydrated').waitFor({ state: 'attached' });
|
||||
|
||||
// The embedded search opens on the first key; a one-letter query is never sent.
|
||||
const passReply = page.waitForResponse('**/~gitbook/search-pass');
|
||||
await typeSearch(page, 'g');
|
||||
await passReply;
|
||||
await typeSearch(page, 'itbook');
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('search-record-result')
|
||||
.filter({ hasText: SEARCH_PASS_RECORD.title })
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
// The one-letter query can reach the route when it is sent before the pass arrives.
|
||||
const routeQueries = routeSearches.map((request) => request.postDataJSON().query);
|
||||
expect(routeQueries).not.toContain('gitbook');
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const VISITOR_AUTH_SITE = 'https://gitbook.gitbook.io/gbo-va-space/';
|
||||
|
||||
function signVisitorToken(name: string) {
|
||||
return jwt.sign({ name }, '70b844d0-c519-4532-8586-5970ce48c537', { expiresIn: '24h' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the page one search pass, then answer later pass requests with `later` or the site's route.
|
||||
*/
|
||||
async function giveOneSearchPass(page: Page, later?: { token: string }) {
|
||||
let passes = 0;
|
||||
await page.route('**/~gitbook/search-pass', async (route) => {
|
||||
passes += 1;
|
||||
if (passes > 1 && !later) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
json: {
|
||||
token: passes === 1 ? 'test-search-pass-1' : later?.token,
|
||||
expiresIn: 300_000,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a second tab of the site at `path`, keeping it from leaving for an upstream sign-in page.
|
||||
*/
|
||||
async function visitInOtherTab(page: Page, path: string) {
|
||||
const other = await page.context().newPage();
|
||||
await other.route(
|
||||
(url) => url.hostname !== new URL(page.url()).hostname,
|
||||
(route) => route.abort()
|
||||
);
|
||||
await other.goto(getContentTestURL(new URL(path, VISITOR_AUTH_SITE).href), {
|
||||
waitUntil: 'commit',
|
||||
});
|
||||
await other.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close search and open it again, waiting for the pass request that opening sends.
|
||||
*/
|
||||
async function reopenSearch(page: Page) {
|
||||
await page.keyboard.press('Escape');
|
||||
const passReply = page.waitForResponse('**/~gitbook/search-pass');
|
||||
await page.getByTestId('search-input').focus();
|
||||
return passReply;
|
||||
}
|
||||
|
||||
const searchPassSessionTestCases: Test[] = [
|
||||
{
|
||||
name: 'Signed out in another tab: reopening search drops the pass',
|
||||
url: () => `first?jwt_token=${signVisitorToken('gitbook-open-tests')}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveOneSearchPass(page);
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
const routeSearches = trackRouteSearches(page);
|
||||
await waitForHydration(page);
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'first');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
|
||||
await visitInOtherTab(page, '~gitbook/auth/logout');
|
||||
await expect
|
||||
.poll(async () =>
|
||||
(await page.context().cookies()).some((cookie) =>
|
||||
cookie.name.startsWith(VISITOR_TOKEN_COOKIE)
|
||||
)
|
||||
)
|
||||
.toBe(false);
|
||||
|
||||
expect((await reopenSearch(page)).status()).toBe(401);
|
||||
await typeSearch(page, ' page');
|
||||
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
|
||||
expect(apiCalls).toHaveLength(1);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Signed in as another visitor in another tab: reopening search uses the new pass',
|
||||
url: () => `first?jwt_token=${signVisitorToken('gitbook-open-tests')}`,
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await giveOneSearchPass(page, { token: 'test-search-pass-2' });
|
||||
const apiCalls = await answerSearchAPI(page);
|
||||
await waitForHydration(page);
|
||||
await openSearchWithPass(page);
|
||||
await typeSearch(page, 'first');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
|
||||
|
||||
const otherVisitor = signVisitorToken('another-visitor');
|
||||
await visitInOtherTab(page, `first?jwt_token=${otherVisitor}`);
|
||||
|
||||
const passReply = await reopenSearch(page);
|
||||
expect((await passReply.request().allHeaders()).cookie).toContain(otherVisitor);
|
||||
await typeSearch(page, ' page');
|
||||
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(2);
|
||||
expect((await apiCalls[1]?.allHeaders())?.authorization).toBe(
|
||||
'Bearer test-search-pass-2'
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'GitBook Site (Single Variant)',
|
||||
@@ -480,6 +1199,59 @@ const testCases: TestsCase[] = [
|
||||
await spaceDrowpdown.waitFor();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search scope change while loading shows the new answer in server order',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
await page.waitForURL(/[?&]q=/);
|
||||
await searchInput.pressSequentially('quick');
|
||||
const variantSearch = await heldSearch('quick');
|
||||
|
||||
const searchPopup = page.getByTestId('search-popover');
|
||||
await searchPopup.getByRole('button', { name: 'Multi-Variants' }).click();
|
||||
await page.getByRole('menuitem', { name: /All content/ }).click();
|
||||
const allContentSearch = await heldSearch('quick');
|
||||
|
||||
const variantScope = variantSearch.request().postDataJSON().scope;
|
||||
expect(allContentSearch.request().postDataJSON().scope).not.toEqual(
|
||||
variantScope
|
||||
);
|
||||
const { siteSpaceId } = variantScope;
|
||||
await allContentSearch.fulfill({
|
||||
json: [
|
||||
searchPageResult(allContentSearch, siteSpaceId, 'Welcome!', ''),
|
||||
searchPageResult(
|
||||
allContentSearch,
|
||||
siteSpaceId,
|
||||
'Quick Start',
|
||||
'quick-start'
|
||||
),
|
||||
],
|
||||
});
|
||||
await variantSearch
|
||||
.fulfill({
|
||||
json: [
|
||||
searchPageResult(
|
||||
variantSearch,
|
||||
siteSpaceId,
|
||||
'Quick Start',
|
||||
'quick-start'
|
||||
),
|
||||
],
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
const results = searchPopup.getByTestId('search-page-result');
|
||||
await expect(results).toHaveText([/Welcome!/, /Quick Start/]);
|
||||
await page.waitForTimeout(1000);
|
||||
await expect(results).toHaveText([/Welcome!/, /Quick Start/]);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Default variant',
|
||||
url: '',
|
||||
@@ -1177,6 +1949,16 @@ const testCases: TestsCase[] = [
|
||||
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
tests: searchTestCases,
|
||||
},
|
||||
{
|
||||
name: 'Search pass',
|
||||
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
tests: searchPassTestCases,
|
||||
},
|
||||
{
|
||||
name: 'Search pass with visitor authentication',
|
||||
contentBaseURL: VISITOR_AUTH_SITE,
|
||||
tests: searchPassSessionTestCases,
|
||||
},
|
||||
{
|
||||
name: 'Content tests',
|
||||
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
@@ -2987,6 +3769,78 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Docs Embed - Search',
|
||||
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/~gitbook/embed/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Enter while results load opens the top result',
|
||||
url: 'search',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await page.waitForLoadState('load');
|
||||
const heldSearch = await holdSearchRequests(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.pressSequentially('files');
|
||||
const search = await heldSearch('files');
|
||||
|
||||
await searchInput.press('Enter');
|
||||
await page.waitForTimeout(1000);
|
||||
await expect(searchInput).toBeFocused();
|
||||
await expect(page.getByTestId('embed-docs-page')).toHaveCount(0);
|
||||
|
||||
const topResult = await answerSearch(search);
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: topResult.title, exact: true })
|
||||
).toBeVisible({ timeout: 20000 });
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
runTestCases(testCases);
|
||||
|
||||
test('Docs Embed inherits the site questions unless the host supplies questions', async ({
|
||||
page,
|
||||
}) => {
|
||||
const docsURL = 'https://gitbook.com/docs/';
|
||||
const { apiToken, organization, site, siteSpace } = await getSiteAPIToken(docsURL);
|
||||
const api = new GitBookAPI({ endpoint: 'https://api.gitbook.com/cache', authToken: apiToken });
|
||||
const { data } = await api.orgs.getPublishedContentSite(organization, site, {});
|
||||
const customization = data.customizations.siteSpaces[siteSpace] ?? data.customizations.site;
|
||||
const siteQuestions = [...new Set(customization.ai?.suggestions)];
|
||||
expect(siteQuestions.length).toBeGreaterThan(0);
|
||||
|
||||
const hostURL = getContentTestURL(new URL('~gitbook/embed/demo/', docsURL).href);
|
||||
const loaderURL = getContentTestURL(new URL('~gitbook/embed/script.js', docsURL).href);
|
||||
const hostQuestions = ['Where should I start?'];
|
||||
await page.route(hostURL, (route) =>
|
||||
route.fulfill({
|
||||
contentType: 'text/html',
|
||||
body: `<!doctype html>
|
||||
<button id="override">Use host questions</button>
|
||||
<script src="${loaderURL}"></script>
|
||||
<script>
|
||||
GitBook('configure', {
|
||||
tabs: ['assistant'],
|
||||
assistantName: 'Docs Assistant',
|
||||
suggestions: [],
|
||||
});
|
||||
GitBook('open');
|
||||
document.getElementById('override').onclick = () => {
|
||||
GitBook('configure', { suggestions: ${JSON.stringify(hostQuestions)} });
|
||||
};
|
||||
</script>`,
|
||||
})
|
||||
);
|
||||
|
||||
await page.goto(hostURL, { waitUntil: 'domcontentloaded' });
|
||||
const frame = page.frameLocator('#gitbook-widget-iframe');
|
||||
await expect(frame.getByText('Docs Assistant', { exact: true })).toBeVisible();
|
||||
const questions = frame.getByTestId('ai-chat-suggested-question');
|
||||
await expect(questions).toHaveText(siteQuestions);
|
||||
|
||||
await page.getByRole('button', { name: 'Use host questions' }).click();
|
||||
await expect(questions).toHaveText(hostQuestions);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
import { networkInterfaces } from 'node:os';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Next blocks its dev client and HMR when a physical device opens the server over a LAN address.
|
||||
// Needed to hydrate the dev client on physical phones/tablets over the internal network
|
||||
@@ -119,6 +120,17 @@ const nextConfig = {
|
||||
],
|
||||
},
|
||||
|
||||
webpack(config, { isServer }) {
|
||||
if (isServer) {
|
||||
// mcp-handler only needs redis for SSE, which we disable: keep the client out of the server bundle.
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
redis$: fileURLToPath(new URL('./src/lib/mcp/redis-stub.ts', import.meta.url)),
|
||||
};
|
||||
}
|
||||
return config;
|
||||
},
|
||||
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"name": "gitbook-open-v2",
|
||||
"compatibility_date": "2026-04-02",
|
||||
"keep_names": false,
|
||||
"minify": true,
|
||||
"compatibility_flags": [
|
||||
"nodejs_compat",
|
||||
"allow_importable_env",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import { GitbookIncrementalCache } from './incrementalCache';
|
||||
|
||||
describe('GitbookIncrementalCache.getR2Key', () => {
|
||||
const cache = new GitbookIncrementalCache();
|
||||
|
||||
it('accepts the hashed composable key passed by OpenNext', () => {
|
||||
const storageKey = createHash('sha256').update('["build-id","action",[]]').digest('hex');
|
||||
|
||||
const key = cache.getR2Key(storageKey, 'composable');
|
||||
|
||||
const hash = createHash('sha256').update(storageKey).digest('hex');
|
||||
expect(key).toBe(`incremental-cache/dataCache/${hash}.composable`);
|
||||
});
|
||||
|
||||
it('maps distinct composable keys to distinct R2 keys', () => {
|
||||
expect(cache.getR2Key('a'.repeat(64), 'composable')).not.toBe(
|
||||
cache.getR2Key('b'.repeat(64), 'composable')
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -118,15 +118,8 @@ export class GitbookIncrementalCache implements IncrementalCache {
|
||||
}
|
||||
}
|
||||
|
||||
// Utility function to generate keys for R2/Cache API
|
||||
getR2Key(initialKey: string, cacheType: CacheEntryType = 'cache'): string {
|
||||
let key = initialKey;
|
||||
if (cacheType === 'composable') {
|
||||
// For composable cache, we need to discard the build ID from the key
|
||||
const [_buildId, ...restOfTheKey] = JSON.parse(initialKey);
|
||||
key = JSON.stringify([...restOfTheKey]);
|
||||
}
|
||||
|
||||
// OpenNext pre-hashes composable keys with the build ID in them: no reuse across deploys.
|
||||
getR2Key(key: string, cacheType: CacheEntryType = 'cache'): string {
|
||||
const hash = createHash('sha256').update(key).digest('hex');
|
||||
return `${DEFAULT_PREFIX}/${cacheType === 'cache' ? process.env?.NEXT_BUILD_ID : 'dataCache'}/${hash}.${cacheType}`.replace(
|
||||
/\/+/g,
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@mermaid-js/mermaid-zenuml": "^0.2.2",
|
||||
"@modelcontextprotocol/sdk": "1.17.5",
|
||||
"@opennextjs/aws": "4.1.15",
|
||||
"@opennextjs/cloudflare": "1.20.16",
|
||||
"@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",
|
||||
@@ -51,7 +51,7 @@
|
||||
"micromark-extension-gfm": "^3.0.0",
|
||||
"motion": "^12.23.24",
|
||||
"negotiator": "^1.0.0",
|
||||
"next": "^16.4.5",
|
||||
"next": "^16.4.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"nuqs": "^2.2.3",
|
||||
"object-hash": "^3.0.0",
|
||||
@@ -59,6 +59,7 @@
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.3",
|
||||
"p-retry": "^8.0.0",
|
||||
"parse5": "7.2.0",
|
||||
"quick-lru": "^7.0.1",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
@@ -88,7 +89,6 @@
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^7.2.0",
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@scalar/api-client-react": "catalog:",
|
||||
"@tailwindcss/postcss": "^4.1.11",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
@@ -118,9 +118,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "./scripts/generate.sh",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/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",
|
||||
@@ -135,7 +135,7 @@
|
||||
"e2e": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.spec.ts e2e/tabs-overflow.spec.ts --project=chromium",
|
||||
"e2e-customers": "playwright test e2e/customers.spec.ts --project=chromium",
|
||||
"e2e-style-perf": "playwright test e2e/style-perf.spec.ts --project=chromium --reporter=list",
|
||||
"unit": "bun run generate:assets && bun test {src,packages} --preload ./tests/preload-bun.ts",
|
||||
"unit": "bun run generate:assets && bun test {src,packages,openNext} --preload ./tests/preload-bun.ts",
|
||||
"e2e-browserless": "bun test ./tests/",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
|
||||
@@ -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
@@ -50,6 +50,7 @@ export async function handleMcpRequest(
|
||||
streamableHttpEndpoint: context.linker.toPathInSite(endpoint),
|
||||
maxDuration: 60,
|
||||
verboseLogs: true,
|
||||
// SSE needs redis, which next.config.mjs stubs out of the server bundle.
|
||||
disableSse: true,
|
||||
}
|
||||
);
|
||||
|
||||
+14
@@ -1,13 +1,18 @@
|
||||
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 { throwIfDataError } from '@/lib/data';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
|
||||
import { transformSitePageResult } from '@/lib/search';
|
||||
import { computeSearchResults } from '@/lib/search-results';
|
||||
import { getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
|
||||
|
||||
const SEARCH_FALLBACK_REASON =
|
||||
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
|
||||
const [context, siteURLData] = await Promise.all([
|
||||
@@ -15,6 +20,15 @@ export async function POST(request: NextRequest) {
|
||||
getSiteURLDataFromMiddleware(),
|
||||
]);
|
||||
|
||||
const fallback = request.headers.get(SEARCH_FALLBACK_HEADER);
|
||||
if (fallback && SEARCH_FALLBACK_REASON.test(fallback)) {
|
||||
getLogger()
|
||||
.subLogger('search')
|
||||
.info(
|
||||
`Search pass fallback to the route (reason=${fallback}, organization=${siteURLData.organization}, site=${siteURLData.site})`
|
||||
);
|
||||
}
|
||||
|
||||
if (query.length <= 1) {
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
|
||||
import { serveOpenSearchDescription } from '@/routes/opensearch';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
export async function GET(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<RouteLayoutParams> }
|
||||
) {
|
||||
const { context } = await getStaticSiteContext(await params);
|
||||
return serveOpenSearchDescription(context);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { jwtDecode } from 'jwt-decode';
|
||||
import { forbidden, notFound } from 'next/navigation';
|
||||
import { cache } from 'react';
|
||||
import rison from 'rison';
|
||||
|
||||
import type { SiteAPIToken } from '@gitbook/api';
|
||||
@@ -27,7 +28,17 @@ export type RouteParams = RouteLayoutParams & {
|
||||
/**
|
||||
* Get the static context when rendering statically a site.
|
||||
*/
|
||||
export async function getStaticSiteContext(params: RouteLayoutParams) {
|
||||
export function getStaticSiteContext(params: RouteLayoutParams) {
|
||||
return getStaticSiteContextCached(params.mode, params.siteURL, params.siteData);
|
||||
}
|
||||
|
||||
// Layouts, pages and their metadata functions each resolve the context: share it per request.
|
||||
// Keyed on the raw strings as `params` objects aren't guaranteed to be the same reference.
|
||||
const getStaticSiteContextCached = cache((mode: string, siteURL: string, siteData: string) =>
|
||||
resolveStaticSiteContext({ mode, siteURL, siteData })
|
||||
);
|
||||
|
||||
async function resolveStaticSiteContext(params: RouteLayoutParams) {
|
||||
const siteURL = getSiteURLFromParams(params);
|
||||
const siteURLData = getSiteURLDataFromParams(params);
|
||||
|
||||
@@ -57,7 +68,15 @@ export async function getStaticSiteContext(params: RouteLayoutParams) {
|
||||
* Get the site context when rendering dynamically.
|
||||
* The context will depend on the request.
|
||||
*/
|
||||
export async function getDynamicSiteContext(params: RouteLayoutParams) {
|
||||
export function getDynamicSiteContext(params: RouteLayoutParams) {
|
||||
return getDynamicSiteContextCached(params.mode, params.siteURL, params.siteData);
|
||||
}
|
||||
|
||||
const getDynamicSiteContextCached = cache((mode: string, siteURL: string, siteData: string) =>
|
||||
resolveDynamicSiteContext({ mode, siteURL, siteData })
|
||||
);
|
||||
|
||||
async function resolveDynamicSiteContext(params: RouteLayoutParams) {
|
||||
const siteURL = getSiteURLFromParams(params);
|
||||
const siteURLData = getSiteURLDataFromParams(params);
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export async function* streamAIChatResponse({
|
||||
},
|
||||
]
|
||||
: [],
|
||||
model: AIModel.ReasoningLow,
|
||||
model: AIModel.ReasoningMedium,
|
||||
previousResponseId,
|
||||
toolCall,
|
||||
tools,
|
||||
|
||||
@@ -57,7 +57,6 @@ export function CookiesToast(props: { privacyPolicy?: string }) {
|
||||
<div
|
||||
role="dialog"
|
||||
data-testid="cookies-dialog"
|
||||
aria-modal="true"
|
||||
aria-label={tString(language, 'cookies_title')}
|
||||
aria-describedby={describedById}
|
||||
className={tcls(
|
||||
|
||||
@@ -180,7 +180,11 @@ function CodeBlockExpandable(props: {
|
||||
<div
|
||||
className={tcls(
|
||||
!isExpanded
|
||||
? '[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden'
|
||||
? [
|
||||
'[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden',
|
||||
// Mask the code rather than the pre to keep its border, with stops on the visible lines.
|
||||
'[&_code]:mask-b-from-[calc((var(--line-count)+1)*var(--line-height)*0.55)] [&_code]:mask-b-to-[calc((var(--line-count)+1)*var(--line-height))]',
|
||||
]
|
||||
: ''
|
||||
)}
|
||||
style={
|
||||
|
||||
@@ -127,8 +127,7 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
|
||||
<code
|
||||
className={tcls(
|
||||
'table max-h-full w-fit min-w-full [counter-reset:line] print:max-h-none print:whitespace-pre-wrap',
|
||||
withWrap && 'whitespace-pre-wrap',
|
||||
'[[aria-expanded=false]_&]:mask-b-from-50%'
|
||||
withWrap && 'whitespace-pre-wrap'
|
||||
)}
|
||||
>
|
||||
{theme.lines.map((line, index) => (
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { getCodeTextFromId } from './utils';
|
||||
import { useCopyToClipboard } from '@/components/hooks';
|
||||
import { Button } from '@/components/primitives';
|
||||
import { t, useLanguage } from '@/intl/client';
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
@@ -15,41 +14,30 @@ export function CopyCodeButton(props: { codeId: string; style: ClassValue }) {
|
||||
const { codeId, style } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!copied) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}, [copied]);
|
||||
const { copied, copy } = useCopyToClipboard();
|
||||
|
||||
const onClick = () => {
|
||||
const codeText = getCodeTextFromId(codeId);
|
||||
if (codeText === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(codeText);
|
||||
|
||||
setCopied(true);
|
||||
copy(codeText);
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
onClick={onClick}
|
||||
className={tcls(style, 'translate-y-0!', 'print:hidden')}
|
||||
>
|
||||
{t(language, copied ? 'code_copied' : 'code_copy')}
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
onClick={onClick}
|
||||
className={tcls(style, 'translate-y-0!', 'print:hidden')}
|
||||
>
|
||||
{t(language, copied ? 'code_copied' : 'code_copy')}
|
||||
</Button>
|
||||
{/* A label swap on the focused button isn't announced, the live region is. */}
|
||||
<span role="status" className="sr-only">
|
||||
{copied ? t(language, 'code_copied') : null}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DocumentBlockHint } from '@gitbook/api';
|
||||
import { Icon, type IconName } from '@gitbook/icons';
|
||||
import { validateIconName } from '@gitbook/icons/icons';
|
||||
import { validateIconName } from '@gitbook/icons/validateIconName';
|
||||
|
||||
import { Block, type BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
@@ -40,7 +40,12 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
return (
|
||||
<NotFoundRefHoverCard context={context}>
|
||||
{fallback ? (
|
||||
<InlineLinkAnchor href={fallback.href} contentRef={inline.data.ref} isExternal>
|
||||
<InlineLinkAnchor
|
||||
href={fallback.href}
|
||||
contentRef={inline.data.ref}
|
||||
target={inline.data.target}
|
||||
isExternal
|
||||
>
|
||||
{inlinesElement}
|
||||
</InlineLinkAnchor>
|
||||
) : (
|
||||
@@ -53,6 +58,7 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
<InlineLinkAnchor
|
||||
href={resolved.href}
|
||||
contentRef={resolved.resolvedRef ?? inline.data.ref}
|
||||
target={inline.data.target}
|
||||
isExternal={(resolved.resolvedRef ?? inline.data.ref).kind === 'url'}
|
||||
>
|
||||
{inlinesElement}
|
||||
@@ -75,14 +81,16 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
function InlineLinkAnchor(props: {
|
||||
href: string;
|
||||
contentRef: ContentRef;
|
||||
target: DocumentInlineLink['data']['target'];
|
||||
isExternal?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { href, isExternal, contentRef, children } = props;
|
||||
const { href, isExternal, contentRef, target, children } = props;
|
||||
const isMailto = href.startsWith('mailto:');
|
||||
return (
|
||||
<StyledLink
|
||||
href={href}
|
||||
target={target ? `_${target}` : undefined}
|
||||
insights={{
|
||||
type: 'link_click',
|
||||
link: {
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
.contentkit-modal {
|
||||
@apply flex flex-col gap-6 relative z-50 bg-tint
|
||||
rounded shadow-lg opacity-0 transition-opacity duration-300 border border-tint
|
||||
w-full max-w-[768px] max-h-[90vh] overflow-y-auto;
|
||||
w-full max-w-[768px] max-h-[90dvh] overflow-y-auto;
|
||||
}
|
||||
.contentkit-modal.contentkit-modal-opened {
|
||||
@apply opacity-[1];
|
||||
|
||||
@@ -16,6 +16,8 @@ import { matchesText } from '../Table/searchMatch';
|
||||
import { MIN_RECORDS_FOR_SEARCH } from '../Table/shouldShowSearch';
|
||||
import { Input } from '@/components/primitives';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
// Imported here, behind the `next/dynamic` boundary, so only pages with OpenAPI blocks load it.
|
||||
import './style.css';
|
||||
|
||||
// Only what survives the RSC boundary. Rebuilding the renderers on the client is what lets this
|
||||
// whole subtree sit behind a `next/dynamic` chunk instead of the route's eager entry.
|
||||
@@ -36,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 =
|
||||
@@ -68,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,10 +16,7 @@ import { PlainCodeBlock } from '../CodeBlock';
|
||||
import { DocumentView } from '../DocumentView';
|
||||
import { Heading } from '../Heading';
|
||||
import type { OpenAPIBlockClientContextProps } from './OpenAPIBlockClient';
|
||||
import './style.css';
|
||||
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';
|
||||
@@ -125,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,
|
||||
@@ -146,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;
|
||||
@@ -159,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,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/* Global, not in style.css: badges also show in the sidebar and outline of pages without OpenAPI blocks. */
|
||||
.openapi-method,
|
||||
.openapi-statuscode {
|
||||
@apply m-0 h-5 min-w-9 justify-center rounded-md text-xs straight-corners:rounded-none circular-corners:rounded-lg uppercase font-mono items-center shrink-0 font-semibold px-1.5 py-0.5 text-tint-12/8 leading-tight align-middle inline-flex whitespace-nowrap;
|
||||
}
|
||||
|
||||
.openapi-method-small {}
|
||||
|
||||
.openapi-method-medium {
|
||||
@apply m-0 px-2.5 py-1 h-6 text-[0.813rem];
|
||||
}
|
||||
|
||||
.toclink .openapi-method {
|
||||
@apply text-[0.625rem] flex items-center justify-center;
|
||||
}
|
||||
|
||||
.openapi-method-get,
|
||||
.openapi-statuscode-success {
|
||||
@apply bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100;
|
||||
}
|
||||
|
||||
.openapi-method-post,
|
||||
.openapi-statuscode-redirection {
|
||||
@apply bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-100;
|
||||
}
|
||||
|
||||
.openapi-method-put,
|
||||
.openapi-statuscode-informational {
|
||||
@apply bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100;
|
||||
}
|
||||
|
||||
.openapi-method-patch {
|
||||
@apply bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100;
|
||||
}
|
||||
|
||||
.openapi-method-delete,
|
||||
.openapi-statuscode-error {
|
||||
@apply bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100;
|
||||
}
|
||||
|
||||
.openapi-method-head,
|
||||
.openapi-method-options,
|
||||
.openapi-method-trace,
|
||||
.openapi-method-hook {
|
||||
@apply bg-tint;
|
||||
}
|
||||
@@ -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,
|
||||
@@ -143,53 +143,6 @@ button.openapi-mcp {
|
||||
@apply !mb-0;
|
||||
}
|
||||
|
||||
/* Method Tags */
|
||||
.openapi-method,
|
||||
.openapi-statuscode {
|
||||
@apply m-0 h-5 min-w-9 justify-center rounded-md text-xs straight-corners:rounded-none circular-corners:rounded-lg uppercase font-mono items-center shrink-0 font-semibold px-1.5 py-0.5 text-tint-12/8 leading-tight align-middle inline-flex whitespace-nowrap;
|
||||
}
|
||||
|
||||
.openapi-method-small {}
|
||||
|
||||
.openapi-method-medium {
|
||||
@apply m-0 px-2.5 py-1 h-6 text-[0.813rem];
|
||||
}
|
||||
|
||||
.toclink .openapi-method {
|
||||
@apply text-[0.625rem] flex items-center justify-center;
|
||||
}
|
||||
|
||||
.openapi-method-get,
|
||||
.openapi-statuscode-success {
|
||||
@apply bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100;
|
||||
}
|
||||
|
||||
.openapi-method-post,
|
||||
.openapi-statuscode-redirection {
|
||||
@apply bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-100;
|
||||
}
|
||||
|
||||
.openapi-method-put,
|
||||
.openapi-statuscode-informational {
|
||||
@apply bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100;
|
||||
}
|
||||
|
||||
.openapi-method-patch {
|
||||
@apply bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100;
|
||||
}
|
||||
|
||||
.openapi-method-delete,
|
||||
.openapi-statuscode-error {
|
||||
@apply bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100;
|
||||
}
|
||||
|
||||
.openapi-method-head,
|
||||
.openapi-method-options,
|
||||
.openapi-method-trace,
|
||||
.openapi-method-hook {
|
||||
@apply bg-tint;
|
||||
}
|
||||
|
||||
/* URL */
|
||||
.openapi-url {
|
||||
@apply font-mono text-sm text-tint;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
type DocumentBlockPrompt,
|
||||
type SiteCustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import { validateIconName } from '@gitbook/icons/icons';
|
||||
import { validateIconName } from '@gitbook/icons/validateIconName';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
import { CodeBlock } from '../CodeBlock';
|
||||
|
||||
@@ -5,6 +5,7 @@ import React from 'react';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { type PromptActionId, setPromptAction, usePromptAction } from './promptAction';
|
||||
import { useCopyToClipboard } from '@/components/hooks';
|
||||
import {
|
||||
Button,
|
||||
ButtonGroup,
|
||||
@@ -27,25 +28,10 @@ export function PromptActions(props: { prompt: string; openInAIProviders: boolea
|
||||
const { prompt, openInAIProviders } = props;
|
||||
const language = useLanguage();
|
||||
const selectedAction = usePromptAction();
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!copied) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, COPIED_MESSAGE_DURATION);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}, [copied]);
|
||||
const { copied, copy } = useCopyToClipboard(COPIED_MESSAGE_DURATION);
|
||||
|
||||
const copyPrompt = () => {
|
||||
navigator.clipboard.writeText(prompt);
|
||||
setCopied(true);
|
||||
copy(prompt);
|
||||
};
|
||||
|
||||
// The pick follows the visitor from site to site, so fall back to copying wherever the agent
|
||||
|
||||
@@ -12,7 +12,13 @@ mock.module('./RecordCard', () => ({
|
||||
}));
|
||||
|
||||
mock.module('./TableSearch', () => ({
|
||||
TableSearchRecord: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TableSearchRecord: ({
|
||||
children,
|
||||
visibleClassName,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
visibleClassName: string;
|
||||
}) => <div className={visibleClassName}>{children}</div>,
|
||||
}));
|
||||
|
||||
const { ViewCards } = await import('./ViewCards');
|
||||
@@ -43,21 +49,51 @@ describe('ViewCards', () => {
|
||||
it('renders the carousel with a symmetric peek and conditional edge masks', () => {
|
||||
const markup = renderWithContext(<ViewCards {...makeProps(false)} />);
|
||||
|
||||
expect(markup).toContain('-mx-12');
|
||||
expect(markup).toContain('px-12');
|
||||
expect(markup).toContain('scroll-px-12');
|
||||
// Gutter-sized peek, the full 3rem from `2xl`.
|
||||
expect(markup).toContain('-mx-4 sm:-mx-6 md:-mx-8 2xl:-mx-12');
|
||||
expect(markup).toContain('scroll-px-4');
|
||||
expect(markup).toContain('2xl:scroll-px-12');
|
||||
expect(markup).toContain('left-0');
|
||||
expect(markup).toContain('ml-8');
|
||||
expect(markup).toContain('2xl:ml-8');
|
||||
expect(markup).toContain('right-0');
|
||||
expect(markup).toContain('mr-8');
|
||||
expect(markup).toContain('2xl:mr-8');
|
||||
expect(markup).not.toContain('before:bg-linear-to-r');
|
||||
expect(markup).not.toContain('after:bg-linear-to-l');
|
||||
expect(markup).toContain('snap-mandatory');
|
||||
});
|
||||
|
||||
it('renders the wrapping grid by default', () => {
|
||||
const markup = renderWithContext(<ViewCards {...makeProps(true)} />);
|
||||
it.each([true, undefined])('renders the wrapping grid with wrap=%s', (wrap) => {
|
||||
const props = makeProps(true);
|
||||
props.view.wrap = wrap;
|
||||
const markup = renderWithContext(<ViewCards {...props} />);
|
||||
|
||||
expect(markup).toContain('inline-grid');
|
||||
});
|
||||
it('renders small cards in four columns and uses the grid for print', () => {
|
||||
const props = makeProps(true);
|
||||
props.view.cardSize = 'small';
|
||||
expect(renderWithContext(<ViewCards {...props} />)).toContain('@3xl:grid-cols-4');
|
||||
|
||||
props.view.wrap = false;
|
||||
const carousel = renderWithContext(<ViewCards {...props} />);
|
||||
expect(carousel).toContain('@3xl:w-[calc(22.5%-0.75rem)]');
|
||||
expect(carousel).toContain('@5xl:w-[calc(25%-0.75rem)]');
|
||||
|
||||
props.context.mode = 'print';
|
||||
const printed = renderWithContext(<ViewCards {...props} />);
|
||||
expect(printed).toContain('@3xl:grid-cols-4');
|
||||
expect(printed).not.toContain('snap-mandatory');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['medium', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
|
||||
['large', '@xl:grid-cols-2', '@5xl:w-[calc(50%-0.5rem)]'],
|
||||
['unknown', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
|
||||
])('preserves %s card layouts', (cardSize, grid, carousel) => {
|
||||
const props = makeProps(true);
|
||||
props.view.cardSize = cardSize;
|
||||
expect(renderWithContext(<ViewCards {...props} />)).toContain(grid);
|
||||
props.view.wrap = false;
|
||||
expect(renderWithContext(<ViewCards {...props} />)).toContain(carousel);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,18 @@ import { TableSearchRecord } from './TableSearch';
|
||||
import { ScrollContainer } from '@/components/primitives/ScrollContainer';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
const gridColumns = {
|
||||
small: '@sm:grid-cols-2 @2xl:grid-cols-3 @3xl:grid-cols-4',
|
||||
medium: '@2xl:grid-cols-3 @sm:grid-cols-2',
|
||||
large: '@xl:grid-cols-2',
|
||||
};
|
||||
|
||||
const carouselWidths = {
|
||||
small: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @3xl:w-[calc(22.5%-0.75rem)] @5xl:w-[calc(25%-0.75rem)]',
|
||||
medium: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]',
|
||||
large: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]',
|
||||
};
|
||||
|
||||
export function ViewCards(props: TableViewProps<DocumentTableViewCards>) {
|
||||
// `wrap` defaults to `true` (a wrapping grid); only an explicit `false` opts into the
|
||||
// horizontally-scrolling carousel row. Fall back to the grid in print mode: a PDF can't
|
||||
@@ -30,7 +42,7 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
|
||||
'inline-grid',
|
||||
'gap-4',
|
||||
'grid-cols-1',
|
||||
view.cardSize === 'large' ? '@xl:grid-cols-2' : '@2xl:grid-cols-3 @sm:grid-cols-2', // Large cards break earlier to avoid becoming *too* big.
|
||||
gridColumns[view.cardSize] ?? gridColumns.medium,
|
||||
block.data.fullWidth ? 'large:flex-column' : null
|
||||
)}
|
||||
>
|
||||
@@ -49,6 +61,16 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
|
||||
);
|
||||
}
|
||||
|
||||
// The peek fits the page gutter (`CONTAINER_STYLE`) so the fade stays on screen; from `2xl` the
|
||||
// cards fill the row exactly and need the full 3rem to show the next one.
|
||||
const PEEK = {
|
||||
margin: '-mx-4 sm:-mx-6 md:-mx-8 2xl:-mx-12',
|
||||
padding:
|
||||
'px-4 scroll-px-4 sm:px-6 sm:scroll-px-6 md:px-8 md:scroll-px-8 2xl:px-12 2xl:scroll-px-12',
|
||||
leadingButton: 'ml-0 sm:ml-2 md:ml-4 2xl:ml-8',
|
||||
trailingButton: 'mr-0 sm:mr-2 md:mr-4 2xl:mr-8',
|
||||
};
|
||||
|
||||
/**
|
||||
* The carousel layout: cards lay out in a single horizontally-scrolling row that
|
||||
* snaps to the leftmost card. Reuses ScrollContainer for the scroll buttons.
|
||||
@@ -60,17 +82,10 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
|
||||
function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
const { view, records } = props;
|
||||
|
||||
// Cards need a fixed width so the row overflows and scrolls; mirror the grid's
|
||||
// medium/large sizing.
|
||||
const cardWidth =
|
||||
view.cardSize === 'large'
|
||||
? 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]'
|
||||
: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]';
|
||||
|
||||
return (
|
||||
<ScrollContainer
|
||||
orientation="horizontal"
|
||||
className={tcls('-mx-12', 'hover:z-11')}
|
||||
className={tcls(PEEK.margin, 'hover:z-11')}
|
||||
// `py-1` keeps the card ring/shadow from being clipped by the scroll overflow;
|
||||
// `snap-mandatory` + the scroll-padding snap each card to the content edge.
|
||||
contentClassName={tcls(
|
||||
@@ -79,19 +94,18 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
'-mt-px',
|
||||
'pb-6',
|
||||
'-mb-6',
|
||||
'px-12',
|
||||
'scroll-px-12',
|
||||
PEEK.padding,
|
||||
'snap-x',
|
||||
'snap-mandatory'
|
||||
)}
|
||||
scrollByVisibleItems
|
||||
leading={{
|
||||
fade: true,
|
||||
button: { size: 'small', className: 'ml-8' },
|
||||
button: { size: 'small', className: PEEK.leadingButton },
|
||||
}}
|
||||
trailing={{
|
||||
fade: true,
|
||||
button: { size: 'small', className: 'mr-8' },
|
||||
button: { size: 'small', className: PEEK.trailingButton },
|
||||
}}
|
||||
>
|
||||
{records.map((record) => {
|
||||
@@ -106,7 +120,7 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
'grid-cols-1',
|
||||
'shrink-0',
|
||||
'snap-start',
|
||||
cardWidth
|
||||
carouselWidths[view.cardSize] ?? carouselWidths.medium
|
||||
)}
|
||||
>
|
||||
<RecordCard {...props} record={record} />
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { getNextTabIndex } from './DynamicTabs';
|
||||
|
||||
describe('getNextTabIndex', () => {
|
||||
it('moves with the arrow keys and wraps around', () => {
|
||||
expect(getNextTabIndex('ArrowRight', 0, 3)).toBe(1);
|
||||
expect(getNextTabIndex('ArrowRight', 2, 3)).toBe(0);
|
||||
expect(getNextTabIndex('ArrowLeft', 0, 3)).toBe(2);
|
||||
});
|
||||
|
||||
it('jumps to the first and last tab', () => {
|
||||
expect(getNextTabIndex('Home', 2, 3)).toBe(0);
|
||||
expect(getNextTabIndex('End', 0, 3)).toBe(2);
|
||||
});
|
||||
|
||||
it('mirrors the arrows in right-to-left', () => {
|
||||
expect(getNextTabIndex('ArrowLeft', 0, 3, true)).toBe(1);
|
||||
expect(getNextTabIndex('ArrowRight', 0, 3, true)).toBe(2);
|
||||
});
|
||||
|
||||
it('ignores other keys and an unknown tab', () => {
|
||||
expect(getNextTabIndex('Enter', 0, 3)).toBeNull();
|
||||
expect(getNextTabIndex('ArrowRight', -1, 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -151,10 +151,15 @@ const TabItemList = memo(function TabItemList(props: {
|
||||
}).filter((x) => x !== undefined),
|
||||
[overflowing, tabs]
|
||||
);
|
||||
// Roving tabindex: one tab stop for the strip, the active tab when it isn't in the overflow menu.
|
||||
const visibleTabs = tabs.filter((tab) => !overflowing.has(getTabButtonId(tab.id)));
|
||||
const focusableTabId =
|
||||
visibleTabs.find((tab) => tab.id === activeTabId)?.id ?? visibleTabs[0]?.id ?? null;
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
role="tablist"
|
||||
onKeyDown={moveFocusBetweenTabs}
|
||||
className={tcls(
|
||||
'group/tabs',
|
||||
'overflow-hidden',
|
||||
@@ -182,6 +187,7 @@ const TabItemList = memo(function TabItemList(props: {
|
||||
key={tab.id}
|
||||
ref={itemRef}
|
||||
isActive={tab.id === activeTabId}
|
||||
isFocusable={tab.id === focusableTabId}
|
||||
isMeasuring={isMeasuring}
|
||||
tab={tab}
|
||||
onSelect={onSelect}
|
||||
@@ -241,16 +247,18 @@ function TabsDropdownMenu(props: {
|
||||
const TabItem = memo(function TabItem(props: {
|
||||
ref: React.Ref<HTMLButtonElement>;
|
||||
isActive: boolean;
|
||||
isFocusable: boolean;
|
||||
isMeasuring: boolean;
|
||||
tab: TabsItem;
|
||||
onSelect: (tabId: string) => void;
|
||||
}) {
|
||||
const { ref, tab, isActive, isMeasuring, onSelect } = props;
|
||||
const { ref, tab, isActive, isFocusable, isMeasuring, onSelect } = props;
|
||||
return (
|
||||
<TabButton
|
||||
ref={ref}
|
||||
role="tab"
|
||||
aria-selected={isActive}
|
||||
tabIndex={isFocusable ? 0 : -1}
|
||||
aria-controls={tab.id}
|
||||
id={getTabButtonId(tab.id)}
|
||||
title={tab.title}
|
||||
@@ -343,6 +351,55 @@ function TabButton(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Arrow keys, Home and End move focus between the tabs of a tablist; Enter or Space then selects.
|
||||
*/
|
||||
function moveFocusBetweenTabs(event: React.KeyboardEvent<HTMLElement>) {
|
||||
const current = event.target instanceof HTMLElement ? event.target : null;
|
||||
if (current?.getAttribute('role') !== 'tab') {
|
||||
return;
|
||||
}
|
||||
const tabs = Array.from(
|
||||
event.currentTarget.querySelectorAll<HTMLElement>('[role="tab"]:not([disabled])')
|
||||
);
|
||||
const index = tabs.indexOf(current);
|
||||
const isRTL = getComputedStyle(event.currentTarget).direction === 'rtl';
|
||||
const next = getNextTabIndex(event.key, index, tabs.length, isRTL);
|
||||
if (next === null) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
tabs[next]?.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Index of the tab to focus for a key press, or null when the key doesn't move focus.
|
||||
*/
|
||||
export function getNextTabIndex(
|
||||
key: string,
|
||||
index: number,
|
||||
count: number,
|
||||
isRTL = false
|
||||
): number | null {
|
||||
if (index < 0 || count === 0) {
|
||||
return null;
|
||||
}
|
||||
const forward = isRTL ? 'ArrowLeft' : 'ArrowRight';
|
||||
const backward = isRTL ? 'ArrowRight' : 'ArrowLeft';
|
||||
switch (key) {
|
||||
case forward:
|
||||
return (index + 1) % count;
|
||||
case backward:
|
||||
return (index - 1 + count) % count;
|
||||
case 'Home':
|
||||
return 0;
|
||||
case 'End':
|
||||
return count - 1;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ID for a tab button.
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DocumentBlockTabs } from '@gitbook/api';
|
||||
import type { IconName } from '@gitbook/icons';
|
||||
import { validateIconName } from '@gitbook/icons/icons';
|
||||
import { validateIconName } from '@gitbook/icons/validateIconName';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
import { Blocks } from '../Blocks';
|
||||
|
||||
@@ -125,6 +125,9 @@ function Color(props: MarkedLeafProps<DocumentMarkColor>) {
|
||||
const { mark, children } = props;
|
||||
return (
|
||||
<span
|
||||
data-highlight={
|
||||
mark.data.background && mark.data.background !== 'default' ? '' : undefined
|
||||
}
|
||||
className={tcls([
|
||||
textColorToStyle[mark.data.text ?? 'default'],
|
||||
backgroundColorToStyle[mark.data.background ?? 'default'],
|
||||
|
||||
@@ -18,7 +18,7 @@ export function EmbeddableAIContextProvider(props: EmbeddableAIContextProviderPr
|
||||
return (
|
||||
<AIContextProvider
|
||||
aiMode={aiMode}
|
||||
suggestions={embedConfig.suggestions ?? suggestions}
|
||||
suggestions={embedConfig.suggestions?.length ? embedConfig.suggestions : suggestions}
|
||||
greeting={embedConfig.greeting ?? greeting}
|
||||
trademark={trademark && (embedConfig.trademark ?? true)}
|
||||
assistantName={embedConfig.assistantName?.substring(0, 32)} // Limit to 32 characters
|
||||
|
||||
@@ -5,7 +5,11 @@ import React, { useEffect, useRef } from 'react';
|
||||
import { createStore, useStore } from 'zustand';
|
||||
|
||||
import type { GitBookIntegrationTool } from '@gitbook/browser-types';
|
||||
import type { GitBookEmbeddableConfiguration, ParentToFrameMessage } from '@gitbook/embed';
|
||||
import type {
|
||||
FrameToParentMessage,
|
||||
GitBookEmbeddableConfiguration,
|
||||
ParentToFrameMessage,
|
||||
} from '@gitbook/embed';
|
||||
|
||||
import { integrationsAssistantTools } from '../Integrations';
|
||||
import { Button, LinkContext, type LinkContextType } from '../primitives';
|
||||
@@ -20,7 +24,6 @@ const embeddableConfiguration = createStore<GitBookEmbeddableConfiguration>(() =
|
||||
tabs: [],
|
||||
actions: [],
|
||||
greeting: { title: '', subtitle: '' },
|
||||
suggestions: [],
|
||||
tools: [],
|
||||
trademark: true,
|
||||
}));
|
||||
@@ -69,6 +72,27 @@ export function EmbeddableIframeAPI(props: { baseURL: string }) {
|
||||
});
|
||||
}, [chatController]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const channel = getChannel();
|
||||
if (!channel) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Menus, dialogs and the zoomed image call preventDefault when Escape closes them.
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
!event.defaultPrevented &&
|
||||
!event.isComposing &&
|
||||
!event.repeat
|
||||
) {
|
||||
channel.send({ type: 'escape' } satisfies FrameToParentMessage);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
return () => window.removeEventListener('keydown', onKeyDown);
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
const channel = getChannel();
|
||||
if (!channel) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { EmbeddableIframeAPI } from './EmbeddableIframeAPI';
|
||||
import { EmbeddableThemeSync } from './EmbeddableThemeSync';
|
||||
import { IfEmbeddableTrademark } from './EmbeddableTrademark';
|
||||
import { CustomizationRootLayout } from '@/components/RootLayout';
|
||||
import { getDirectSearchProps } from '@/components/Search/search-props';
|
||||
import {
|
||||
SiteLayoutClientContexts,
|
||||
generateSiteLayoutMetadata,
|
||||
@@ -60,6 +61,7 @@ export async function EmbeddableRootLayout({
|
||||
contextId={context.contextId}
|
||||
proxyOrigin={context.site.proxy?.origin}
|
||||
searchPrewarmURL={context.linker.toPathInSite('~gitbook/search-prewarm')}
|
||||
directSearch={getDirectSearchProps(context)}
|
||||
>
|
||||
{/* Persist an explicit ?theme= override so it survives tab navigation. RND-11571 */}
|
||||
<EmbeddableThemeSync forcedTheme={rememberedTheme} />
|
||||
|
||||
@@ -50,7 +50,9 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
error,
|
||||
fetching,
|
||||
onInputKeyDown,
|
||||
inputHandlers,
|
||||
onResultSelect,
|
||||
onResultHover,
|
||||
query,
|
||||
results,
|
||||
resultsId,
|
||||
@@ -79,6 +81,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
resultsId={resultsId}
|
||||
resultsRef={resultsRef}
|
||||
onResultSelect={onResultSelect}
|
||||
onResultHover={onResultHover}
|
||||
showAsk={showAsk}
|
||||
dataTestId="embed-search"
|
||||
input={
|
||||
@@ -89,6 +92,7 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) {
|
||||
aria-controls={resultsId}
|
||||
onChange={setQuery}
|
||||
onKeyDown={onInputKeyDown}
|
||||
{...inputHandlers}
|
||||
value={searchValue}
|
||||
withAI={withSearchAI}
|
||||
isOpen={true}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { isForeignHandshake } from './channel';
|
||||
|
||||
describe('isForeignHandshake', () => {
|
||||
const parent = {} as MessageEventSource;
|
||||
const other = {} as MessageEventSource;
|
||||
|
||||
it('accepts a handshake from the expected window', () => {
|
||||
expect(isForeignHandshake({ data: { type: 'bidc-connect' }, source: parent }, parent)).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a handshake from another window', () => {
|
||||
expect(isForeignHandshake({ data: { type: 'bidc-connect' }, source: other }, parent)).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores messages that are not handshakes', () => {
|
||||
expect(isForeignHandshake({ data: { type: 'other' }, source: other }, parent)).toBe(false);
|
||||
expect(isForeignHandshake({ data: null, source: other }, parent)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -9,11 +9,33 @@ export function log(...data: any[]) {
|
||||
console.log(...data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a message is a bidc handshake sent by a window other than the expected one.
|
||||
*/
|
||||
export function isForeignHandshake(
|
||||
event: Pick<MessageEvent, 'data' | 'source'>,
|
||||
expectedSource: MessageEventSource
|
||||
): boolean {
|
||||
return event.data?.type === 'bidc-connect' && event.source !== expectedSource;
|
||||
}
|
||||
|
||||
export const getChannel = memoize(() => {
|
||||
if (typeof window === 'undefined' || window.parent === window) {
|
||||
return null;
|
||||
}
|
||||
log('[gitbook] create channel with parent window');
|
||||
|
||||
// bidc accepts a handshake from any window; registered first and in capture so it runs before
|
||||
// bidc's own listener and only the embedding page can open the channel.
|
||||
window.addEventListener(
|
||||
'message',
|
||||
(event) => {
|
||||
if (isForeignHandshake(event, window.parent)) {
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
return createChannel();
|
||||
});
|
||||
|
||||
@@ -55,6 +55,8 @@ export async function Header(props: {
|
||||
'flex-none',
|
||||
'shadow-[0px_1px_0px]',
|
||||
'shadow-tint-12/2',
|
||||
// Box shadows are dropped in forced colors mode, the separator needs a real border.
|
||||
'forced-colors:border-b',
|
||||
|
||||
'bg-tint-base/9',
|
||||
'theme-muted:bg-tint-subtle/9',
|
||||
|
||||
@@ -9,7 +9,7 @@ interface HeaderLinksProps {
|
||||
|
||||
export async function HeaderLinks({ children, style }: HeaderLinksProps) {
|
||||
return (
|
||||
<div
|
||||
<nav
|
||||
className={tcls(
|
||||
'header-links',
|
||||
'@4xl:[&>.button+.button]:-ml-2 z-20 ml-auto flex min-w-9 shrink grow @7xl:grow-0 items-center justify-end @4xl:gap-x-6 gap-x-4',
|
||||
@@ -17,6 +17,6 @@ export async function HeaderLinks({ children, style }: HeaderLinksProps) {
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -193,13 +193,18 @@ export function InsightsProvider(props: InsightsProviderProps) {
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* When the page is unloaded, flush all events.
|
||||
*/
|
||||
// `beforeunload` doesn't fire reliably on mobile, hiding the page is the last dependable signal.
|
||||
React.useEffect(() => {
|
||||
window.addEventListener('beforeunload', flushEventsSync);
|
||||
const flushWhenHidden = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
flushEventsSync();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', flushWhenHidden);
|
||||
window.addEventListener('pagehide', flushEventsSync);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', flushEventsSync);
|
||||
document.removeEventListener('visibilitychange', flushWhenHidden);
|
||||
window.removeEventListener('pagehide', flushEventsSync);
|
||||
};
|
||||
}, [flushEventsSync]);
|
||||
|
||||
|
||||
@@ -73,7 +73,11 @@ export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }
|
||||
'mt-2',
|
||||
'first:mt-0',
|
||||
'mb-0.5',
|
||||
section.depth > 1 && ['ml-3', 'my-0', 'sidebar-list-line:ml-0']
|
||||
section.depth > 1 && [
|
||||
section.depth > 2 ? 'ml-6' : 'ml-3',
|
||||
'my-0',
|
||||
'sidebar-list-line:ml-0',
|
||||
]
|
||||
)}
|
||||
ref={activeId === section.id ? activeItemRef : null}
|
||||
{...(section.tags !== undefined
|
||||
@@ -82,6 +86,7 @@ export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }
|
||||
>
|
||||
<a
|
||||
href={`#${section.id}`}
|
||||
aria-current={activeId === section.id ? 'true' : undefined}
|
||||
data-cover-aware-text
|
||||
className={tcls(
|
||||
'relative',
|
||||
@@ -118,7 +123,9 @@ export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }
|
||||
|
||||
section.depth > 1 && [
|
||||
'subitem',
|
||||
'sidebar-list-line:pl-6',
|
||||
section.depth > 2
|
||||
? 'sidebar-list-line:pl-9'
|
||||
: 'sidebar-list-line:pl-6',
|
||||
'opacity-8',
|
||||
'contrast-more:opacity-11',
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { PageCover } from './PageCover';
|
||||
import { PageFooterNavigation } from './PageFooterNavigation';
|
||||
import { PageHeader } from './PageHeader';
|
||||
import { PreservePageLayout } from './PreservePageLayout';
|
||||
import { MAIN_CONTENT_ID } from '@/components/layout';
|
||||
import { getSpaceLanguage } from '@/intl/server';
|
||||
import { t } from '@/intl/translate';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
@@ -26,7 +27,6 @@ import {
|
||||
hasTopLevelBlock,
|
||||
isNodeEmpty,
|
||||
} from '@/lib/document';
|
||||
import { getLLMsTxtURL, getPageMarkdownURL } from '@/lib/llms-directive';
|
||||
import type { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getPageRSSURL } from '@/routes/rss';
|
||||
@@ -103,6 +103,7 @@ export async function PageBody(props: {
|
||||
/>
|
||||
) : null}
|
||||
<main
|
||||
id={MAIN_CONTENT_ID}
|
||||
// Comments on the whole page target anywhere in it that isn't a block.
|
||||
{...(withCommentAnchors ? { 'data-comment-page': '' } : {})}
|
||||
className={tcls(
|
||||
@@ -120,7 +121,6 @@ export async function PageBody(props: {
|
||||
)}
|
||||
>
|
||||
<PreservePageLayout wideLayout={wideLayout} pageHasToc={pageHasToc} />
|
||||
<LLMsTxtPageDirective context={context} page={page} />
|
||||
{page.cover && page.layout.cover && page.layout.coverSize === 'hero' ? (
|
||||
<PageCover as="hero" page={page} cover={page.cover} context={context} />
|
||||
) : null}
|
||||
@@ -205,14 +205,3 @@ export async function PageBody(props: {
|
||||
</CurrentPageProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function LLMsTxtPageDirective(props: { context: GitBookSiteContext; page: RevisionPageDocument }) {
|
||||
const { context, page } = props;
|
||||
|
||||
return (
|
||||
<div className="sr-only">
|
||||
For the complete documentation index, see <a href={getLLMsTxtURL(context)}>llms.txt</a>.
|
||||
This page is also available as <a href={getPageMarkdownURL(context, page)}>Markdown</a>.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { StaticImageData } from 'next/image';
|
||||
import { assert } from 'ts-essentials';
|
||||
|
||||
import type { RevisionPageDocument, RevisionPageDocumentCover } from '@gitbook/api';
|
||||
import {
|
||||
CustomizationDefaultThemeMode,
|
||||
type RevisionPageDocument,
|
||||
type RevisionPageDocumentCover,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { CONTENT_STYLE } from '../layout';
|
||||
import { getCoverHeight } from './coverHeight';
|
||||
@@ -144,6 +148,11 @@ export async function PageCover(props: {
|
||||
y={cover.yPos}
|
||||
height={height}
|
||||
mask={mask}
|
||||
priorityTheme={
|
||||
context.customization.themes.default === CustomizationDefaultThemeMode.Dark
|
||||
? 'dark'
|
||||
: 'light'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -25,10 +25,14 @@ interface PageCoverImageProps {
|
||||
// Only if the `height` was customized by the user (and thus defined), we use it to set the cover's height and skip the default behaviour of fixed aspect-ratio.
|
||||
height: number | undefined;
|
||||
mask?: 'none' | 'radial';
|
||||
/** Theme most visitors see first, its cover is the LCP candidate. */
|
||||
priorityTheme?: 'light' | 'dark';
|
||||
}
|
||||
|
||||
export function PageCoverImage(props: PageCoverImageProps) {
|
||||
const { imgs, y, height, mask } = props;
|
||||
const { imgs, y, height, mask, priorityTheme = 'light' } = props;
|
||||
// The light cover is never demoted to low: a visitor can still have switched to the light theme.
|
||||
const darkFirst = priorityTheme === 'dark' && Boolean(imgs.dark);
|
||||
const { objectPositionY, isLoading } = useCoverPosition(imgs, y, {
|
||||
height,
|
||||
aspectRatio: PAGE_COVER_SIZE,
|
||||
@@ -48,7 +52,7 @@ export function PageCoverImage(props: PageCoverImageProps) {
|
||||
src={imgs.light.src}
|
||||
srcSet={imgs.light.srcSet}
|
||||
sizes={imgs.light.sizes}
|
||||
fetchPriority="high"
|
||||
fetchPriority={darkFirst ? 'auto' : 'high'}
|
||||
alt="Page cover"
|
||||
className={tcls('w-full', 'object-cover', imgs.dark ? 'dark:hidden' : '')}
|
||||
style={{
|
||||
@@ -69,7 +73,7 @@ export function PageCoverImage(props: PageCoverImageProps) {
|
||||
src={imgs.dark.src}
|
||||
srcSet={imgs.dark.srcSet}
|
||||
sizes={imgs.dark.sizes}
|
||||
fetchPriority="low"
|
||||
fetchPriority={darkFirst ? 'high' : 'low'}
|
||||
alt="Page cover"
|
||||
className={tcls('w-full', 'object-cover', 'dark:inline', 'hidden')}
|
||||
style={{
|
||||
|
||||
@@ -56,7 +56,6 @@ function preloadFont(fontData: FontData) {
|
||||
ReactDOM.preload(url, {
|
||||
as: 'font',
|
||||
crossOrigin: 'anonymous',
|
||||
fetchPriority: 'high',
|
||||
type: format ? `font/${format}` : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
@config '../../../tailwind.config.ts';
|
||||
|
||||
@import "./prose.css";
|
||||
@import "../DocumentView/OpenAPI/method-badge.css";
|
||||
|
||||
/*
|
||||
The default border color has changed to `currentcolor` in Tailwind CSS v4,
|
||||
@@ -33,7 +34,6 @@
|
||||
@utility hide-scrollbar {
|
||||
/* Hide scrollbar by default */
|
||||
scrollbar-color: transparent transparent;
|
||||
transition: scrollbar-color 0.2s ease-in-out;
|
||||
|
||||
&:hover {
|
||||
/* Show scrollbar on hover */
|
||||
@@ -52,21 +52,14 @@
|
||||
rgba(0, 0, 0, 1) 96px,
|
||||
rgba(0, 0, 0, 0)
|
||||
);
|
||||
mask-image: linear-gradient(
|
||||
to bottom,
|
||||
rgba(0, 0, 0, 1) 96px,
|
||||
rgba(0, 0, 0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
@utility linear-mask-util {
|
||||
mask-image: linear-gradient(to bottom, white, white);
|
||||
mask-image: linear-gradient(to bottom, white, white);
|
||||
}
|
||||
|
||||
@utility grid-area-1-1 {
|
||||
grid-area: 1 / 1;
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
|
||||
@utility gutter-stable {
|
||||
@@ -102,41 +95,6 @@
|
||||
border-top-right-radius: 30%;
|
||||
}
|
||||
|
||||
&:before {
|
||||
transform: rotate(-135deg) skewX(-45deg) scale(1.414, 0.707)
|
||||
translate(0, -50%);
|
||||
}
|
||||
&:after {
|
||||
transform: rotate(135deg) skewY(-45deg) scale(0.707, 1.414) translate(50%);
|
||||
}
|
||||
position: relative;
|
||||
background-color: orange;
|
||||
text-align: left;
|
||||
transform: rotate(-60deg) skewX(-30deg) scale(1, 0.866);
|
||||
&:before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
background-color: inherit;
|
||||
}
|
||||
&:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
background-color: inherit;
|
||||
}
|
||||
width: inherit;
|
||||
height: inherit;
|
||||
border-top-right-radius: 30%;
|
||||
&:before {
|
||||
width: inherit;
|
||||
height: inherit;
|
||||
border-top-right-radius: 30%;
|
||||
}
|
||||
&:after {
|
||||
width: inherit;
|
||||
height: inherit;
|
||||
border-top-right-radius: 30%;
|
||||
}
|
||||
|
||||
&:before {
|
||||
transform: rotate(-135deg) skewX(-45deg) scale(1.414, 0.707)
|
||||
translate(0, -50%);
|
||||
@@ -152,21 +110,14 @@
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
word-break: break-word;
|
||||
@supports (overflow-wrap: anywhere) {
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
@utility bg-gradient-primary {
|
||||
@apply bg-linear-to-bl from-primary-4 to-tint-base to-60% bg-fixed;
|
||||
@apply bg-linear-to-bl from-primary-4 to-tint-base to-60% bg-fixed;
|
||||
}
|
||||
|
||||
@utility bg-gradient-tint {
|
||||
@apply bg-linear-to-bl from-tint-4 to-tint-base to-60% bg-fixed;
|
||||
@apply bg-linear-to-bl from-tint-4 to-tint-base to-60% bg-fixed;
|
||||
}
|
||||
|
||||
@utility site-background {
|
||||
@@ -186,24 +137,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
The default border color has changed to `currentcolor` in Tailwind CSS v4,
|
||||
so we've added these compatibility styles to make sure everything still
|
||||
looks the same as it did with Tailwind CSS v3.
|
||||
|
||||
If we ever want to remove these styles, we need to add an explicit border
|
||||
color utility to any element that depends on these defaults.
|
||||
*/
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-gray-200, currentcolor);
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
@apply leading-relaxed;
|
||||
@@ -575,6 +508,18 @@ html.dark .highlight-line.diff-deleted .highlight-line-content::before {
|
||||
@apply text-contrast-cover;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Inline code and highlights sit on their own background, not the cover, so they keep the regular
|
||||
text color. Inherited, the transparent fill of a split element hides their text behind that
|
||||
background. Kept out of the utilities layer so a highlight's own text color still applies.
|
||||
*/
|
||||
@media not (prefers-contrast: more) {
|
||||
[data-over-cover] :is(code, [data-highlight]) {
|
||||
color: var(--cover-text-below);
|
||||
-webkit-text-fill-color: currentcolor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Zoomable images */
|
||||
@@ -680,3 +625,275 @@ html:has(.zoom-modal) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Enter and exit animations, referenced by the `animation` theme in tailwind.config.ts. */
|
||||
@keyframes present {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(1rem) scale(90%);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes scaleIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: rotateX(-10deg) scale(0.9);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes scaleOut {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: rotateX(-10deg) scale(0.95);
|
||||
}
|
||||
}
|
||||
@keyframes blurIn {
|
||||
0% {
|
||||
filter: blur(6px);
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
100% {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurOut {
|
||||
0% {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
100% {
|
||||
filter: blur(6px);
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
}
|
||||
@keyframes blurInDisplay {
|
||||
0% {
|
||||
filter: blur(6px);
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
display: none;
|
||||
}
|
||||
100% {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurOutDisplay {
|
||||
0% {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
to {
|
||||
filter: blur(6px);
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@keyframes enterFromLeft {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-50%);
|
||||
display: none;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
@keyframes enterFromRight {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(50%);
|
||||
display: none;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
@keyframes exitToLeft {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateX(-50%);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@keyframes exitToRight {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateX(50%);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Reduced motion keeps the fades and drops the movement. Redefining the keyframes rather than
|
||||
* disabling the animations keeps their duration, so code waiting on `animationend` is unaffected.
|
||||
* Each variant keeps the identity transform and filter of the full animation's end state: with
|
||||
* `fill-mode: both` they persist, and dropping them would change stacking and text rasterization.
|
||||
*/
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@keyframes present {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes scaleIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes scaleOut {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: rotateX(0deg) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurIn {
|
||||
from {
|
||||
filter: blur(0px);
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
}
|
||||
to {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurOut {
|
||||
from {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
to {
|
||||
filter: blur(0px);
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurInDisplay {
|
||||
from {
|
||||
filter: blur(0px);
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
display: none;
|
||||
}
|
||||
to {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes blurOutDisplay {
|
||||
from {
|
||||
filter: blur(0px);
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
to {
|
||||
filter: blur(0px);
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@keyframes enterFromLeft {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
display: none;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
@keyframes enterFromRight {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
display: none;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
@keyframes exitToLeft {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@keyframes exitToRight {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
display: flex;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateX(0);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* A loader must keep showing activity, so it slows down instead of stopping. */
|
||||
.animate-spin {
|
||||
animation-duration: 3s;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Icon, type IconName } from '@gitbook/icons';
|
||||
|
||||
import { Emoji } from '../primitives/Emoji/Emoji';
|
||||
import { Link } from '../primitives/Link';
|
||||
import type { LocalPageResult } from './useLocalSearchResults';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
* Renders local search results above the main server results.
|
||||
*
|
||||
* Layout:
|
||||
* - While server results are still fetching → 2-column wrapping row (cards fill width)
|
||||
* - Once server results are ready → single horizontal scrollable row (fixed-width cards)
|
||||
*
|
||||
* The card width is CSS-transitioned so the switch between the two layouts animates smoothly.
|
||||
*/
|
||||
export function LocalSearchResults({
|
||||
results,
|
||||
fetching,
|
||||
}: {
|
||||
results: LocalPageResult[];
|
||||
fetching: boolean;
|
||||
}) {
|
||||
if (results.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'py-2',
|
||||
'flex',
|
||||
'flex-row',
|
||||
'gap-2',
|
||||
fetching
|
||||
? 'flex-wrap'
|
||||
: ['overflow-x-auto', '[scrollbar-width:none]', '[&::-webkit-scrollbar]:hidden']
|
||||
)}
|
||||
>
|
||||
{results.map((result) => (
|
||||
<LocalSearchResultCard key={result.id} result={result} fetching={fetching} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LocalSearchResultCard({
|
||||
result,
|
||||
fetching,
|
||||
}: {
|
||||
result: LocalPageResult;
|
||||
fetching: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
href={result.pathname}
|
||||
className={tcls(
|
||||
'group',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-1',
|
||||
'p-3',
|
||||
'rounded-corners:rounded-lg',
|
||||
'circular-corners:rounded-2xl',
|
||||
'text-tint',
|
||||
'bg-tint-subtle',
|
||||
'hover:bg-tint',
|
||||
'hover:text-tint-strong',
|
||||
'transition-colors',
|
||||
'cursor-pointer',
|
||||
fetching ? ['basis-[calc(50%-4px)]', 'min-w-0'] : ['w-40', 'shrink-0']
|
||||
)}
|
||||
>
|
||||
<div className={tcls('flex', 'flex-row', 'items-center', 'gap-1.5', 'min-w-0')}>
|
||||
{result.emoji ? (
|
||||
<span className="size-4 shrink-0 text-tint-subtle">
|
||||
<Emoji code={result.emoji} style="text-base leading-none" />
|
||||
</span>
|
||||
) : result.icon ? (
|
||||
<span className="size-4 shrink-0 text-tint-subtle">
|
||||
<Icon icon={result.icon as IconName} className="size-4" />
|
||||
</span>
|
||||
) : null}
|
||||
<p className="grow truncate font-heading text-sm font-semibold leading-snug text-tint-strong">
|
||||
{result.title}
|
||||
</p>
|
||||
<span className="ml-auto shrink-0 text-tint-subtle">
|
||||
<Icon icon="chevron-right" className="size-3" />
|
||||
</span>
|
||||
</div>
|
||||
{result.description ? (
|
||||
<p className="line-clamp-2 text-xs leading-snug">{result.description}</p>
|
||||
) : null}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
|
||||
import { addRecentSearchQuery } from './recent-queries';
|
||||
import { SearchResultItem } from './SearchResultItem';
|
||||
import { useSearchLink } from './useSearch';
|
||||
@@ -16,10 +15,10 @@ export function SearchAskBar(props: {
|
||||
query: string;
|
||||
assistant: Assistant;
|
||||
active?: boolean;
|
||||
withShortcut?: boolean;
|
||||
onHover?: () => void;
|
||||
onSelect?: () => void;
|
||||
}) {
|
||||
const { query, assistant, active = false, withShortcut = false, onSelect } = props;
|
||||
const { query, assistant, active = false, onHover, onSelect } = props;
|
||||
const language = useLanguage();
|
||||
const { siteSpaceId } = useCurrentContent();
|
||||
const getSearchLinkProps = useSearchLink();
|
||||
@@ -43,18 +42,14 @@ export function SearchAskBar(props: {
|
||||
<SearchResultItem
|
||||
{...linkProps}
|
||||
active={active}
|
||||
onHover={onHover}
|
||||
action={tString(language, 'ask')}
|
||||
leadingIcon={assistant.icon}
|
||||
data-testid="search-ask-question"
|
||||
className="gutter-stable rounded-none! shrink-0 overflow-y-scroll border-t border-tint-subtle pl-6 pr-5"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="line-clamp-1">
|
||||
{t(language, 'ai_chat_ask_query', assistant.label, query)}
|
||||
</div>
|
||||
{withShortcut ? (
|
||||
<KeyboardShortcut className="bg-tint-base" keys={['mod', 'i']} />
|
||||
) : null}
|
||||
<div className="line-clamp-1">
|
||||
{t(language, 'ai_chat_ask_query', assistant.label, query)}
|
||||
</div>
|
||||
</SearchResultItem>
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user