mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-27 12:39:08 +00:00
Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3bd9976524 | |||
| 4c36cf9abd | |||
| c1530706d0 | |||
| d4fa433d92 | |||
| a2170a352a | |||
| e05abafddb | |||
| 7e0e76e58a | |||
| 42ab12a387 | |||
| 2251b36673 | |||
| 8ef76487c2 | |||
| e401c4d4c7 | |||
| fb971aefcc | |||
| b6770d959a | |||
| 8d881d88f6 | |||
| 351c4ffa28 | |||
| bd608e6beb | |||
| 825e245703 | |||
| 828ce66cd9 | |||
| 8e1fdedf83 | |||
| 4a88202274 | |||
| d077e1a6b6 | |||
| 7605d03d8c | |||
| 80026d2724 | |||
| b86ee531d4 | |||
| d939d4c1fd | |||
| 0cc9a03add | |||
| 3805bac462 | |||
| 23b438404c | |||
| 40d14b02d8 | |||
| ef0b6f020a | |||
| d6c0d2dbcd | |||
| 125872769f | |||
| a04513f887 | |||
| 7adbb5068f | |||
| 2b146dbc6a | |||
| ea9420817f |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Add `leaveAgentFeedback` and `leaveUserFeedback` assistant tools, reporting documentation findings to the site's team through the same path as the MCP `sendFeedback` tool, and record an `agent_feedback` insights event on both surfaces.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Include published page descriptions in the page's Markdown output.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix select filters not working on table and cards blocks.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix ContentKit buttons to size to their content instead of stretching to the full container width.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Automatically resolve GitHub and GitLab page links to matching pages in the same published site, including cross-space links imported before their target page was available.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Give the prompt block a default "Copy prompt" action alongside "Open in Claude", "Open in Codex" and "Open in Cursor", and remember the visitor's last pick across every prompt block.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Hide heading and expandable anchor links on pages whose layout disables anchors (landing pages).
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Hide the Intercom launcher while the Assistant panel is open, so it no longer overlaps the message box.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Serve Markdown responses to ChatGPT with a `text/plain` Content-Type for compatibility.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Prefix all cache tags with `ppr:` when rendering under the PPR route, so PPR cache entries are partitioned from the static ones.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Require a GitBook-secret signature on the `x-gbo-*` PPR headers, so a client can't opt itself into the PPR route.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Exchange the PPR revalidation token for a content API token scoped to each PPR component, so the API receives claims it understands and the header and table of contents can be cached across pages.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Preserve the full site preview path and query parameters when redirecting users to log in.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix pages resolving to "not found" when a root URL lookup resolves to a custom homepage, by no longer using the homepage pathname as a prefix for the requested page path.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep current-space search results inside revision previews.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix analytics and adaptive content silently breaking on sites served from a different host than the one configured (apex vs www, domain alias, CDN). The insights and visitor-claims endpoints are now requested relative to the page's own origin instead of the configured host, which a prerendered page cannot know.
|
||||
|
||||
Keep the traffic of GitBook's own preview deployments out of the sites' analytics, now that those requests reach the events endpoint.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Resolve stable page, space and file refs in images, definitions and HTML blocks of published markdown pages, instead of leaking internal `/pages/{id}`, `/spaces/{id}` and `/files/{id}` URLs.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@gitbook/react-contentkit": patch
|
||||
---
|
||||
|
||||
Show a close button on ContentKit modals rendered on published sites.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
"@gitbook/react-contentkit": patch
|
||||
---
|
||||
|
||||
Let ContentKit webframes dispatch the built-in `@ui.*` actions. Actions posted from a webframe were forwarded to the integration as a plain re-render instead of being handled, so `@ui.modal.open`, `@ui.modal.close` and `@ui.url.open` did nothing — most visibly, an integration could not close a modal from inside its own webframe.
|
||||
|
||||
Keep `null` values and class instances such as `Date` intact when resolving dynamic bindings in an action, instead of throwing or flattening them to `{}`.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix section links in search results opening the page without scrolling to the section.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix keyboard focus getting trapped inside the header search popover, allowing Tab/Shift+Tab to exit it as expected.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Use cached Git metadata (via @gitbook/api 0.201.0's `cachedMetadata` param) when rendering Edit on Git actions.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix the tabs "more" dropdown showing when no tab is overflowing, and stop a tab click re-rendering every tab group on the page.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Let a tab keep its content selection across a rename, by honouring an explicit slug set on the tab instead of always deriving one from its title.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Remove the fallback query parameter after successful page navigation without adding a browser history entry.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Restore Edit on Git page actions for Git-synced pages.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Expose the site's MCP tools to browser agents through WebMCP when the MCP page action is enabled.
|
||||
@@ -48,6 +48,7 @@ runs:
|
||||
GITBOOK_ICONS_TOKEN: ${{ inputs.opItem }}/GITBOOK_ICONS_TOKEN
|
||||
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ inputs.opItem }}/NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
|
||||
GITBOOK_SECRET: ${{ inputs.opItem }}/GITBOOK_SECRET
|
||||
GITBOOK_EXCHANGE_TOKEN_URL: ${{ inputs.opItem }}/GITBOOK_EXCHANGE_TOKEN_URL
|
||||
GITBOOK_APP_URL: ${{ inputs.opItem }}/GITBOOK_APP_URL
|
||||
GITBOOK_API_URL: ${{ inputs.opItem }}/GITBOOK_API_URL
|
||||
GITBOOK_API_PUBLIC_URL: ${{ inputs.opItem }}/GITBOOK_API_PUBLIC_URL
|
||||
@@ -69,7 +70,6 @@ runs:
|
||||
GITBOOK_RUNTIME: cloudflare
|
||||
GITBOOK_BLOCK_SEARCH_INDEXATION: ${{ inputs.environment == 'preview' && 'true' || '' }}
|
||||
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: ${{ inputs.environment == 'preview' && 'true' || '' }}
|
||||
GITBOOK_DISABLE_INSIGHTS: ${{ inputs.environment == 'preview' && 'true' || '' }}
|
||||
shell: bash
|
||||
|
||||
- name: Upload the DO worker
|
||||
|
||||
@@ -50,6 +50,7 @@ runs:
|
||||
GITBOOK_ICONS_URL: ${{ inputs.opItem }}/GITBOOK_ICONS_URL
|
||||
GITBOOK_ICONS_TOKEN: ${{ inputs.opItem }}/GITBOOK_ICONS_TOKEN
|
||||
GITBOOK_SECRET: ${{ inputs.opItem }}/GITBOOK_SECRET
|
||||
GITBOOK_EXCHANGE_TOKEN_URL: ${{ inputs.opItem }}/GITBOOK_EXCHANGE_TOKEN_URL
|
||||
GITBOOK_APP_URL: ${{ inputs.opItem }}/GITBOOK_APP_URL
|
||||
GITBOOK_API_URL: ${{ inputs.opItem }}/GITBOOK_API_URL
|
||||
GITBOOK_API_PUBLIC_URL: ${{ inputs.opItem }}/GITBOOK_API_PUBLIC_URL
|
||||
@@ -75,7 +76,6 @@ runs:
|
||||
echo "GITBOOK_RUNTIME=vercel" >> .vercel/.env.${{ inputs.environment }}.local
|
||||
echo "GITBOOK_BLOCK_SEARCH_INDEXATION=true" >> .vercel/.env.${{ inputs.environment }}.local
|
||||
echo "GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE=true" >> .vercel/.env.${{ inputs.environment }}.local
|
||||
echo "GITBOOK_DISABLE_INSIGHTS=true" >> .vercel/.env.${{ inputs.environment }}.local
|
||||
echo "--- .vercel/.env.${{ inputs.environment }}.local after inject ---"
|
||||
cat .vercel/.env.${{ inputs.environment }}.local
|
||||
- name: Build Project Artifacts
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"display_information": {
|
||||
"name": "PR Status",
|
||||
"description": "Updates PR status reactions in engineering"
|
||||
},
|
||||
"features": {
|
||||
"bot_user": {
|
||||
"display_name": "PR Status",
|
||||
"always_online": false
|
||||
}
|
||||
},
|
||||
"oauth_config": {
|
||||
"scopes": {
|
||||
"bot": ["channels:history", "reactions:read", "reactions:write"]
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"org_deploy_enabled": false,
|
||||
"socket_mode_enabled": false,
|
||||
"token_rotation_enabled": false
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
# Slack PR reactions
|
||||
|
||||
[DataDog/slapr](https://github.com/DataDog/slapr) updates reactions on existing PR-link messages in [#engineering](https://gitbook.slack.com/archives/C01NXGWJELS). It runs in GitHub Actions. It does not post messages, approve or merge PRs, or change branch protection.
|
||||
|
||||
## Rollout and ownership
|
||||
|
||||
Owner: Peter White.
|
||||
|
||||
The rollout targets `GitbookIO/gitbook` (GBO), `GitbookIO/gitbook-x` (GBX), and `GitbookIO/integrations`. Each repository contains `.github/workflows/slapr.yml` and this runbook.
|
||||
|
||||
| Configuration | Value |
|
||||
| --- | --- |
|
||||
| Channel | `#engineering`, `C01NXGWJELS` |
|
||||
| App manifest | `.github/slapr-app-manifest.json` |
|
||||
| Slack app ID | `A0C2AGLAD0T` |
|
||||
| Bot user ID | `U0C2AGP16R1`, repository variable `SLAPR_BOT_USER_ID` |
|
||||
| Bot token | Repository Actions secret `SLAPR_SLACK_BOT_TOKEN` |
|
||||
| Action | `DataDog/slapr@1c074e1dfd433f91a679d5113f7f8b956b65d973` |
|
||||
| Approval threshold | Stock default, one approval |
|
||||
| Events | `pull_request_review: submitted`, `pull_request: closed` |
|
||||
|
||||
## Install and configure
|
||||
|
||||
1. In [Slack app management](https://api.slack.com/apps), create the **PR Status** app from `.github/slapr-app-manifest.json` in the GitBook workspace. Obtain workspace approval if required, then install it. The bot requests Slapr's documented `channels:history`, `reactions:read`, and `reactions:write` scopes. `#engineering` is public, so `groups:history` is unnecessary. No review map is configured, so `channels:read` is unnecessary.
|
||||
2. Invite **PR Status** only to `#engineering`. Keep it dedicated to Slapr: stock Slapr removes obsolete reactions belonging to this bot on a matched message. It leaves other users' reactions alone.
|
||||
3. Record the app ID and bot user ID above. The bot profile's member ID or Slack `auth.test` response's `user_id` is the required bot user ID, not the app ID or bot ID.
|
||||
4. Store the bot OAuth token as `SLAPR_SLACK_BOT_TOKEN` in each of the three repositories' Actions secrets. Use the GitHub secret UI or `gh secret set SLAPR_SLACK_BOT_TOKEN --repo GitbookIO/<repository>` and its hidden prompt. Never paste the token into a command argument, chat, workflow, or committed file. Alternatively, an organization secret must use selected-repository visibility limited to these three repositories.
|
||||
5. Set Actions variable `SLAPR_BOT_USER_ID` in each repository to that bot's user ID. The token and user ID must belong to the same installation. Use `gh variable set SLAPR_BOT_USER_ID --repo GitbookIO/<repository> --body '<user-id>'` or the GitHub UI.
|
||||
6. Merge the workflows through normal review, then run the live checks below. Repository maintainers handle reviews and merges; Slapr has only read access to GitHub contents and pull requests.
|
||||
|
||||
GBX runs this workflow on `blacksmith-2vcpu-ubuntu-2404`. GBO and integrations use `ubuntu-latest`, matching their existing workflows.
|
||||
|
||||
The workflow hardcodes the engineering channel and does not check out PR code. It uses the stock event triggers and leaves the approval threshold unset. There are no listeners, schedules, review maps, custom discovery, or additional services.
|
||||
|
||||
## Reactions
|
||||
|
||||
Slapr's status selection stays unchanged. Missing custom emoji names are mapped through the action's supported inputs to existing equivalents. Workspace lookup on 2026-09-17 confirmed `pr-approved` and `merged`; the other mappings are standard Slack emojis.
|
||||
|
||||
| Stock status | Reaction |
|
||||
| --- | --- |
|
||||
| Review started | `:eyes:` |
|
||||
| Partially approved | `:next_track_button:` |
|
||||
| Approved | `:pr-approved:` |
|
||||
| Changes requested | `:construction:` |
|
||||
| Merged | `:merged:` |
|
||||
| Closed without merging | `:no_entry_sign:` |
|
||||
| Comment-only review | `:speech_balloon:` |
|
||||
|
||||
The partially-approved reaction is configured but cannot occur with the default threshold of one approval. It becomes relevant only if that threshold is raised.
|
||||
|
||||
On approval, expect review-started and approved reactions. On merge, stock Slapr removes review-started and adds merged; it can retain approved alongside merged. Approval and merging have distinct reactions. Other stock review-state behavior is accepted.
|
||||
|
||||
## Live acceptance test
|
||||
|
||||
For each repository after credentials are configured and the workflow is on the default branch:
|
||||
|
||||
1. Open a fresh same-repository test PR through normal review. Post its full `https://github.com/GitbookIO/<repository>/pull/<number>` link as a new top-level message in `#engineering` before the review event.
|
||||
2. Have another contributor approve it. Open the **Slack PR reactions** Actions run and verify that the matched message has the bot's `pr-approved` reaction.
|
||||
3. Have an authorized maintainer merge it. Verify the closed-event run succeeds and the same message has the bot's `merged` reaction. No new Slack status message should appear.
|
||||
4. Record the PR URL, Slack message permalink, approval/merge workflow run URLs, date, and result below. A green workflow alone does not prove the message was found or reacted to.
|
||||
|
||||
| Repository | PR and Slack message | Approval run/result | Merge run/result |
|
||||
| --- | --- | --- | --- |
|
||||
| GitbookIO/gitbook | Pending | Not tested | Not tested |
|
||||
| GitbookIO/gitbook-x | Pending | Not tested | Not tested |
|
||||
| GitbookIO/integrations | Pending | Not tested | Not tested |
|
||||
|
||||
Only the first matching message in Slapr's recent-history response is updated. Older messages, thread replies, duplicate posts, fork PRs, and links posted after the event are outside this rollout's acceptance criteria. Slapr does not paginate history or reconcile missed events.
|
||||
|
||||
## Troubleshoot and disable
|
||||
|
||||
- No workflow run: confirm the workflow is merged, Actions permits the pinned action, and the event was a submitted review or PR closure. These are the only configured triggers.
|
||||
- `No message found requesting review`: confirm the full PR link was posted as a recent top-level message in `#engineering` before the event. This is a successful no-op in stock Slapr.
|
||||
- `not_in_channel` or `channel_not_found`: check the app installation, channel ID, and bot membership in `#engineering`.
|
||||
- `missing_scope`: compare the installed bot scopes with the manifest and reinstall after changes.
|
||||
- `invalid_auth` or `account_inactive`: replace the repository secrets with the current bot token. If the bot identity changed, update `SLAPR_BOT_USER_ID` too.
|
||||
- `invalid_name`: check the emoji mappings still exist. If a custom emoji was removed, map that input to another existing emoji, keeping approval and merged distinct.
|
||||
- Old reactions remain or removal fails: confirm `SLAPR_BOT_USER_ID` is the member ID for the token's bot.
|
||||
- GitHub permission errors: keep `contents: read` and `pull-requests: read`; do not introduce a PAT, write permissions, or `pull_request_target` to cover forks. Fork and Dependabot secret restrictions are accepted limitations.
|
||||
- Rate limits or transient API failures: inspect the Actions log and retry the failed run after the limit resets. There is no scheduled reconciliation.
|
||||
|
||||
Disable one repository with `gh workflow disable slapr.yml --repo GitbookIO/<repository>`, or disable **Slack PR reactions** in its Actions UI. Repeat for all three to stop the integration. Revoke the Slack app token to stop its access immediately, remove its repository secrets, and remove the bot from `#engineering` when retiring it. Existing reactions remain.
|
||||
|
||||
## Pin review
|
||||
|
||||
On 2026-09-17, the pinned action definition, Dockerfile, entry point, dependency declarations, GitHub reads, Slack history lookup and reaction writes were inspected. Without `review-map`, the action targets only the supplied channel. It reads PR/review state and adds/removes reactions; it does not post Slack messages or write to GitHub.
|
||||
|
||||
The action SHA pins Slapr's source. Its upstream Dockerfile still uses the mutable `python:3.14` image and installs dependencies, including `pyyaml>=5.0`, at build time. This rollout keeps stock Slapr unchanged. Review upstream source and dependency changes before updating the SHA in all three repositories.
|
||||
@@ -1,30 +0,0 @@
|
||||
name: Slack PR reactions
|
||||
|
||||
on:
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
pull_request:
|
||||
types: [closed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
run_slapr:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Update PR reactions in engineering
|
||||
uses: DataDog/slapr@1c074e1dfd433f91a679d5113f7f8b956b65d973
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
slack-api-token: ${{ secrets.SLAPR_SLACK_BOT_TOKEN }}
|
||||
slack-channel-id: C01NXGWJELS
|
||||
bot-user-id: ${{ vars.SLAPR_BOT_USER_ID }}
|
||||
emoji-review-started: eyes
|
||||
emoji-partially-approved: next_track_button
|
||||
emoji-approved: pr-approved
|
||||
emoji-changes-requested: construction
|
||||
emoji-merged: merged
|
||||
emoji-closed: no_entry_sign
|
||||
emoji-commented: speech_balloon
|
||||
@@ -29,6 +29,3 @@ yarn-error.log*
|
||||
|
||||
# Bun pack artifacts
|
||||
packages/*/*.tgz
|
||||
|
||||
# Playwright MCP artifacts
|
||||
.playwright-mcp/
|
||||
|
||||
@@ -24,6 +24,35 @@ Examples:
|
||||
- `http://localhost:3000/url/gitbook.com/docs`
|
||||
- `http://localhost:3000/url/open-source.gitbook.io/midjourney`
|
||||
|
||||
### PPR routes
|
||||
|
||||
PPR requests are normally resolved upstream and arrive with a large set of `x-gbo-*` headers, so they
|
||||
can't be reproduced by hitting the dev server directly. `bun run dev:ppr` (from `packages/gitbook`)
|
||||
starts a dev-only proxy on port 3001 that resolves the URL, injects those headers and signs them.
|
||||
The app rejects an unsigned set, so `GITBOOK_SECRET` must be set in `.env.local` (any value works
|
||||
locally, as long as both processes read the same one).
|
||||
|
||||
The app also exchanges the PPR token for one scoped to each component, against
|
||||
`GITBOOK_EXCHANGE_TOKEN_URL`. That endpoint only accepts a revalidation token, which the
|
||||
published-URLs lookup never returns, so the proxy mints one with `PPR_DEV_API_TOKEN_SECRET` — a
|
||||
local-only stand-in for the API token secret the cache worker holds in production. It must match the
|
||||
secret the target `/token` endpoint verifies with, so local PPR needs a local gitbook-x sites stack.
|
||||
The secret is read only by the proxy script: never add it to `src/lib/env`, `next.config.mjs` or a
|
||||
deploy workflow.
|
||||
|
||||
```
|
||||
GITBOOK_SECRET=<any value>
|
||||
GITBOOK_EXCHANGE_TOKEN_URL=http://localhost:8788/token
|
||||
PPR_DEV_API_TOKEN_SECRET=<local gitbook-x functionsConfig.api.tokenSecret>
|
||||
```
|
||||
|
||||
```
|
||||
http://localhost:3001/url/<published-gitbook-url>
|
||||
```
|
||||
|
||||
Responses carry `x-gitbook-route-type: ppr` when the PPR route was used. Hot reload doesn't work
|
||||
through the proxy (its websocket can't be forwarded), so keep using port 3000 while iterating.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
|
||||
@@ -275,7 +275,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "catalog:",
|
||||
"bun-types": "catalog:",
|
||||
"react": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
@@ -355,7 +354,7 @@
|
||||
},
|
||||
"catalog": {
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.202.0",
|
||||
"@gitbook/api": "0.199.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
@@ -727,7 +726,7 @@
|
||||
|
||||
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
|
||||
|
||||
"@gitbook/api": ["@gitbook/api@0.202.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-qhrjEQbNNmCljR0AgP79+BsVh9yelh9TIBg9X3TyYx5a3lJwDiT3sw1ND9DFQSxGHp8hH5w+20KJHn/IDpTbaw=="],
|
||||
"@gitbook/api": ["@gitbook/api@0.199.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-yLxkSTXlGk7jbtThV2vpnTfqZTq6yLgMJt6jhDGqOmP0LsYAVYYtg8NPf2tXp37aF46m3Z0D908wfSQyu374cg=="],
|
||||
|
||||
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
|
||||
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.202.0",
|
||||
"@gitbook/api": "0.199.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Page, expect } from '@playwright/test';
|
||||
import { type Page, expect, test } from '@playwright/test';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import {
|
||||
@@ -10,12 +10,12 @@ import {
|
||||
CustomizationDepth,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationIconsStyle,
|
||||
CustomizationPageActionType,
|
||||
CustomizationSidebarListStyle,
|
||||
SiteSocialAccountPlatform,
|
||||
} from '@gitbook/api';
|
||||
import type { GitBookStandalone } from '@gitbook/embed';
|
||||
|
||||
import { signPPRRequestHeaders } from '../src/lib/ppr';
|
||||
import { getGitBookPreviewURL, getSiteAPIToken } from '../tests/utils';
|
||||
import {
|
||||
type Test,
|
||||
@@ -159,7 +159,7 @@ const searchTestCases: Test[] = [
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Keyboard focus exits to the next page control',
|
||||
name: 'Search - Keyboard focus stays within search',
|
||||
url: getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.Search,
|
||||
@@ -180,16 +180,13 @@ const searchTestCases: Test[] = [
|
||||
)
|
||||
.filter({ visible: true })
|
||||
.last();
|
||||
const nextPageControl = page.getByTestId('table-of-contents').getByRole('link').first();
|
||||
await expect(finalPopupControl).toBeVisible();
|
||||
await expect(nextPageControl).toBeVisible();
|
||||
await finalPopupControl.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
await expect(searchPopup).toBeHidden();
|
||||
await expect(nextPageControl).toBeFocused();
|
||||
await expect(searchInput).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(searchInput).toBeFocused();
|
||||
await expect(finalPopupControl).toBeFocused();
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -249,43 +246,6 @@ const searchTestCases: Test[] = [
|
||||
await expect(page.getByTestId('search-results')).toBeVisible();
|
||||
},
|
||||
},
|
||||
{
|
||||
// RND-12844: the popover's focus manager re-focused the closing popup and
|
||||
// scrolled the page back to the top right after landing on the section.
|
||||
name: 'Search - Section result scrolls to the section',
|
||||
url: getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.None,
|
||||
},
|
||||
}),
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForCookiesDialog(page);
|
||||
const searchInput = page.getByTestId('search-input');
|
||||
await searchInput.focus();
|
||||
// Type like a visitor: `fill()` doesn't trigger the remote search.
|
||||
await searchInput.pressSequentially('tasks');
|
||||
|
||||
const sectionResult = page.locator(
|
||||
'[data-testid="search-page-result"][href$="/blocks/lists#tasks"]'
|
||||
);
|
||||
// Section results come from the remote index, which can be slow to answer.
|
||||
await expect(sectionResult).toBeVisible({ timeout: 30_000 });
|
||||
await sectionResult.click();
|
||||
await page.waitForURL(/\/blocks\/lists#tasks$/);
|
||||
|
||||
// The regression scrolled back to the top shortly after landing, so let
|
||||
// that happen before asserting.
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// The heading is parked under the header, within its scroll margin.
|
||||
const top = await page
|
||||
.locator('#tasks')
|
||||
.evaluate((heading) => heading.getBoundingClientRect().top);
|
||||
expect(top).toBeGreaterThanOrEqual(0);
|
||||
expect(top).toBeLessThanOrEqual(150);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Ask - AI Mode: Assistant - Complete flow',
|
||||
url: getCustomizationURL({
|
||||
@@ -387,6 +347,49 @@ const searchTestCases: Test[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const PPR_TEST_SITE_URL = 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/';
|
||||
|
||||
/**
|
||||
* The `x-gbo-*` set GBO resolves upstream. `sign` mirrors what GBO does with `GITBOOK_SECRET`;
|
||||
* without it the app must fall back to resolving the URL itself.
|
||||
*/
|
||||
async function getPPRHeaders(options: { sign: string | undefined }) {
|
||||
const data = await getSiteAPIToken(PPR_TEST_SITE_URL);
|
||||
|
||||
if (!data.revision) {
|
||||
throw new Error('PPR test site did not resolve to content with a revision');
|
||||
}
|
||||
|
||||
const headers = new Headers({
|
||||
'x-gbo-site': data.site,
|
||||
'x-gbo-site-section': data.siteSection ?? '',
|
||||
'x-gbo-site-space': data.siteSpace,
|
||||
'x-gbo-space': data.space,
|
||||
'x-gbo-site-base-path': data.siteBasePath,
|
||||
'x-gbo-base-path': data.basePath,
|
||||
'x-gbo-pathname': data.pathname || '/',
|
||||
'x-gbo-organization': data.organization,
|
||||
'x-gbo-share-key': data.shareKey ?? '',
|
||||
'x-gbo-complete': String(data.complete),
|
||||
'x-gbo-context-id': data.contextId ?? '',
|
||||
'x-gbo-canonical-url': data.canonicalUrl,
|
||||
'x-gbo-preview': data.preview === undefined ? '' : String(data.preview),
|
||||
'x-gbo-revision': data.revision ?? '',
|
||||
'x-gbo-change-request': data.changeRequest ?? '',
|
||||
'x-gbo-api-token': data.apiToken,
|
||||
'x-gbo-revalidation-id': 'ppr-e2e-revalidation',
|
||||
'x-gbo-default-site-section': data.siteSection ?? '',
|
||||
'x-gbo-default-site-space': data.siteSpace,
|
||||
'x-gbo-default-space': data.space,
|
||||
});
|
||||
|
||||
if (options.sign) {
|
||||
await signPPRRequestHeaders(headers, options.sign);
|
||||
}
|
||||
|
||||
return Object.fromEntries(headers.entries());
|
||||
}
|
||||
|
||||
const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'GitBook Site (Single Variant)',
|
||||
@@ -397,6 +400,37 @@ const testCases: TestsCase[] = [
|
||||
url: '',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'PPR route renders the site shell',
|
||||
url: '',
|
||||
headers: () => getPPRHeaders({ sign: process.env.GITBOOK_SECRET }),
|
||||
screenshot: false,
|
||||
run: async (page, response) => {
|
||||
// The deployment signs with its own `GITBOOK_SECRET`; without it here the
|
||||
// headers can only be tested for rejection (see the test below).
|
||||
test.skip(
|
||||
!process.env.GITBOOK_SECRET,
|
||||
'GITBOOK_SECRET is required to sign PPR headers'
|
||||
);
|
||||
expect(response?.headers()['x-gitbook-route-type']).toBe('ppr');
|
||||
await expect(page.locator('header[data-gb-site-header]')).toBeVisible();
|
||||
await expect(page.getByTestId('table-of-contents')).toBeVisible();
|
||||
await expect(page.locator('main')).toBeVisible();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'PPR route ignores an unsigned header set',
|
||||
url: '',
|
||||
headers: () => getPPRHeaders({ sign: undefined }),
|
||||
screenshot: false,
|
||||
run: async (page, response) => {
|
||||
// Anyone can send these headers, so an unsigned set must never take the PPR
|
||||
// path: it skips URL resolution and visitor-auth, and picks the cache key.
|
||||
expect(response?.headers()['x-gitbook-route-type']).not.toBe('ppr');
|
||||
await expect(page.locator('header[data-gb-site-header]')).toBeVisible();
|
||||
await expect(page.locator('main')).toBeVisible();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'No variants dropdown',
|
||||
url: '',
|
||||
@@ -554,24 +588,6 @@ const testCases: TestsCase[] = [
|
||||
name: 'GitBook Site (Navigation when switching variant)',
|
||||
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Strip fallback after loading a page without adding history',
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const previousURL = page.url();
|
||||
const targetURL = new URL(previousURL);
|
||||
targetURL.searchParams.set('fallback', 'true');
|
||||
targetURL.searchParams.set('ref', 'variant');
|
||||
targetURL.hash = 'pets';
|
||||
await page.goto(targetURL.toString());
|
||||
targetURL.searchParams.delete('fallback');
|
||||
await expect(page).toHaveURL(targetURL.toString());
|
||||
await page.goBack();
|
||||
await expect(page).toHaveURL(previousURL);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (Public)',
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
@@ -594,11 +610,8 @@ const testCases: TestsCase[] = [
|
||||
.click();
|
||||
|
||||
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
|
||||
await page.waitForURL(
|
||||
(url) =>
|
||||
url.pathname.includes(
|
||||
'api-multi-versions/2.0/reference/api-reference/pets'
|
||||
) && !url.searchParams.has('fallback')
|
||||
await page.waitForURL((url) =>
|
||||
url.pathname.includes('api-multi-versions/2.0/reference/api-reference/pets')
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -1634,70 +1647,6 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Edit on Git page actions',
|
||||
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/yjs/',
|
||||
tests: [
|
||||
{
|
||||
name: 'With Edit on Git as the default action',
|
||||
url: getCustomizationURL({
|
||||
pageActions: {
|
||||
items: [CustomizationPageActionType.Git],
|
||||
},
|
||||
}),
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
await expect(
|
||||
page.getByRole('link', { name: 'Edit', exact: true })
|
||||
).toHaveAttribute(
|
||||
'href',
|
||||
'https://github.com/taranvohra/yjs-docs/tree/main/README.md'
|
||||
);
|
||||
},
|
||||
screenshot: false,
|
||||
},
|
||||
{
|
||||
name: 'With Edit on Git in the dropdown',
|
||||
url: getCustomizationURL({
|
||||
pageActions: {
|
||||
items: [
|
||||
CustomizationPageActionType.Markdown,
|
||||
CustomizationPageActionType.Git,
|
||||
],
|
||||
},
|
||||
}),
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
await page.getByRole('button', { name: 'More' }).click();
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('menuitem', { name: 'Edit on GitHub' })
|
||||
).toHaveAttribute(
|
||||
'href',
|
||||
'https://github.com/taranvohra/yjs-docs/tree/main/README.md'
|
||||
);
|
||||
},
|
||||
screenshot: false,
|
||||
},
|
||||
{
|
||||
name: 'Without Edit on Git',
|
||||
url: getCustomizationURL({
|
||||
pageActions: {
|
||||
items: [CustomizationPageActionType.Markdown],
|
||||
},
|
||||
}),
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
await page.getByRole('button', { name: 'More' }).click();
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('menuitem', { name: 'Edit on GitHub' })
|
||||
).toHaveCount(0);
|
||||
},
|
||||
screenshot: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Page actions',
|
||||
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
@@ -1750,6 +1699,7 @@ const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'Without previewed ads',
|
||||
url: 'text-page?ads_preview=1',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
import { type Page, expect, test } from '@playwright/test';
|
||||
|
||||
// Import the specific module (not the package barrel) so this stays free of the `@/` path alias,
|
||||
// which Playwright's loader doesn't resolve — same reason as `select.spec.ts`.
|
||||
import { resolveOverflowingItems } from '../src/components/hooks/listOverflow';
|
||||
|
||||
/**
|
||||
* Behaviour tests for the tab bar's overflow rule (`useListOverflow`), which decides which tabs move
|
||||
* into the "more" dropdown. Rects are measured in a real browser so the geometry is genuine — the
|
||||
* layout below mirrors the tab bar in `DynamicTabs`: a non-wrapping flex row of `shrink-0` items,
|
||||
* clipped by `overflow: hidden`, measured with the dropdown rendered ahead of the tabs.
|
||||
*
|
||||
* The regression these guard is a dropdown appearing when nothing actually overflowed: measuring
|
||||
* with the dropdown present consumes `MENU` pixels, so a bar whose tabs total just under the
|
||||
* container would hand its last tab to a menu it never needed.
|
||||
*/
|
||||
|
||||
/** Width of the ellipsis button, matching the `px-3.5` + `size-4` icon of the real one. */
|
||||
const MENU = 44;
|
||||
|
||||
interface Row {
|
||||
/** Container width in px. */
|
||||
container: number;
|
||||
/** Tab widths in px, in order. */
|
||||
tabs: number[];
|
||||
/** Whether the dropdown is reserving space ahead of the tabs, as during a measure pass. */
|
||||
withMenu?: boolean;
|
||||
/** Hide an ancestor, so the row measures with no box at all. */
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay the row out in the browser and run the real rule over the rects it produces.
|
||||
* Returns the ids reported as overflowing, or `null` when the measurement carried no information.
|
||||
*/
|
||||
async function measure(page: Page, row: Row): Promise<string[] | null> {
|
||||
const { container, tabs, withMenu = true, hidden = false } = row;
|
||||
|
||||
const items = tabs
|
||||
.map((w, i) => `<div class="item" id="tab-${i}" style="width:${w}px">${i}</div>`)
|
||||
.join('');
|
||||
const menu = withMenu ? `<div class="item" style="width:${MENU}px">…</div>` : '';
|
||||
|
||||
await page.setContent(
|
||||
`<!doctype html><html><head><style>
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; }
|
||||
.pane { ${hidden ? 'display: none;' : ''} }
|
||||
.bar {
|
||||
width: ${container}px;
|
||||
display: inline-flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
.bar::after { content: ""; flex: 1; }
|
||||
.item { flex-shrink: 0; max-width: 100%; }
|
||||
</style></head><body>
|
||||
<div class="pane"><div class="bar" id="bar">${menu}${items}</div></div>
|
||||
</body></html>`
|
||||
);
|
||||
|
||||
const measured = await page.evaluate(() => {
|
||||
const bar = document.getElementById('bar');
|
||||
if (!bar) {
|
||||
throw new Error('missing bar');
|
||||
}
|
||||
const rect = bar.getBoundingClientRect();
|
||||
return {
|
||||
container: { left: rect.left, right: rect.right, width: rect.width },
|
||||
items: [...bar.querySelectorAll<HTMLElement>('.item[id]')].map((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return { id: el.id, rect: { left: r.left, right: r.right } };
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const result = resolveOverflowingItems(measured.container, measured.items);
|
||||
return result ? [...result].sort() : null;
|
||||
}
|
||||
|
||||
test.describe('tab overflow rule', () => {
|
||||
test('reports nothing when every tab fits with room to spare', async ({ page }) => {
|
||||
// 3 x 100 = 300 of 600, so even with the menu reserved there is slack.
|
||||
expect(await measure(page, { container: 600, tabs: [100, 100, 100] })).toEqual([]);
|
||||
});
|
||||
|
||||
test('reports nothing when the tabs fit exactly', async ({ page }) => {
|
||||
expect(await measure(page, { container: 300, tabs: [100, 100, 100] })).toEqual([]);
|
||||
});
|
||||
|
||||
test('reports nothing when only the reserved menu made the row overflow', async ({ page }) => {
|
||||
// The regression: tabs total 300 and the container is 320, so they fit — but measuring
|
||||
// reserves 44 for the menu, which used to push the last tab out and show a needless
|
||||
// dropdown. Every width in `container - MENU < 300 <= container` must stay empty.
|
||||
for (const container of [300, 305, 320, 330, 343]) {
|
||||
expect(
|
||||
await measure(page, { container, tabs: [100, 100, 100] }),
|
||||
`container ${container}px`
|
||||
).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test('reports the tabs that genuinely do not fit alongside the menu', async ({ page }) => {
|
||||
// 300 of tabs into 290: the row really does overflow, so the menu is warranted and the
|
||||
// remaining tabs must fit beside it (100 + 100 + 44 = 244 <= 290).
|
||||
expect(await measure(page, { container: 290, tabs: [100, 100, 100] })).toEqual(['tab-2']);
|
||||
});
|
||||
|
||||
test('gives up as many tabs as the width demands', async ({ page }) => {
|
||||
expect(await measure(page, { container: 190, tabs: [100, 100, 100] })).toEqual([
|
||||
'tab-1',
|
||||
'tab-2',
|
||||
]);
|
||||
expect(await measure(page, { container: 150, tabs: [100, 100, 100] })).toEqual([
|
||||
'tab-1',
|
||||
'tab-2',
|
||||
]);
|
||||
});
|
||||
|
||||
test('moves every tab into the menu once not even the first fits beside it', async ({
|
||||
page,
|
||||
}) => {
|
||||
// 100 + 44 > 120, so no tab can share the row with the menu. Everything goes in, leaving a
|
||||
// bar that is only the menu — deliberately, since the menu is then the sole route to any
|
||||
// tab. Forcing the first tab to stay would push the menu past the clipped edge and strand
|
||||
// the rest.
|
||||
expect(await measure(page, { container: 120, tabs: [100, 100, 100] })).toEqual([
|
||||
'tab-0',
|
||||
'tab-1',
|
||||
'tab-2',
|
||||
]);
|
||||
});
|
||||
|
||||
test('keeps a single tab that fills the bar rather than hiding it behind a menu', async ({
|
||||
page,
|
||||
}) => {
|
||||
// `max-width: 100%` truncates it to the container, so it fits — a lone tab should never be
|
||||
// the only thing in the dropdown.
|
||||
expect(await measure(page, { container: 200, tabs: [400] })).toEqual([]);
|
||||
});
|
||||
|
||||
test('cuts a nested bar earlier, since its pane padding narrows it', async ({ page }) => {
|
||||
// A nested tab bar sits inside a `p-4` pane, so it has 32px less to work with. At 330 the
|
||||
// outer bar keeps all three tabs; the nested one at 330 - 32 cannot.
|
||||
expect(await measure(page, { container: 330, tabs: [100, 100, 100] })).toEqual([]);
|
||||
expect(await measure(page, { container: 330 - 32, tabs: [100, 100, 100] })).toEqual([
|
||||
'tab-2',
|
||||
]);
|
||||
});
|
||||
|
||||
test('progressively fills the menu as a long list is squeezed', async ({ page }) => {
|
||||
const tabs = Array.from({ length: 12 }, () => 100);
|
||||
let previous = -1;
|
||||
for (const container of [1300, 1200, 1000, 800, 600, 400, 200]) {
|
||||
const overflowing = await measure(page, { container, tabs });
|
||||
expect(overflowing, `container ${container}px`).not.toBeNull();
|
||||
const hidden = overflowing?.length ?? 0;
|
||||
// Never loses a tab, and never un-hides one as the space shrinks.
|
||||
expect(hidden, `container ${container}px`).toBeGreaterThanOrEqual(previous);
|
||||
expect(hidden, `container ${container}px`).toBeLessThanOrEqual(tabs.length);
|
||||
previous = hidden;
|
||||
}
|
||||
// Widest fits everything; at 200 only the first tab still fits beside the menu.
|
||||
expect(await measure(page, { container: 1300, tabs })).toEqual([]);
|
||||
expect((await measure(page, { container: 200, tabs }))?.length).toBe(11);
|
||||
});
|
||||
|
||||
test('reports nothing measurable while an ancestor is hidden', async ({ page }) => {
|
||||
// A bar behind an inactive tab has no box, so every rect is zero. That says nothing about
|
||||
// what fits, and must not be mistaken for "everything overflows".
|
||||
expect(
|
||||
await measure(page, { container: 200, tabs: [100, 100, 100], hidden: true })
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test('reports nothing measurable for an empty list', async ({ page }) => {
|
||||
expect(await measure(page, { container: 600, tabs: [] })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,10 @@ export interface Test {
|
||||
*/
|
||||
url: string | (() => string | Promise<string>);
|
||||
cookies?: Parameters<BrowserContext['addCookies']>[0];
|
||||
/** Headers to send with the main document request. */
|
||||
headers?:
|
||||
| Record<string, string>
|
||||
| (() => Record<string, string> | Promise<Record<string, string>>);
|
||||
/**
|
||||
* Test to run
|
||||
*/
|
||||
@@ -279,6 +283,11 @@ export function runTestCases(testCases: TestsCase[]) {
|
||||
} catch {}
|
||||
});
|
||||
|
||||
const headers =
|
||||
typeof testEntry.headers === 'function'
|
||||
? await testEntry.headers()
|
||||
: testEntry.headers;
|
||||
|
||||
// Set the header to disable the Vercel toolbar
|
||||
// But only on the main document as it'd cause CORS issues on other resources
|
||||
await page.route('**/*', async (route, request) => {
|
||||
@@ -287,6 +296,7 @@ export function runTestCases(testCases: TestsCase[]) {
|
||||
headers: {
|
||||
...request.headers(),
|
||||
'x-vercel-skip-toolbar': '1',
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -465,11 +475,7 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
|
||||
socialAccounts: [],
|
||||
};
|
||||
|
||||
const encoded = rison.encode_object(
|
||||
deepMerge(DEFAULT_CUSTOMIZATION, partial, {
|
||||
arrayMerge: (_target, source) => source,
|
||||
})
|
||||
);
|
||||
const encoded = rison.encode_object(deepMerge(DEFAULT_CUSTOMIZATION, partial));
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('customization', encoded);
|
||||
|
||||
@@ -88,13 +88,13 @@ const nextConfig = {
|
||||
GITBOOK_API_TOKEN: process.env.GITBOOK_API_TOKEN,
|
||||
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
|
||||
GITBOOK_SECRET: process.env.GITBOOK_SECRET,
|
||||
GITBOOK_EXCHANGE_TOKEN_URL: process.env.GITBOOK_EXCHANGE_TOKEN_URL,
|
||||
GITBOOK_IMAGE_RESIZE_SIGNING_KEY: process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
||||
GITBOOK_IMAGE_RESIZE_MODE: process.env.GITBOOK_IMAGE_RESIZE_MODE,
|
||||
GITBOOK_FONTS_URL: process.env.GITBOOK_FONTS_URL,
|
||||
GITBOOK_RUNTIME: process.env.GITBOOK_RUNTIME,
|
||||
GITBOOK_BLOCK_SEARCH_INDEXATION: process.env.GITBOOK_BLOCK_SEARCH_INDEXATION,
|
||||
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: process.env.GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE,
|
||||
GITBOOK_DISABLE_INSIGHTS: process.env.GITBOOK_DISABLE_INSIGHTS,
|
||||
|
||||
// Next.js envs
|
||||
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
|
||||
|
||||
@@ -122,6 +122,7 @@
|
||||
"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",
|
||||
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
|
||||
"dev:ppr": "env-cmd --silent -f ../../.env.local bun scripts/ppr-dev-proxy.ts",
|
||||
"build": "bun run generate:assets && next build --webpack",
|
||||
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
|
||||
"check:css-browser-compatibility": "bun scripts/check-css-browser-compatibility.ts",
|
||||
@@ -132,7 +133,7 @@
|
||||
"dev:cf:middleware": "wrangler dev --port 8771 --inspector-port 9230 --env dev --config ./openNext/customWorkers/middlewareWrangler.jsonc",
|
||||
"dev:cf:server": "wrangler dev --port 8772 --env dev --config ./openNext/customWorkers/defaultWrangler.jsonc",
|
||||
"profile:cf:memory": "bun run build:cloudflare && bun ./scripts/profile-opennext-memory.ts",
|
||||
"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": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.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",
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* Dev-only proxy that stands in for the upstream layer resolving PPR requests.
|
||||
*
|
||||
* It resolves the incoming URL against the published-URLs API and forwards the request to the local
|
||||
* app with the complete `x-gbo-*` header set, so PPR routes can be exercised locally:
|
||||
*
|
||||
* bun dev # app on :3000
|
||||
* bun run dev:ppr # this proxy on :3001
|
||||
* open http://localhost:3001/url/gitbook.com/docs
|
||||
*
|
||||
* Never deploy this. It trusts its input and caches API tokens in memory.
|
||||
*/
|
||||
import type { PublishedSiteContent, PublishedSiteContentLookup, Space } from '@gitbook/api';
|
||||
|
||||
import { PPRRequestHeaders, signPPRRequestHeaders } from '../src/lib/ppr';
|
||||
|
||||
const PORT = Number(process.env.PPR_PROXY_PORT || 3001);
|
||||
const UPSTREAM = process.env.PPR_UPSTREAM || 'http://localhost:3000';
|
||||
const API_URL = process.env.GITBOOK_API_URL || 'https://api.gitbook.com/cache';
|
||||
const API_TOKEN = process.env.GITBOOK_API_TOKEN;
|
||||
const REVALIDATION_ID = process.env.PPR_REVALIDATION_ID;
|
||||
const LOOKUP_TTL = Number(process.env.PPR_LOOKUP_TTL || 60) * 1000;
|
||||
|
||||
const URL_PREFIX = '/url/';
|
||||
const PASSTHROUGH_PREFIXES = ['/_next/', '/~gitbook/static/'];
|
||||
|
||||
function log(message: string) {
|
||||
// biome-ignore lint/suspicious/noConsole: this is a CLI script
|
||||
console.log(`[ppr-proxy] ${message}`);
|
||||
}
|
||||
|
||||
// The app rejects an unsigned header set, so `bun dev` must run with the same secret.
|
||||
function requireSecret(): string {
|
||||
const secret = process.env.GITBOOK_SECRET;
|
||||
if (!secret) {
|
||||
log(
|
||||
'GITBOOK_SECRET is not set: the app rejects unsigned PPR headers. Add it to .env.local.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
// This proxy mints API tokens, so it must never be reachable outside a developer machine.
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
log('This proxy mints API tokens and must never run in production.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const SECRET = requireSecret();
|
||||
|
||||
// The app always exchanges the PPR token, and the exchange endpoint only accepts a revalidation
|
||||
// token, which the published-URLs lookup never returns: we have to mint one ourselves.
|
||||
function requireAPITokenSecret(): string {
|
||||
const secret = process.env.PPR_DEV_API_TOKEN_SECRET;
|
||||
if (!secret) {
|
||||
log(
|
||||
'PPR_DEV_API_TOKEN_SECRET is not set: the token exchange rejects the lookup token. Add it to .env.local.'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
const API_TOKEN_SECRET = requireAPITokenSecret();
|
||||
|
||||
const cache = new Map<string, { value: unknown; expiresAt: number }>();
|
||||
const inflight = new Map<string, Promise<unknown>>();
|
||||
|
||||
/**
|
||||
* Cache and dedupe an API call. A single page load fans out into many requests for the same site,
|
||||
* and the site root lookup is shared by every page of a site.
|
||||
*/
|
||||
function cached<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
|
||||
const entry = cache.get(key);
|
||||
if (entry && entry.expiresAt > Date.now()) {
|
||||
return Promise.resolve(entry.value as T);
|
||||
}
|
||||
|
||||
const pending = inflight.get(key);
|
||||
if (pending) {
|
||||
return pending as Promise<T>;
|
||||
}
|
||||
|
||||
const promise = fetcher()
|
||||
.then((value) => {
|
||||
cache.set(key, { value, expiresAt: Date.now() + LOOKUP_TTL });
|
||||
return value;
|
||||
})
|
||||
.finally(() => inflight.delete(key));
|
||||
|
||||
inflight.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function api<T>(path: string, init: RequestInit, token = API_TOKEN): Promise<T> {
|
||||
const response = await fetch(`${API_URL}/v1${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(token ? { authorization: `Bearer ${token}` } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`${path}: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
function lookupPublishedURL(url: string): Promise<PublishedSiteContentLookup> {
|
||||
return cached(`url:${url}`, () =>
|
||||
api<PublishedSiteContentLookup>('/urls/published', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ url }),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The lookup only carries a revision for preview URLs, so for a regular published URL we read the
|
||||
* space's active revision using the short-lived token the lookup returned.
|
||||
*/
|
||||
function getActiveRevision(content: PublishedSiteContent): Promise<string> {
|
||||
return cached(`revision:${content.space}`, async () => {
|
||||
const space = await api<Space>(`/spaces/${content.space}`, {}, content.apiToken);
|
||||
return space.revision;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The `x-gbo-default-*` headers describe the site's default variant, which is the cache key of the
|
||||
* shared header. Resolving the site root is the only way to get it from the published-URLs API.
|
||||
*/
|
||||
async function getDefaults(content: PublishedSiteContent) {
|
||||
const fallback = {
|
||||
siteSection: content.siteSection,
|
||||
siteSpace: content.siteSpace,
|
||||
space: content.space,
|
||||
};
|
||||
|
||||
try {
|
||||
const rootURL = `https://${new URL(content.canonicalUrl).host}${content.siteBasePath}`;
|
||||
const root = await lookupPublishedURL(rootURL);
|
||||
if ('redirect' in root) {
|
||||
return fallback;
|
||||
}
|
||||
return { siteSection: root.siteSection, siteSpace: root.siteSpace, space: root.space };
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the lookup's content token into the revalidation token the cache worker would send: the same
|
||||
* payload, with the claims split into the per-scope buckets the exchange endpoint narrows down.
|
||||
* Reusing the payload keeps `spaces`, `iat` and `exp` valid.
|
||||
*/
|
||||
async function mintRevalidationToken(apiToken: string): Promise<string> {
|
||||
const { claims: _claims, ...payload } = decodeJWTPayload(apiToken);
|
||||
|
||||
const result = signJWT(
|
||||
{
|
||||
...payload,
|
||||
target: 'content',
|
||||
// Empty buckets: local dev has no revalidation run to compute adaptive claims from.
|
||||
siteClaims: {},
|
||||
revisionClaims: {},
|
||||
pageClaims: {},
|
||||
},
|
||||
API_TOKEN_SECRET
|
||||
);
|
||||
console.log('minted revalidation token', await result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function decodeJWTPayload(token: string): Record<string, unknown> {
|
||||
const payload = token.split('.')[1];
|
||||
if (!payload) {
|
||||
throw new Error('API token is not a JWT');
|
||||
}
|
||||
return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
}
|
||||
|
||||
async function signJWT(payload: Record<string, unknown>, secret: string): Promise<string> {
|
||||
const signingInput = `${base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))}.${base64url(
|
||||
JSON.stringify(payload)
|
||||
)}`;
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
);
|
||||
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput));
|
||||
|
||||
return `${signingInput}.${base64url(Buffer.from(signature))}`;
|
||||
}
|
||||
|
||||
function base64url(value: string | Buffer): string {
|
||||
return (typeof value === 'string' ? Buffer.from(value, 'utf8') : value).toString('base64url');
|
||||
}
|
||||
|
||||
async function setPPRHeaders(
|
||||
headers: Headers,
|
||||
content: PublishedSiteContent & { revision: string },
|
||||
defaults: { siteSection: string | undefined; siteSpace: string; space: string },
|
||||
secret: string
|
||||
) {
|
||||
headers.set(PPRRequestHeaders.Site, content.site);
|
||||
headers.set(PPRRequestHeaders.SiteSection, content.siteSection ?? '');
|
||||
headers.set(PPRRequestHeaders.SiteSpace, content.siteSpace);
|
||||
headers.set(PPRRequestHeaders.Space, content.space);
|
||||
headers.set(PPRRequestHeaders.SiteBasePath, content.siteBasePath);
|
||||
headers.set(PPRRequestHeaders.BasePath, content.basePath);
|
||||
// An empty pathname is rejected; the root page is `/`.
|
||||
headers.set(PPRRequestHeaders.Pathname, content.pathname || '/');
|
||||
headers.set(PPRRequestHeaders.Organization, content.organization);
|
||||
headers.set(PPRRequestHeaders.ShareKey, content.shareKey ?? '');
|
||||
headers.set(PPRRequestHeaders.Complete, String(content.complete));
|
||||
headers.set(PPRRequestHeaders.ContextID, content.contextId ?? '');
|
||||
headers.set(PPRRequestHeaders.CanonicalURL, content.canonicalUrl);
|
||||
// Anything other than '', 'true' or 'false' rejects the whole PPR request.
|
||||
headers.set(
|
||||
PPRRequestHeaders.Preview,
|
||||
content.preview === undefined ? '' : String(content.preview)
|
||||
);
|
||||
headers.set(PPRRequestHeaders.Revision, content.revision);
|
||||
headers.set(PPRRequestHeaders.ChangeRequest, content.changeRequest ?? '');
|
||||
headers.set(PPRRequestHeaders.APIToken, await mintRevalidationToken(content.apiToken));
|
||||
headers.set(PPRRequestHeaders.RevalidationID, REVALIDATION_ID || content.revision);
|
||||
// Unlike the other optional headers this one is checked with `has()`, so it must be sent even
|
||||
// when the site has no sections.
|
||||
headers.set(PPRRequestHeaders.DefaultSiteSection, defaults.siteSection ?? '');
|
||||
headers.set(PPRRequestHeaders.DefaultSiteSpace, defaults.siteSpace);
|
||||
headers.set(PPRRequestHeaders.DefaultSpace, defaults.space);
|
||||
// Signed last: the signature covers every other PPR header.
|
||||
await signPPRRequestHeaders(headers, secret);
|
||||
}
|
||||
|
||||
/**
|
||||
* `fetch` decodes the response body, so the upstream framing headers no longer describe what we are
|
||||
* about to send. Forwarding `content-encoding: gzip` with plain bytes renders as a blank page.
|
||||
*/
|
||||
const DECODED_RESPONSE_HEADERS = ['content-encoding', 'content-length', 'transfer-encoding'];
|
||||
|
||||
async function forward(request: Request, url: URL, headers: Headers): Promise<Response> {
|
||||
const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
|
||||
const upstreamURL = new URL(url.pathname + url.search, UPSTREAM);
|
||||
|
||||
// `/url/` mode is only enabled for requests on the app's own host (`GITBOOK_URL`), so the proxy
|
||||
// host must not leak through: the app would treat it as a custom domain and 404.
|
||||
headers.set('host', upstreamURL.host);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(upstreamURL, {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: hasBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
...(hasBody ? { duplex: 'half' } : {}),
|
||||
} as RequestInit);
|
||||
} catch (error) {
|
||||
log(`${request.method} ${url.pathname} → upstream unreachable at ${UPSTREAM}`);
|
||||
return new Response(`Upstream ${UPSTREAM} unreachable: ${error}`, { status: 502 });
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers(response.headers);
|
||||
for (const name of DECODED_RESPONSE_HEADERS) {
|
||||
responseHeaders.delete(name);
|
||||
}
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
async function handle(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
// `fetch` can't perform an upgrade, so hot reload only works when hitting the app directly.
|
||||
if (request.headers.get('upgrade') === 'websocket') {
|
||||
return new Response('Websocket upgrades are not proxied', { status: 501 });
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
|
||||
// Never let a client inject its own PPR headers.
|
||||
for (const name of Object.values(PPRRequestHeaders)) {
|
||||
headers.delete(name);
|
||||
}
|
||||
|
||||
if (
|
||||
!url.pathname.startsWith(URL_PREFIX) ||
|
||||
PASSTHROUGH_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))
|
||||
) {
|
||||
return forward(request, url, headers);
|
||||
}
|
||||
|
||||
const publishedURL = `https://${url.pathname.slice(URL_PREFIX.length)}${url.search}`;
|
||||
|
||||
const skip = (reason: string) => {
|
||||
log(`${request.method} ${url.pathname} → no PPR: ${reason}`);
|
||||
return forward(request, url, headers);
|
||||
};
|
||||
|
||||
let content: PublishedSiteContent;
|
||||
try {
|
||||
const result = await lookupPublishedURL(publishedURL);
|
||||
if ('redirect' in result) {
|
||||
return skip(`lookup redirected to ${result.redirect}`);
|
||||
}
|
||||
content = result;
|
||||
} catch (error) {
|
||||
return skip(`lookup failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
let revision: string;
|
||||
let defaults: Awaited<ReturnType<typeof getDefaults>>;
|
||||
try {
|
||||
[revision, defaults] = await Promise.all([
|
||||
content.revision ?? getActiveRevision(content),
|
||||
getDefaults(content),
|
||||
]);
|
||||
} catch (error) {
|
||||
return skip(`no revision: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
await setPPRHeaders(headers, { ...content, revision }, defaults, SECRET);
|
||||
|
||||
log(
|
||||
`${request.method} ${url.pathname} → site=${content.site} space=${content.space} revision=${revision}`
|
||||
);
|
||||
|
||||
return forward(request, url, headers);
|
||||
}
|
||||
|
||||
Bun.serve({
|
||||
port: PORT,
|
||||
idleTimeout: 60,
|
||||
fetch: handle,
|
||||
});
|
||||
|
||||
log(`listening on http://localhost:${PORT} → ${UPSTREAM}`);
|
||||
log(`try http://localhost:${PORT}/url/gitbook.com/docs`);
|
||||
+77
-45
@@ -2,21 +2,10 @@ import { createMcpHandler } from 'mcp-handler';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import {
|
||||
AgentFeedbackSource,
|
||||
CustomizationPageActionType,
|
||||
SiteInsightsDisplayContext,
|
||||
} from '@gitbook/api';
|
||||
import { CustomizationPageActionType, SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
|
||||
import { type RouteLayoutParams, getDynamicSiteContext } from '@/app/utils';
|
||||
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
|
||||
import {
|
||||
AGENT_FEEDBACK_GOAL_MAX_LENGTH,
|
||||
AGENT_FEEDBACK_MAX_LENGTH,
|
||||
agentFeedbackDescriptions,
|
||||
parseAgentFeedbackPageURL,
|
||||
} from '@/lib/agentFeedback';
|
||||
import { submitAgentFeedback } from '@/lib/agentFeedback/server';
|
||||
import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask';
|
||||
import { getExposableError, throwIfDataError } from '@/lib/data';
|
||||
import { fromPageMarkdown, getMarkdownForPageInSpace, toPageMarkdown } from '@/lib/markdownPage';
|
||||
@@ -364,14 +353,26 @@ export async function handleMcpRequest(
|
||||
content: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(AGENT_FEEDBACK_MAX_LENGTH)
|
||||
.describe(agentFeedbackDescriptions.finding),
|
||||
.max(2048)
|
||||
.describe(
|
||||
'Explain the issue in full, as if writing to a documentation maintainer who never saw this conversation. Describe what is wrong, where on the page it appears (quote the exact sentence or section title when possible), what the user was trying to do, and, when relevant, what the correct or expected information should be. Write a few clear, specific sentences in English. Never include personal or confidential information from the conversation. Up to 2048 characters.'
|
||||
),
|
||||
pageUrl: z
|
||||
.string()
|
||||
.describe(agentFeedbackDescriptions.pageURL(siteUrl))
|
||||
.describe(
|
||||
`The full URL of the page the issue is about (e.g. ${siteUrl}/getting-started), so the finding is linked to the exact page.`
|
||||
)
|
||||
.transform((value, ctx) => {
|
||||
const url = parseAgentFeedbackPageURL(value, siteUrl);
|
||||
if (!url) {
|
||||
const candidate = URL.canParse(value)
|
||||
? new URL(value)
|
||||
: URL.canParse(value, siteUrl)
|
||||
? new URL(value, siteUrl)
|
||||
: null;
|
||||
|
||||
if (
|
||||
!candidate ||
|
||||
(candidate.protocol !== 'https:' && candidate.protocol !== 'http:')
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `"${value}" is not a valid URL on this site. Expected a full URL like ${siteUrl}/getting-started`,
|
||||
@@ -379,13 +380,14 @@ export async function handleMcpRequest(
|
||||
return z.NEVER;
|
||||
}
|
||||
|
||||
return url;
|
||||
return candidate.toString();
|
||||
}),
|
||||
goal: z
|
||||
.string()
|
||||
.max(AGENT_FEEDBACK_GOAL_MAX_LENGTH)
|
||||
.optional()
|
||||
.describe(agentFeedbackDescriptions.goal),
|
||||
.describe(
|
||||
'The broader end goal you were ultimately trying to accomplish (as/on behalf of the user) when you hit this issue. Gives the team the context you were working towards. Optional.'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Send feedback',
|
||||
@@ -396,36 +398,66 @@ export async function handleMcpRequest(
|
||||
},
|
||||
async ({ content, pageUrl, goal }) => {
|
||||
try {
|
||||
const result = await submitAgentFeedback(context, {
|
||||
feedback: content,
|
||||
goal,
|
||||
page: pageUrl,
|
||||
source: AgentFeedbackSource.Mcp,
|
||||
});
|
||||
|
||||
if (!result.submitted) {
|
||||
const match = findSiteSpaceByUrl(context.structure, pageUrl);
|
||||
if (!match) {
|
||||
return {
|
||||
content: [{ type: 'text', text: result.error }],
|
||||
content: [{ type: 'text', text: `Page not found: "${pageUrl}"` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
trackMcpEvent({
|
||||
organizationId: context.organizationId,
|
||||
siteId: site.id,
|
||||
events: [
|
||||
{
|
||||
type: 'agent_feedback',
|
||||
location: {
|
||||
displayContext: SiteInsightsDisplayContext.Mcp,
|
||||
page: result.page.pageId,
|
||||
space: result.page.spaceId,
|
||||
revision: result.page.revisionId,
|
||||
},
|
||||
},
|
||||
],
|
||||
request,
|
||||
});
|
||||
const revision = await throwIfDataError(
|
||||
dataFetcher.getRevision({
|
||||
spaceId: match.siteSpace.space.id,
|
||||
revisionId: match.siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
|
||||
const resolved = resolveSiteSpacePagePath(
|
||||
match.siteSpace,
|
||||
revision.pages,
|
||||
match.pagePath
|
||||
);
|
||||
if (!resolved) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Page not found: "${pageUrl}"` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
const trimmedGoal = goal?.trim() || undefined;
|
||||
|
||||
//!! DISABLED FOR NOW: We'll add this back in when we have a way to track agent feedback.
|
||||
// trackMcpEvent({
|
||||
// organizationId: context.organizationId,
|
||||
// siteId: site.id,
|
||||
// events: [
|
||||
// {
|
||||
// type: 'agent_feedback',
|
||||
// feedback: { content, category },
|
||||
// location: {
|
||||
// displayContext: SiteInsightsDisplayContext.Mcp,
|
||||
// page: resolved.page.id,
|
||||
// space: match.siteSpace.space.id,
|
||||
// revision: match.siteSpace.space.revision,
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// request,
|
||||
// });
|
||||
|
||||
const apiClient = await dataFetcher.api();
|
||||
await apiClient.orgs.submitSiteAgentFeedback(
|
||||
context.organizationId,
|
||||
site.id,
|
||||
{
|
||||
feedback: content,
|
||||
url: pageUrl,
|
||||
spaceId: match.siteSpace.space.id,
|
||||
pageId: resolved.page.id,
|
||||
...(trimmedGoal ? { goal: trimmedGoal } : {}),
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Feedback recorded. Thank you.' }],
|
||||
|
||||
+3
-149
@@ -1,12 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type {
|
||||
RevisionPage,
|
||||
RevisionPageDocument,
|
||||
SearchPageResult,
|
||||
SearchSpaceResult,
|
||||
SiteSpace,
|
||||
} from '@gitbook/api';
|
||||
import type { SearchPageResult, SearchSpaceResult, SiteSpace } from '@gitbook/api';
|
||||
|
||||
import { orderSearchResultGroups } from './orderSearchResults';
|
||||
import { createLinker } from '@/lib/links';
|
||||
@@ -22,13 +16,6 @@ const linker = createLinker({
|
||||
spaceBasePath: '/',
|
||||
});
|
||||
|
||||
const revisionLinker = createLinker({
|
||||
protocol: 'https:',
|
||||
host: 'docs.runway.team',
|
||||
siteBasePath: '/handbook/',
|
||||
spaceBasePath: '/handbook/api/~/revisions/revision_preview/',
|
||||
});
|
||||
|
||||
const spaceItem: SearchSpaceResult = {
|
||||
type: 'space',
|
||||
id: 'space_runway',
|
||||
@@ -76,33 +63,6 @@ function transformPage(pageItem: SearchPageResult, asEmbeddable = false) {
|
||||
pageItem,
|
||||
spaceItem,
|
||||
siteSpace,
|
||||
})!;
|
||||
}
|
||||
|
||||
function createRevisionPage(id: string, path: string): RevisionPageDocument {
|
||||
return {
|
||||
id,
|
||||
type: 'document',
|
||||
path,
|
||||
pages: [],
|
||||
} as RevisionPageDocument;
|
||||
}
|
||||
|
||||
function createRevisionPages(pagePath: string): RevisionPage[] {
|
||||
return [
|
||||
createRevisionPage('page_home', 'home'),
|
||||
createRevisionPage('page_api_reference', pagePath),
|
||||
];
|
||||
}
|
||||
|
||||
function transformRevisionPage(pageItem: SearchPageResult, revisionPages: RevisionPage[]) {
|
||||
return transformSitePageResult({
|
||||
asEmbeddable: false,
|
||||
linker: revisionLinker,
|
||||
pageItem,
|
||||
spaceItem,
|
||||
siteSpace,
|
||||
revisionPages,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -123,92 +83,12 @@ describe('transformSitePageResult', () => {
|
||||
expect(transformPage(createPageResult({ path: destination }), true).href).toBe(destination);
|
||||
});
|
||||
|
||||
it('keeps published search results on their published destination', () => {
|
||||
it('resolves a relative page path through the published site URL', () => {
|
||||
const result = transformPage(createPageResult({ path: 'guides/getting-started' }));
|
||||
|
||||
expect(result.href).toBe('/guides/getting-started');
|
||||
});
|
||||
|
||||
it('keeps a current-space page result inside the revision being previewed', () => {
|
||||
const result = transformRevisionPage(
|
||||
createPageResult({ path: 'guides/getting-started' }),
|
||||
createRevisionPages('guides/getting-started')
|
||||
);
|
||||
|
||||
expect(result?.href).toBe(
|
||||
'/handbook/api/~/revisions/revision_preview/guides/getting-started'
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the current revision path when a page moved after the indexed revision', () => {
|
||||
const result = transformRevisionPage(
|
||||
createPageResult({ path: 'guides/getting-started' }),
|
||||
createRevisionPages('start/quickstart')
|
||||
);
|
||||
|
||||
expect(result?.href).toBe('/handbook/api/~/revisions/revision_preview/start/quickstart');
|
||||
});
|
||||
|
||||
it('keeps a section result and its anchor inside the current revision', () => {
|
||||
const result = transformRevisionPage(
|
||||
createPageResult({
|
||||
path: 'guides/getting-started',
|
||||
sections: [
|
||||
{
|
||||
id: 'section_authentication',
|
||||
title: 'Authentication',
|
||||
body: 'Synthetic section excerpt',
|
||||
path: 'guides/getting-started#authentication',
|
||||
score: 10,
|
||||
resultType: 'section',
|
||||
urls: {
|
||||
app: 'https://app.gitbook.com/o/example/s/example',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
createRevisionPages('guides/getting-started')
|
||||
);
|
||||
|
||||
expect(result?.bestSection?.href).toBe(
|
||||
'/handbook/api/~/revisions/revision_preview/guides/getting-started#authentication'
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to the revision page root when a section anchor cannot be safely retained', () => {
|
||||
const result = transformRevisionPage(
|
||||
createPageResult({
|
||||
path: 'guides/getting-started',
|
||||
sections: [
|
||||
{
|
||||
id: 'section_authentication',
|
||||
title: 'Authentication',
|
||||
body: 'Synthetic section excerpt',
|
||||
path: 'another-page#authentication',
|
||||
score: 10,
|
||||
resultType: 'section',
|
||||
urls: {
|
||||
app: 'https://app.gitbook.com/o/example/s/example',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
createRevisionPages('start/quickstart')
|
||||
);
|
||||
|
||||
expect(result?.bestSection?.href).toBe(
|
||||
'/handbook/api/~/revisions/revision_preview/start/quickstart'
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes a main-index result that does not exist in the current revision', () => {
|
||||
const result = transformRevisionPage(createPageResult({ path: 'guides/getting-started' }), [
|
||||
createRevisionPage('page_home', 'home'),
|
||||
]);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps embeddable GitBook page links in the embeddable route', () => {
|
||||
const result = transformPage(createPageResult({ path: 'guides/getting-started' }), true);
|
||||
|
||||
@@ -246,33 +126,7 @@ describe('transformSitePageResult', () => {
|
||||
spaceItem,
|
||||
});
|
||||
|
||||
expect(result?.href).toBe('/guides/getting-started');
|
||||
});
|
||||
|
||||
it('keeps cross-space results on their published destination during a revision preview', () => {
|
||||
const otherSpaceItem = { ...spaceItem, id: 'space_sdk', title: 'SDK' };
|
||||
const otherSiteSpace = {
|
||||
...siteSpace,
|
||||
id: 'site_space_sdk',
|
||||
path: 'sdk',
|
||||
space: {
|
||||
...siteSpace.space,
|
||||
id: otherSpaceItem.id,
|
||||
title: otherSpaceItem.title,
|
||||
},
|
||||
urls: {
|
||||
published: 'https://docs.runway.team/handbook/sdk/',
|
||||
},
|
||||
} as SiteSpace;
|
||||
const result = transformSitePageResult({
|
||||
asEmbeddable: false,
|
||||
linker: revisionLinker,
|
||||
pageItem: createPageResult({ path: 'guides/getting-started' }),
|
||||
spaceItem: otherSpaceItem,
|
||||
siteSpace: otherSiteSpace,
|
||||
});
|
||||
|
||||
expect(result?.href).toBe('/handbook/sdk/guides/getting-started');
|
||||
expect(result.href).toBe('/guides/getting-started');
|
||||
});
|
||||
|
||||
it('preserves ranks, scores, and result ordering', () => {
|
||||
|
||||
+12
-34
@@ -9,7 +9,7 @@ import { throwIfDataError } from '@/lib/data';
|
||||
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
|
||||
import { transformSitePageResult } from '@/lib/search';
|
||||
import { getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
|
||||
import { findSiteSpaceBy } from '@/lib/sites';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
|
||||
@@ -22,7 +22,7 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
|
||||
const [searchResults, { structure }, revision] = await Promise.all([
|
||||
const [searchResults, { structure }] = await Promise.all([
|
||||
throwIfDataError(
|
||||
context.dataFetcher.searchSiteContent({
|
||||
organizationId: siteURLData.organization,
|
||||
@@ -38,24 +38,8 @@ export async function POST(request: NextRequest) {
|
||||
siteShareKey: siteURLData.shareKey,
|
||||
})
|
||||
),
|
||||
siteURLData.revision
|
||||
? throwIfDataError(
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId: siteURLData.space,
|
||||
revisionId: siteURLData.revision,
|
||||
})
|
||||
)
|
||||
: Promise.resolve(undefined),
|
||||
]);
|
||||
|
||||
const currentSiteSpace = revision
|
||||
? findSiteSpaceBy(structure, (siteSpace) => siteSpace.id === siteURLData.siteSpace)
|
||||
: null;
|
||||
const revisionLinker =
|
||||
revision && currentSiteSpace
|
||||
? getLinkerForSiteSpace(context.linker, currentSiteSpace.siteSpace, revision.pages)
|
||||
: context.linker;
|
||||
|
||||
const results = orderSearchResultGroups<OrderedComputedResult>(
|
||||
searchResults.map((resultItem) => {
|
||||
if (resultItem.type === 'record') {
|
||||
@@ -71,31 +55,25 @@ export async function POST(request: NextRequest) {
|
||||
return { type: 'context' as const, results: [result] };
|
||||
}
|
||||
|
||||
const isCurrentRevisionSpace = Boolean(revision && resultItem.id === siteURLData.space);
|
||||
const found =
|
||||
isCurrentRevisionSpace && currentSiteSpace
|
||||
? currentSiteSpace
|
||||
: findSiteSpaceBy(
|
||||
structure,
|
||||
(siteSpace) => siteSpace.space.id === resultItem.id
|
||||
);
|
||||
const found = findSiteSpaceBy(
|
||||
structure,
|
||||
(siteSpace) => siteSpace.space.id === resultItem.id
|
||||
);
|
||||
|
||||
return {
|
||||
type: 'pages' as const,
|
||||
results: resultItem.pages.flatMap((pageItem) => {
|
||||
const result = transformSitePageResult({
|
||||
results: resultItem.pages.map((pageItem) => ({
|
||||
rank: pageItem.rank,
|
||||
result: transformSitePageResult({
|
||||
asEmbeddable: Boolean(asEmbeddable),
|
||||
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
|
||||
linker: context.linker,
|
||||
pageItem,
|
||||
spaceItem: resultItem,
|
||||
siteSpace: found?.siteSpace,
|
||||
siteSection: found?.siteSection ?? undefined,
|
||||
siteSectionGroup: found?.siteSectionGroup ?? undefined,
|
||||
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
|
||||
});
|
||||
|
||||
return result ? [{ rank: pageItem.rank, result }] : [];
|
||||
}),
|
||||
}),
|
||||
})),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { SitePageNotFound } from '@/components/SitePage';
|
||||
|
||||
export default async function NotFound() {
|
||||
return <SitePageNotFound />;
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
|
||||
import { type PPRRouteParams, getPPRPageRouteParams, getPagePathFromParams } from '@/app/utils';
|
||||
import {
|
||||
PPRPageBody,
|
||||
cachedGenerateSitePageMetadata,
|
||||
cachedGenerateSitePageViewport,
|
||||
} from '@/components/SitePage/PPRSitePage';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
type PageProps = {
|
||||
params: Promise<PPRRouteParams>;
|
||||
};
|
||||
|
||||
export default async function Page(props: PageProps) {
|
||||
const params = await props.params;
|
||||
const pathname = getPagePathFromParams(params);
|
||||
|
||||
return <PPRPageBody params={await getPPRPageRouteParams(params)} pathname={pathname} />;
|
||||
}
|
||||
|
||||
export async function generateViewport(props: PageProps): Promise<Viewport> {
|
||||
const params = await props.params;
|
||||
return cachedGenerateSitePageViewport(await getPPRPageRouteParams(params));
|
||||
}
|
||||
|
||||
export async function generateMetadata(props: PageProps): Promise<Metadata> {
|
||||
const params = await props.params;
|
||||
return cachedGenerateSitePageMetadata(await getPPRPageRouteParams(params));
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import type React from 'react';
|
||||
|
||||
import {
|
||||
type PPRRouteLayoutParams,
|
||||
getPPRHeaderRouteParams,
|
||||
getPPRPageRouteParams,
|
||||
getPPRSiteRouteParams,
|
||||
getPPRStaticSiteContext,
|
||||
getPPRStaticSiteScopeContext,
|
||||
getPPRTableOfContentsRouteParams,
|
||||
getPPRVisitorAuthClaims,
|
||||
} from '@/app/utils';
|
||||
import { CustomizationRootLayout } from '@/components/RootLayout';
|
||||
import {
|
||||
SiteLayout,
|
||||
generateSiteLayoutMetadata,
|
||||
generateSiteLayoutViewport,
|
||||
} from '@/components/SiteLayout';
|
||||
import {
|
||||
PPRAdminToolbar,
|
||||
PPRAnnouncement,
|
||||
PPRFooter,
|
||||
PPRHeader,
|
||||
PPRRevisionIconsProvider,
|
||||
PPRTableOfContents,
|
||||
} from '@/components/SitePage/PPRSitePage';
|
||||
import { shouldTrackEvents } from '@/lib/tracking';
|
||||
|
||||
interface SitePPRLayoutProps {
|
||||
params: Promise<PPRRouteLayoutParams>;
|
||||
}
|
||||
|
||||
export default async function SitePPRLayout({
|
||||
params,
|
||||
children,
|
||||
}: React.PropsWithChildren<SitePPRLayoutProps>) {
|
||||
const routeParams = await params;
|
||||
const [siteParams, headerParams, tableOfContentsParams, visitorAuthClaims] = await Promise.all([
|
||||
getPPRSiteRouteParams(routeParams),
|
||||
getPPRHeaderRouteParams(routeParams),
|
||||
getPPRTableOfContentsRouteParams(routeParams),
|
||||
// Each component holds a token narrowed to one scope, so the client claims need their union.
|
||||
getPPRVisitorAuthClaims(routeParams),
|
||||
]);
|
||||
// The layout is rendered on every request, so it only resolves site-level data — under the
|
||||
// scope of the header, whose site fetch it then shares. Everything below the site level is
|
||||
// delegated to the cached components in the slots.
|
||||
const { context } = await getPPRStaticSiteScopeContext(siteParams, 'header');
|
||||
const withTracking = shouldTrackEvents();
|
||||
|
||||
return (
|
||||
<CustomizationRootLayout
|
||||
htmlClassName="sheet-open:gutter-stable"
|
||||
bodyClassName="site-background"
|
||||
context={context}
|
||||
>
|
||||
<PPRRevisionIconsProvider params={tableOfContentsParams}>
|
||||
<SiteLayout
|
||||
context={context}
|
||||
withTracking={withTracking}
|
||||
visitorAuthClaims={visitorAuthClaims}
|
||||
slots={{
|
||||
announcement: <PPRAnnouncement params={tableOfContentsParams} />,
|
||||
header: <PPRHeader params={headerParams} />,
|
||||
tableOfContents: <PPRTableOfContents params={tableOfContentsParams} />,
|
||||
footer: <PPRFooter params={tableOfContentsParams} />,
|
||||
adminToolbar: <PPRAdminToolbar params={tableOfContentsParams} />,
|
||||
}}
|
||||
// The header and table of contents are cached across pages, so the selection they
|
||||
// were rendered with belongs to another page and has to be resolved on the client.
|
||||
clientNavigationSelection
|
||||
>
|
||||
{children}
|
||||
</SiteLayout>
|
||||
</PPRRevisionIconsProvider>
|
||||
</CustomizationRootLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateViewport({ params }: SitePPRLayoutProps) {
|
||||
const { context } = await getPPRStaticSiteContext(
|
||||
await getPPRPageRouteParams(await params),
|
||||
'header'
|
||||
);
|
||||
return generateSiteLayoutViewport(context);
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: SitePPRLayoutProps) {
|
||||
const { context } = await getPPRStaticSiteContext(
|
||||
await getPPRPageRouteParams(await params),
|
||||
'header'
|
||||
);
|
||||
return generateSiteLayoutMetadata(context);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, mock } from 'bun:test';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import rison from 'rison';
|
||||
|
||||
import * as realContext from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
// Only the lookup is stubbed: mocking the whole module would leak into the other test files,
|
||||
// as `mock.module` replaces it for the entire test process.
|
||||
mock.module('@/lib/context', () => ({
|
||||
...realContext,
|
||||
getBaseContext: (input: unknown) => input,
|
||||
fetchSiteContextByURLLookup: async (_baseContext: unknown, data: unknown) => data,
|
||||
fetchSiteScopeContextByURLLookup: async (_baseContext: unknown, data: unknown) => data,
|
||||
}));
|
||||
// Stand in for the exchange endpoint, which is the only thing that can narrow the claims. It is
|
||||
// stubbed at the network boundary rather than with `mock.module`, which would replace
|
||||
// `@/lib/ppr-token` for the entire test process and break its own test file.
|
||||
const realFetch = globalThis.fetch;
|
||||
|
||||
beforeAll(() => {
|
||||
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const { scope } = JSON.parse(String(init?.body));
|
||||
// Deterministic per scope, so the assertions below can compare tokens across pages.
|
||||
return Response.json({
|
||||
token: jwt.sign(
|
||||
{ exp: Math.floor(Date.now() / 1000) + 3600, claims: { scope } },
|
||||
'secret'
|
||||
),
|
||||
});
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
const {
|
||||
getPPRHeaderRouteParams,
|
||||
getPPRPageRouteParams,
|
||||
getPPRRouteParams,
|
||||
getPPRSiteRouteParams,
|
||||
getPPRStaticSiteContext,
|
||||
getPPRStaticSiteScopeContext,
|
||||
getPPRTableOfContentsRouteParams,
|
||||
getPPRVisitorAuthClaims,
|
||||
getSiteURLDataFromParams,
|
||||
} = await import('./utils');
|
||||
type PPRRouteParams = import('./utils').PPRRouteParams;
|
||||
|
||||
const apiToken = jwt.sign(
|
||||
{
|
||||
exp: Math.floor(Date.now() / 1000) + 3600,
|
||||
siteClaims: { audience: 'external' },
|
||||
revisionClaims: { account: { tier: 'pro' } },
|
||||
pageClaims: { unsigned: { locale: 'fr' } },
|
||||
},
|
||||
'secret'
|
||||
);
|
||||
|
||||
const routeParams: PPRRouteParams = {
|
||||
mode: 'url',
|
||||
siteURL: 'docs.example.com',
|
||||
siteData: encodeURIComponent(
|
||||
rison.encode({
|
||||
apiToken,
|
||||
site: 'site-id',
|
||||
siteSection: 'page-site-section-id',
|
||||
siteSpace: 'page-site-space-id',
|
||||
space: 'space-id',
|
||||
revision: 'resolved-revision-id',
|
||||
siteBasePath: '/docs/',
|
||||
basePath: '/docs/v/page-variant/',
|
||||
imagesContextId: 'images-context-id',
|
||||
})
|
||||
),
|
||||
revisionId: encodeURIComponent('ppr-revision-id'),
|
||||
revalidationId: encodeURIComponent('revalidation-id'),
|
||||
pprDefaults: encodeURIComponent(
|
||||
rison.encode({
|
||||
siteSection: 'default-site-section-id',
|
||||
siteSpace: 'default-site-space-id',
|
||||
space: 'default-space-id',
|
||||
})
|
||||
),
|
||||
pagePath: 'guide',
|
||||
};
|
||||
|
||||
describe('getPPRRouteParams', () => {
|
||||
it('removes the PPR cache key while preserving resolved content and API token', () => {
|
||||
const params = getPPRRouteParams(routeParams);
|
||||
|
||||
expect(params).toMatchObject({
|
||||
mode: routeParams.mode,
|
||||
siteURL: routeParams.siteURL,
|
||||
pagePath: routeParams.pagePath,
|
||||
});
|
||||
expect(params).not.toHaveProperty('revisionId');
|
||||
expect(params).not.toHaveProperty('revalidationId');
|
||||
expect(params).not.toHaveProperty('pprDefaults');
|
||||
expect(getSiteURLDataFromParams(params)).toMatchObject({
|
||||
apiToken,
|
||||
site: 'site-id',
|
||||
space: 'space-id',
|
||||
revision: 'ppr-revision-id',
|
||||
imagesContextId: 'images-context-id',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('PPR cache region params', () => {
|
||||
const changedRouteParams: PPRRouteParams = {
|
||||
...routeParams,
|
||||
siteData: encodeURIComponent(
|
||||
rison.encode({
|
||||
apiToken: jwt.sign({ siteClaims: {} }, 'other-secret'),
|
||||
site: 'site-id',
|
||||
siteSection: 'new-page-site-section-id',
|
||||
siteSpace: 'new-page-site-space-id',
|
||||
space: 'new-space-id',
|
||||
revision: 'resolved-revision-id',
|
||||
siteBasePath: '/docs/',
|
||||
basePath: '/docs/v/other-variant/',
|
||||
imagesContextId: 'images-context-id',
|
||||
})
|
||||
),
|
||||
};
|
||||
|
||||
it('keeps header params stable, API token included', async () => {
|
||||
const headerData = getSiteURLDataFromParams(await getPPRHeaderRouteParams(routeParams));
|
||||
const changedHeaderData = getSiteURLDataFromParams(
|
||||
await getPPRHeaderRouteParams(changedRouteParams)
|
||||
);
|
||||
|
||||
expect(headerData).toMatchObject({
|
||||
siteSection: 'default-site-section-id',
|
||||
siteSpace: 'default-site-space-id',
|
||||
space: 'default-space-id',
|
||||
// The default variant is served at the site root, so its links can't keep the base
|
||||
// path of the variant the visitor is on.
|
||||
basePath: '/docs/',
|
||||
});
|
||||
// The whole point of the exchange: the site-scoped token no longer varies per page, so the
|
||||
// header can be cached once for the site instead of once per page.
|
||||
expect(headerData).toEqual(changedHeaderData);
|
||||
});
|
||||
|
||||
it('keeps the visited location in the site params, with the header token', async () => {
|
||||
const siteData = getSiteURLDataFromParams(await getPPRSiteRouteParams(routeParams));
|
||||
const headerData = getSiteURLDataFromParams(await getPPRHeaderRouteParams(routeParams));
|
||||
|
||||
// The shell renders the variant the visitor is on, it just never reads below the site level.
|
||||
expect(siteData).toMatchObject({
|
||||
siteSection: 'page-site-section-id',
|
||||
siteSpace: 'page-site-space-id',
|
||||
space: 'space-id',
|
||||
basePath: '/docs/v/page-variant/',
|
||||
revision: 'ppr-revision-id',
|
||||
});
|
||||
// Same scope as the header, so they share their site fetch.
|
||||
expect(siteData.apiToken).toBe(headerData.apiToken);
|
||||
});
|
||||
|
||||
it('narrows the header token to the site scope', async () => {
|
||||
const { apiToken: headerToken } = getSiteURLDataFromParams(
|
||||
await getPPRHeaderRouteParams(routeParams)
|
||||
);
|
||||
|
||||
expect(headerToken).not.toBe(apiToken);
|
||||
expect(jwt.decode(headerToken)).toMatchObject({ claims: { scope: 'site' } });
|
||||
});
|
||||
|
||||
it('keeps the visited base path when the defaults point at the visited variant', async () => {
|
||||
const headerData = getSiteURLDataFromParams(
|
||||
await getPPRHeaderRouteParams({
|
||||
...routeParams,
|
||||
pprDefaults: encodeURIComponent(
|
||||
rison.encode({
|
||||
siteSection: 'page-site-section-id',
|
||||
siteSpace: 'page-site-space-id',
|
||||
space: 'space-id',
|
||||
})
|
||||
),
|
||||
})
|
||||
);
|
||||
|
||||
expect(headerData).toMatchObject({
|
||||
siteSpace: 'page-site-space-id',
|
||||
basePath: '/docs/v/page-variant/',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps TOC params stable apart from its current location', async () => {
|
||||
const tocData = getSiteURLDataFromParams(
|
||||
await getPPRTableOfContentsRouteParams(routeParams)
|
||||
);
|
||||
const changedTOCData = getSiteURLDataFromParams(
|
||||
await getPPRTableOfContentsRouteParams(changedRouteParams)
|
||||
);
|
||||
|
||||
expect(tocData).toMatchObject({
|
||||
siteSection: 'page-site-section-id',
|
||||
siteSpace: 'page-site-space-id',
|
||||
space: 'space-id',
|
||||
basePath: '/docs/v/page-variant/',
|
||||
});
|
||||
// The revision-scoped token drops the page claims, so it is shared by every page of the
|
||||
// space; only the location data still varies.
|
||||
expect(tocData.apiToken).toBe(changedTOCData.apiToken);
|
||||
expect({
|
||||
...tocData,
|
||||
siteSection: undefined,
|
||||
siteSpace: undefined,
|
||||
space: undefined,
|
||||
basePath: undefined,
|
||||
}).toEqual({
|
||||
...changedTOCData,
|
||||
siteSection: undefined,
|
||||
siteSpace: undefined,
|
||||
space: undefined,
|
||||
basePath: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('narrows the TOC and page tokens to their own scopes', async () => {
|
||||
const tocData = getSiteURLDataFromParams(
|
||||
await getPPRTableOfContentsRouteParams(routeParams)
|
||||
);
|
||||
const pageData = getSiteURLDataFromParams(await getPPRPageRouteParams(routeParams));
|
||||
|
||||
expect(jwt.decode(tocData.apiToken)).toMatchObject({ claims: { scope: 'revision' } });
|
||||
expect(jwt.decode(pageData.apiToken)).toMatchObject({ claims: { scope: 'page' } });
|
||||
expect(tocData.apiToken).not.toBe(pageData.apiToken);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPPRVisitorAuthClaims', () => {
|
||||
it('resolves every scope at once through a full exchange', async () => {
|
||||
// The scoped tokens each carry one bucket, so the client claims can only come from `full`.
|
||||
expect(await getPPRVisitorAuthClaims(routeParams)).toEqual({ scope: 'full' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPPRStaticSiteScopeContext', () => {
|
||||
it('resolves the site scope from the supplied params', async () => {
|
||||
const { context } = await getPPRStaticSiteScopeContext(
|
||||
getPPRRouteParams(routeParams),
|
||||
'header'
|
||||
);
|
||||
|
||||
expect(context).toMatchObject({
|
||||
apiToken,
|
||||
revision: 'ppr-revision-id',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPPRStaticSiteContext', () => {
|
||||
it('uses the supplied API token without resolving published content again', async () => {
|
||||
const { context } = await getPPRStaticSiteContext(getPPRRouteParams(routeParams), 'body');
|
||||
|
||||
expect(context).toMatchObject({
|
||||
apiToken,
|
||||
revision: 'ppr-revision-id',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,20 @@ import rison from 'rison';
|
||||
|
||||
import type { SiteAPIToken } from '@gitbook/api';
|
||||
|
||||
import { getVisitorAuthClaims, getVisitorAuthClaimsFromToken } from '@/lib/adaptive';
|
||||
import { type SiteURLData, fetchSiteContextByURLLookup, getBaseContext } from '@/lib/context';
|
||||
import {
|
||||
type VisitorAuthClaims,
|
||||
getVisitorAuthClaims,
|
||||
getVisitorAuthClaimsFromToken,
|
||||
} from '@/lib/adaptive';
|
||||
import type { PPRCacheScope } from '@/lib/cache-tags';
|
||||
import {
|
||||
type SiteURLData,
|
||||
fetchSiteContextByURLLookup,
|
||||
fetchSiteScopeContextByURLLookup,
|
||||
getBaseContext,
|
||||
} from '@/lib/context';
|
||||
import { getDynamicCustomizationSettings } from '@/lib/customization';
|
||||
import { PPR_TOKEN_SCOPE, type PPRTokenScope, exchangePPRToken } from '@/lib/ppr-token';
|
||||
|
||||
export type RouteParamMode = 'url-host' | 'url';
|
||||
|
||||
@@ -24,10 +35,50 @@ export type RouteParams = RouteLayoutParams & {
|
||||
pagePath: string;
|
||||
};
|
||||
|
||||
export type PPRRouteLayoutParams = RouteLayoutParams & {
|
||||
revisionId: string;
|
||||
revalidationId: string;
|
||||
pprDefaults: string;
|
||||
};
|
||||
|
||||
export type PPRRouteParams = PPRRouteLayoutParams & {
|
||||
pagePath: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the static context when rendering statically a site.
|
||||
*/
|
||||
export async function getStaticSiteContext(params: RouteLayoutParams) {
|
||||
export async function getStaticSiteContext(
|
||||
params: RouteLayoutParams,
|
||||
options?: { pprScope?: PPRCacheScope }
|
||||
) {
|
||||
const { baseContext, siteURLData, decoded } = getStaticBaseContext(params, options);
|
||||
|
||||
return {
|
||||
context: await fetchSiteContextByURLLookup(baseContext, siteURLData),
|
||||
visitorAuthClaims: getVisitorAuthClaimsFromToken(decoded),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the site-level part of the static context, without resolving the space and its revision.
|
||||
*/
|
||||
export async function getStaticSiteScopeContext(
|
||||
params: RouteLayoutParams,
|
||||
options?: { pprScope?: PPRCacheScope }
|
||||
) {
|
||||
const { baseContext, siteURLData, decoded } = getStaticBaseContext(params, options);
|
||||
|
||||
return {
|
||||
context: await fetchSiteScopeContextByURLLookup(baseContext, siteURLData),
|
||||
visitorAuthClaims: getVisitorAuthClaimsFromToken(decoded),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the params of a static route and open a base context for them.
|
||||
*/
|
||||
function getStaticBaseContext(params: RouteLayoutParams, options?: { pprScope?: PPRCacheScope }) {
|
||||
const siteURL = getSiteURLFromParams(params);
|
||||
const siteURLData = getSiteURLDataFromParams(params);
|
||||
|
||||
@@ -38,18 +89,15 @@ export async function getStaticSiteContext(params: RouteLayoutParams) {
|
||||
forbidden();
|
||||
}
|
||||
|
||||
const context = await fetchSiteContextByURLLookup(
|
||||
getBaseContext({
|
||||
return {
|
||||
baseContext: getBaseContext({
|
||||
siteURL,
|
||||
siteURLData,
|
||||
urlMode: getModeFromParams(params.mode),
|
||||
...(options?.pprScope ? { pprScope: options.pprScope } : {}),
|
||||
}),
|
||||
siteURLData
|
||||
);
|
||||
|
||||
return {
|
||||
context,
|
||||
visitorAuthClaims: getVisitorAuthClaimsFromToken(decoded),
|
||||
siteURLData,
|
||||
decoded,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,3 +180,190 @@ export function getSiteURLDataFromParams(params: RouteLayoutParams): SiteURLData
|
||||
notFound();
|
||||
}
|
||||
}
|
||||
|
||||
export function getPPRRouteParams(params: PPRRouteParams): RouteParams;
|
||||
export function getPPRRouteParams(params: PPRRouteLayoutParams): RouteLayoutParams;
|
||||
/**
|
||||
* Project PPR route params for the current page, without PPR-only cache inputs.
|
||||
*/
|
||||
export function getPPRRouteParams(params: PPRRouteLayoutParams): RouteLayoutParams {
|
||||
const { revisionId, revalidationId, pprDefaults: _, ...routeParams } = params;
|
||||
const siteURLData = getSiteURLDataFromParams(params);
|
||||
|
||||
return {
|
||||
...routeParams,
|
||||
siteData: encodeURIComponent(
|
||||
rison.encode({
|
||||
...siteURLData,
|
||||
revision: getPPRRouteParam(revisionId, 'revision ID'),
|
||||
})
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Project PPR params for the current page, with a token scoped to the page claims.
|
||||
*/
|
||||
export function getPPRPageRouteParams(params: PPRRouteParams): Promise<RouteParams>;
|
||||
export function getPPRPageRouteParams(params: PPRRouteLayoutParams): Promise<RouteLayoutParams>;
|
||||
export function getPPRPageRouteParams(params: PPRRouteLayoutParams): Promise<RouteLayoutParams> {
|
||||
return withExchangedPPRToken(getPPRRouteParams(params), PPR_TOKEN_SCOPE.body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project PPR params for the site-level shell, with a token scoped to the site claims.
|
||||
* Unlike the header params, they keep the location data of the visited page: the shell renders the
|
||||
* current variant, it just never reads anything below the site level.
|
||||
*/
|
||||
export function getPPRSiteRouteParams(params: PPRRouteLayoutParams): Promise<RouteLayoutParams> {
|
||||
return withExchangedPPRToken(getPPRRouteParams(params), PPR_TOKEN_SCOPE.header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project PPR params for the shared header by replacing page-varying location data.
|
||||
*/
|
||||
export async function getPPRHeaderRouteParams(
|
||||
params: PPRRouteLayoutParams
|
||||
): Promise<RouteLayoutParams> {
|
||||
const routeParams = getPPRRouteParams(params);
|
||||
const { revision, ...siteURLData } = getSiteURLDataFromParams(routeParams);
|
||||
const defaults = getPPRDefaults(params);
|
||||
|
||||
return withExchangedPPRToken(
|
||||
{
|
||||
...routeParams,
|
||||
siteData: encodeSiteData({
|
||||
...siteURLData,
|
||||
// For the header, we keep site section and space data from the PPR defaults, so that the header can be cached across all pages in a site.
|
||||
siteSection: defaults.siteSection ?? undefined,
|
||||
siteSpace: defaults.siteSpace,
|
||||
space: defaults.space,
|
||||
// The base path has to describe the same variant as the ids above, or the header
|
||||
// prefixes one variant's page paths with another variant's base path. The site default
|
||||
// variant is published at the site root; defaults pointing at the visited variant keep
|
||||
// its own base path.
|
||||
basePath:
|
||||
defaults.siteSpace === siteURLData.siteSpace
|
||||
? siteURLData.basePath
|
||||
: siteURLData.siteBasePath,
|
||||
}),
|
||||
},
|
||||
PPR_TOKEN_SCOPE.header
|
||||
);
|
||||
}
|
||||
|
||||
/** rison can't encode undefined values, so they are dropped like the middleware does. */
|
||||
function encodeSiteData(siteURLData: Record<string, unknown>): string {
|
||||
return encodeURIComponent(
|
||||
rison.encode(
|
||||
Object.fromEntries(
|
||||
Object.entries(siteURLData).filter(([_, value]) => typeof value !== 'undefined')
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project PPR params for the table of contents, keeping its current location data.
|
||||
* The table of contents depends only on the space you're in and the claims of that revision, not on the page,
|
||||
* and the layout params carry no page path, so only the token has to be narrowed.
|
||||
*/
|
||||
export function getPPRTableOfContentsRouteParams(
|
||||
params: PPRRouteLayoutParams
|
||||
): Promise<RouteLayoutParams> {
|
||||
return withExchangedPPRToken(getPPRRouteParams(params), PPR_TOKEN_SCOPE.toc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the revalidation token carried by the PPR params with a content API token narrowed to
|
||||
* `scope`. Components sharing a scope then share a token, and with it a cache entry.
|
||||
*/
|
||||
async function withExchangedPPRToken<T extends RouteLayoutParams>(
|
||||
params: T,
|
||||
scope: PPRTokenScope
|
||||
): Promise<T> {
|
||||
const siteURLData = getSiteURLDataFromParams(params);
|
||||
|
||||
return {
|
||||
...params,
|
||||
siteData: encodeSiteData({
|
||||
...siteURLData,
|
||||
apiToken: await exchangePPRToken(siteURLData.apiToken, scope),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the claims the client should resolve adaptive content with. Each component holds a token
|
||||
* narrowed to a single scope, so the union has to come from a `full` exchange.
|
||||
*/
|
||||
export async function getPPRVisitorAuthClaims(
|
||||
params: PPRRouteLayoutParams
|
||||
): Promise<VisitorAuthClaims> {
|
||||
const { apiToken } = getSiteURLDataFromParams(params);
|
||||
const fullToken = await exchangePPRToken(apiToken, 'full');
|
||||
|
||||
return getVisitorAuthClaimsFromToken(jwtDecode<SiteAPIToken>(fullToken));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the static context for a PPR component. The scope partitions the cache entries and scopes
|
||||
* the tags they emit, so the component and its data are revalidated as one unit.
|
||||
*/
|
||||
export async function getPPRStaticSiteContext(params: RouteLayoutParams, pprScope: PPRCacheScope) {
|
||||
return getStaticSiteContext(params, { pprScope });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the site-level context for a PPR component, without resolving the space and its revision.
|
||||
*/
|
||||
export async function getPPRStaticSiteScopeContext(
|
||||
params: RouteLayoutParams,
|
||||
pprScope: PPRCacheScope
|
||||
) {
|
||||
return getStaticSiteScopeContext(params, { pprScope });
|
||||
}
|
||||
|
||||
function getPPRRouteParam(encodedParam: string, name: string): string {
|
||||
try {
|
||||
return decodeURIComponent(encodedParam);
|
||||
} catch (error) {
|
||||
console.error(`Returning 404 after failing to decode PPR ${name}: ${error}`);
|
||||
notFound();
|
||||
}
|
||||
}
|
||||
|
||||
type PPRDefaults = {
|
||||
siteSection: string | null;
|
||||
siteSpace: string;
|
||||
space: string;
|
||||
};
|
||||
|
||||
function getPPRDefaults(params: PPRRouteLayoutParams): PPRDefaults {
|
||||
let defaults: unknown;
|
||||
try {
|
||||
defaults = rison.decode(decodeURIComponent(params.pprDefaults));
|
||||
} catch (error) {
|
||||
console.error(`Returning 404 after failing to decode PPR defaults: ${error}`);
|
||||
notFound();
|
||||
}
|
||||
|
||||
if (
|
||||
!defaults ||
|
||||
typeof defaults !== 'object' ||
|
||||
Array.isArray(defaults) ||
|
||||
!('siteSection' in defaults) ||
|
||||
!('siteSpace' in defaults) ||
|
||||
!('space' in defaults) ||
|
||||
(defaults.siteSection !== null && typeof defaults.siteSection !== 'string') ||
|
||||
typeof defaults.siteSpace !== 'string' ||
|
||||
!defaults.siteSpace ||
|
||||
typeof defaults.space !== 'string' ||
|
||||
!defaults.space
|
||||
) {
|
||||
console.error(`Returning 404 after decoding invalid PPR defaults: ${params.pprDefaults}`);
|
||||
notFound();
|
||||
}
|
||||
|
||||
return defaults as PPRDefaults;
|
||||
}
|
||||
|
||||
+2
-2
@@ -6,8 +6,8 @@ import {
|
||||
GITBOOK_API_URL,
|
||||
GITBOOK_APP_URL,
|
||||
GITBOOK_ASSETS_URL,
|
||||
GITBOOK_DISABLE_INSIGHTS,
|
||||
GITBOOK_DISABLE_TRACKING,
|
||||
GITBOOK_EXCHANGE_TOKEN_URL,
|
||||
GITBOOK_FONTS_URL,
|
||||
GITBOOK_ICONS_URL,
|
||||
GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
|
||||
@@ -29,6 +29,7 @@ export async function GET(_req: NextRequest) {
|
||||
GITBOOK_API_URL,
|
||||
GITBOOK_API_PUBLIC_URL,
|
||||
GITBOOK_OAUTH_SERVER_URL,
|
||||
GITBOOK_EXCHANGE_TOKEN_URL,
|
||||
GITBOOK_ASSETS_URL,
|
||||
GITBOOK_FONTS_URL,
|
||||
GITBOOK_ICONS_URL,
|
||||
@@ -36,7 +37,6 @@ export async function GET(_req: NextRequest) {
|
||||
GITBOOK_INTEGRATIONS_HOST,
|
||||
GITBOOK_INTEGRATIONS_CONTENT_HOST,
|
||||
GITBOOK_DISABLE_TRACKING,
|
||||
GITBOOK_DISABLE_INSIGHTS,
|
||||
|
||||
// Secret envs
|
||||
GITBOOK_SECRET: !!GITBOOK_SECRET,
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'bun:test';
|
||||
|
||||
import { setIntercomLauncherHidden } from './intercom';
|
||||
|
||||
const originalWindow = globalThis.window;
|
||||
|
||||
afterEach(() => {
|
||||
if (originalWindow === undefined) {
|
||||
delete (globalThis as { window?: Window }).window;
|
||||
} else {
|
||||
globalThis.window = originalWindow;
|
||||
}
|
||||
});
|
||||
|
||||
function installIntercom(intercom: Window['Intercom']): void {
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: { Intercom: intercom },
|
||||
writable: true,
|
||||
});
|
||||
}
|
||||
|
||||
describe('setIntercomLauncherHidden', () => {
|
||||
it('hides the Intercom launcher', () => {
|
||||
const calls: unknown[][] = [];
|
||||
installIntercom((...args) => calls.push(args));
|
||||
|
||||
setIntercomLauncherHidden(true);
|
||||
|
||||
expect(calls).toEqual([['update', { hide_default_launcher: true }]]);
|
||||
});
|
||||
|
||||
it('shows the Intercom launcher', () => {
|
||||
const calls: unknown[][] = [];
|
||||
installIntercom((...args) => calls.push(args));
|
||||
|
||||
setIntercomLauncherHidden(false);
|
||||
|
||||
expect(calls).toEqual([['update', { hide_default_launcher: false }]]);
|
||||
});
|
||||
|
||||
it('does nothing when Intercom is unavailable', () => {
|
||||
expect(() => setIntercomLauncherHidden(true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
declare global {
|
||||
interface Window {
|
||||
Intercom?: (command: string, options?: Record<string, unknown>) => void;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide or show Intercom's default launcher when it is available on the host page.
|
||||
*/
|
||||
export function setIntercomLauncherHidden(hidden: boolean): void {
|
||||
if (typeof window === 'undefined' || typeof window.Intercom !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.Intercom('update', { hide_default_launcher: hidden });
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
'use server';
|
||||
|
||||
import { AgentFeedbackSource } from '@gitbook/api';
|
||||
|
||||
import type { AgentFeedbackResult } from '@/lib/agentFeedback';
|
||||
import { submitAgentFeedback } from '@/lib/agentFeedback/server';
|
||||
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import { traceErrorOnly } from '@/lib/tracing';
|
||||
|
||||
/**
|
||||
* Record a finding about the site's content, submitted by the assistant while helping a reader.
|
||||
*/
|
||||
export async function submitAssistantFeedbackToTeam(input: {
|
||||
feedback: string;
|
||||
goal?: string;
|
||||
/** Page the finding is about, as a URL on the site or a `/spaces/…/pages/…` ref. */
|
||||
page: string;
|
||||
asEmbeddable?: boolean;
|
||||
}): Promise<AgentFeedbackResult> {
|
||||
return traceErrorOnly('AI.submitAssistantFeedbackToTeam', async () => {
|
||||
const baseContext = await getServerActionBaseContext({
|
||||
isEmbeddable: input.asEmbeddable,
|
||||
});
|
||||
const context = await fetchServerActionSiteContext(baseContext);
|
||||
|
||||
return submitAgentFeedback(context, {
|
||||
feedback: input.feedback,
|
||||
goal: input.goal,
|
||||
page: input.page,
|
||||
source: AgentFeedbackSource.Assistant,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
export * from './types';
|
||||
export * from './chat';
|
||||
export * from './feedback';
|
||||
export * from './navigate';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use server';
|
||||
|
||||
import { toInSiteHref } from '../navigation';
|
||||
import { resolveContentRef, resolveStringContentRef, toContentRefPath } from '@/lib/references';
|
||||
import { resolveContentRef, resolveStringContentRef } from '@/lib/references';
|
||||
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import { traceErrorOnly } from '@/lib/tracing';
|
||||
|
||||
@@ -21,7 +21,15 @@ export async function resolveAINavigationLink(
|
||||
const baseContext = await getServerActionBaseContext();
|
||||
const context = await fetchServerActionSiteContext(baseContext);
|
||||
|
||||
const contentRef = resolveStringContentRef(toContentRefPath(url));
|
||||
// The content-ref scheme operates on the path portion of the URL. Strip any origin so an
|
||||
// absolute URL (e.g. `https://docs.example.com/spaces/.../pages/...`) is handled too.
|
||||
let path = url;
|
||||
if (URL.canParse(url)) {
|
||||
const parsed = new URL(url);
|
||||
path = `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
||||
}
|
||||
|
||||
const contentRef = resolveStringContentRef(path);
|
||||
if (contentRef) {
|
||||
const resolved = await resolveContentRef(contentRef, context);
|
||||
if (!resolved) {
|
||||
|
||||
@@ -18,12 +18,10 @@ import { type UpdateSearchState, useSetSearchState } from '../Search';
|
||||
import { addRecentSearchQuery } from '../Search/recent-queries';
|
||||
import type { AnyAIControl } from './controls';
|
||||
import { ConfirmControlDef, ConfirmControlOutputSchema } from './controls/ConfirmControl';
|
||||
import { setIntercomLauncherHidden } from './intercom';
|
||||
import { type AIChatReference, serializeReferences } from './references';
|
||||
import { type RenderAIMessageOptions, streamAIChatResponse } from './server-actions';
|
||||
import { getTools } from './tools';
|
||||
import { useAIMessageContextRef } from './useAIMessageContext';
|
||||
import { useLeaveAgentFeedbackTool, useLeaveUserFeedbackTool } from './useLeaveFeedbackTools';
|
||||
import { useNavigateToPageTool } from './useNavigateToPageTool';
|
||||
import {
|
||||
type ResponseToRate,
|
||||
@@ -242,6 +240,7 @@ export function AIChatProvider(props: {
|
||||
const setSearchStateInURL = useSetSearchState();
|
||||
const { siteSpaceId } = useCurrentContent();
|
||||
const language = useLanguage();
|
||||
|
||||
const displayContext = renderMessageOptions?.asEmbeddable
|
||||
? SiteInsightsDisplayContext.Embed
|
||||
: SiteInsightsDisplayContext.Site;
|
||||
@@ -257,10 +256,6 @@ export function AIChatProvider(props: {
|
||||
const responseToRateRef = React.useRef<ResponseToRate>({ responseId: null, query: null });
|
||||
const getResponseToRate = React.useCallback(() => responseToRateRef.current, []);
|
||||
|
||||
// Findings reported to the site's team are capped at one per conversation, so the assistant
|
||||
// cannot flood the inbox over a long chat.
|
||||
const reportedAgentFeedbackRef = React.useRef(false);
|
||||
|
||||
// Built-in tools exposed to the assistant (e.g. navigating to a page, submitting page or
|
||||
// assistant feedback). Each tool has a stable identity, so it can be referenced directly from
|
||||
// the streaming callback.
|
||||
@@ -270,41 +265,22 @@ export function AIChatProvider(props: {
|
||||
displayContext,
|
||||
getResponseToRate,
|
||||
});
|
||||
const leaveAgentFeedbackTool = useLeaveAgentFeedbackTool({
|
||||
asEmbeddable: renderMessageOptions?.asEmbeddable,
|
||||
displayContext,
|
||||
reportedRef: reportedAgentFeedbackRef,
|
||||
});
|
||||
const leaveUserFeedbackTool = useLeaveUserFeedbackTool({
|
||||
asEmbeddable: renderMessageOptions?.asEmbeddable,
|
||||
displayContext,
|
||||
});
|
||||
|
||||
// The assistant-feedback tool is always available (it mirrors the chat's own thumbs up/down
|
||||
// rating), while the tools carrying the reader's own feedback are gated on the site's
|
||||
// "Was this helpful?" setting.
|
||||
// rating), while the page-feedback tool is gated on the site's "Was this helpful?" setting.
|
||||
const builtInTools = React.useMemo(() => {
|
||||
const tools = [navigateToPageTool, submitAssistantFeedbackTool, leaveAgentFeedbackTool];
|
||||
const tools = [navigateToPageTool, submitAssistantFeedbackTool];
|
||||
if (withPageFeedback) {
|
||||
tools.push(submitPageFeedbackTool, leaveUserFeedbackTool);
|
||||
tools.push(submitPageFeedbackTool);
|
||||
}
|
||||
return tools;
|
||||
}, [
|
||||
navigateToPageTool,
|
||||
submitAssistantFeedbackTool,
|
||||
leaveAgentFeedbackTool,
|
||||
leaveUserFeedbackTool,
|
||||
submitPageFeedbackTool,
|
||||
withPageFeedback,
|
||||
]);
|
||||
}, [navigateToPageTool, submitAssistantFeedbackTool, submitPageFeedbackTool, withPageFeedback]);
|
||||
|
||||
// Event listeners storage
|
||||
const eventsRef = React.useRef<Map<AIChatEvent['type'], AIChatEventListener[]>>(new Map());
|
||||
|
||||
// Open AI chat and sync with search state
|
||||
const onOpen = React.useCallback(() => {
|
||||
setIntercomLauncherHidden(true);
|
||||
|
||||
const { initialQuery } = globalState.getState();
|
||||
globalState.setState((state) => ({ ...state, opened: true }));
|
||||
|
||||
@@ -321,8 +297,6 @@ export function AIChatProvider(props: {
|
||||
|
||||
// Close AI chat and clear ask parameter
|
||||
const onClose = React.useCallback(() => {
|
||||
setIntercomLauncherHidden(false);
|
||||
|
||||
globalState.setState((state) => ({ ...state, opened: false }));
|
||||
|
||||
// Clear ask parameter but keep other search state
|
||||
@@ -737,7 +711,6 @@ export function AIChatProvider(props: {
|
||||
// Clear the conversation and reset ask parameter
|
||||
const onClear = React.useCallback(() => {
|
||||
responseToRateRef.current = { responseId: null, query: null };
|
||||
reportedAgentFeedbackRef.current = false;
|
||||
globalState.setState((state) => ({
|
||||
opened: state.opened,
|
||||
responding: false,
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { z } from 'zod';
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
|
||||
import type { AIToolDefinition, SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
import type { GitBookIntegrationTool } from '@gitbook/browser-types';
|
||||
|
||||
import { type PagePointer, useCurrentPage } from '../hooks';
|
||||
import { type InsightsEventPageContext, useTrackEvent } from '../Insights';
|
||||
import { submitAssistantFeedbackToTeam } from './server-actions';
|
||||
import { useLanguage } from '@/intl/client';
|
||||
import { tString } from '@/intl/translate';
|
||||
import {
|
||||
AGENT_FEEDBACK_GOAL_MAX_LENGTH,
|
||||
AGENT_FEEDBACK_MAX_LENGTH,
|
||||
agentFeedbackDescriptions,
|
||||
formatAgentFeedbackPageRef,
|
||||
} from '@/lib/agentFeedback';
|
||||
|
||||
const feedbackInput = z.string().min(1).max(AGENT_FEEDBACK_MAX_LENGTH);
|
||||
const pageInput = z.string().optional().describe(agentFeedbackDescriptions.pageReference);
|
||||
|
||||
const LeaveAgentFeedbackInputSchema = z.object({
|
||||
feedback: feedbackInput.describe(agentFeedbackDescriptions.finding),
|
||||
goal: z
|
||||
.string()
|
||||
.max(AGENT_FEEDBACK_GOAL_MAX_LENGTH)
|
||||
.optional()
|
||||
.describe(agentFeedbackDescriptions.goal),
|
||||
page: pageInput,
|
||||
});
|
||||
|
||||
const LeaveUserFeedbackInputSchema = z.object({
|
||||
feedback: feedbackInput.describe(
|
||||
"The user's feedback about the content, copied verbatim. Never rephrase, summarise, correct, translate or add to their words. Quote only what they said about the documentation, and leave out anything personal or confidential."
|
||||
),
|
||||
page: pageInput,
|
||||
});
|
||||
|
||||
type LeaveFeedbackToolOptions = {
|
||||
/** Whether the assistant runs in the embeddable, which resolves its own site context. */
|
||||
asEmbeddable?: boolean;
|
||||
/** Display context recorded with the feedback event (e.g. `site` vs. `embed`). */
|
||||
displayContext: SiteInsightsDisplayContext;
|
||||
};
|
||||
|
||||
/** The assistant's own finding, so it submits without confirmation, capped at one per chat. */
|
||||
export function useLeaveAgentFeedbackTool(
|
||||
options: LeaveFeedbackToolOptions & {
|
||||
/** Whether a finding was already reported in this conversation, reset when it is cleared. */
|
||||
reportedRef: React.RefObject<boolean>;
|
||||
}
|
||||
): GitBookIntegrationTool {
|
||||
const { asEmbeddable, displayContext, reportedRef } = options;
|
||||
const language = useLanguage();
|
||||
const currentPage = useCurrentPage();
|
||||
const trackEvent = useTrackEvent();
|
||||
|
||||
// The tool object is memoized once, so read the latest values from a ref at call time.
|
||||
const ref = React.useRef({
|
||||
language,
|
||||
currentPage,
|
||||
asEmbeddable,
|
||||
displayContext,
|
||||
trackEvent,
|
||||
reportedRef,
|
||||
});
|
||||
React.useEffect(() => {
|
||||
ref.current = {
|
||||
language,
|
||||
currentPage,
|
||||
asEmbeddable,
|
||||
displayContext,
|
||||
trackEvent,
|
||||
reportedRef,
|
||||
};
|
||||
});
|
||||
|
||||
return React.useMemo<GitBookIntegrationTool>(
|
||||
() => ({
|
||||
name: 'leaveAgentFeedback',
|
||||
description:
|
||||
'Leave feedback as you, the GitBook Assistant, on ways this question could have been answered more easily through content changes or reorganization — a missing explanation, an outdated or contradictory passage, or an answer you had to piece together from several pages. Use it when answering was hard, or when you could not answer at all, so the team can close the gap. Write it for a documentation maintainer who never saw this conversation, and send at most one per conversation. This carries your own observation: use `leaveUserFeedback` to relay what the user said, and `submitPageFeedback` to record their rating of a page. Do not use it to confirm that a page is accurate.',
|
||||
inputSchema: zodToJsonSchema(
|
||||
LeaveAgentFeedbackInputSchema as any
|
||||
) as AIToolDefinition['inputSchema'],
|
||||
execute: async (input) => {
|
||||
const { reportedRef, ...tracking } = ref.current;
|
||||
const { feedback, goal, page } = LeaveAgentFeedbackInputSchema.parse(input);
|
||||
|
||||
if (reportedRef.current) {
|
||||
throw new Error(
|
||||
'A finding was already reported in this conversation. Do not report another one.'
|
||||
);
|
||||
}
|
||||
|
||||
await submitFeedback({ feedback, goal, page, ...tracking });
|
||||
reportedRef.current = true;
|
||||
|
||||
return {
|
||||
output: { submitted: true },
|
||||
summary: {
|
||||
icon: 'comment-check',
|
||||
text: tString(tracking.language, 'ai_chat_tools_shared_feedback_with_team'),
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
// Rebuild when the locale changes so the summary (read at memo time, not from the ref)
|
||||
// stays translated.
|
||||
[language]
|
||||
);
|
||||
}
|
||||
|
||||
/** Speaks for the reader, so it confirms first, showing the exact text about to be sent. */
|
||||
export function useLeaveUserFeedbackTool(
|
||||
options: LeaveFeedbackToolOptions
|
||||
): GitBookIntegrationTool {
|
||||
const { asEmbeddable, displayContext } = options;
|
||||
const language = useLanguage();
|
||||
const currentPage = useCurrentPage();
|
||||
const trackEvent = useTrackEvent();
|
||||
|
||||
// The tool object is memoized once, so read the latest values from a ref at call time.
|
||||
const ref = React.useRef({ language, currentPage, asEmbeddable, displayContext, trackEvent });
|
||||
React.useEffect(() => {
|
||||
ref.current = { language, currentPage, asEmbeddable, displayContext, trackEvent };
|
||||
});
|
||||
|
||||
return React.useMemo<GitBookIntegrationTool>(
|
||||
() => ({
|
||||
name: 'leaveUserFeedback',
|
||||
description:
|
||||
"Leave feedback on behalf of the user about the documentation, so the team can act on it. Use it when the user reports that something in the content is wrong, missing, outdated or confusing, or asks you to pass a message to the documentation team. Do not modify their feedback in any way: copy their own words. The user will be asked to confirm before it is sent. This carries the user's words: use `leaveAgentFeedback` for your own findings about the content, and `submitPageFeedback` to record their rating of a page.",
|
||||
confirmation: (input) => {
|
||||
const parsed = LeaveUserFeedbackInputSchema.safeParse(input);
|
||||
const feedback = parsed.success ? parsed.data.feedback.trim() : undefined;
|
||||
return {
|
||||
icon: 'paper-plane',
|
||||
label: tString(language, 'ai_chat_tools_submit_feedback'),
|
||||
context: feedback ? `"${feedback}"` : undefined,
|
||||
};
|
||||
},
|
||||
inputSchema: zodToJsonSchema(
|
||||
LeaveUserFeedbackInputSchema as any
|
||||
) as AIToolDefinition['inputSchema'],
|
||||
execute: async (input) => {
|
||||
const tracking = ref.current;
|
||||
const { feedback, page } = LeaveUserFeedbackInputSchema.parse(input);
|
||||
|
||||
await submitFeedback({ feedback, page, ...tracking });
|
||||
|
||||
return {
|
||||
output: { submitted: true },
|
||||
summary: {
|
||||
icon: 'comment-check',
|
||||
text: tString(tracking.language, 'ai_chat_tools_submitted_feedback'),
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
// Rebuild when the locale changes so the confirmation label (read at memo time, not from
|
||||
// the ref) stays translated.
|
||||
[language]
|
||||
);
|
||||
}
|
||||
|
||||
async function submitFeedback(input: {
|
||||
feedback: string;
|
||||
goal?: string;
|
||||
page?: string;
|
||||
currentPage: PagePointer | null;
|
||||
asEmbeddable?: boolean;
|
||||
displayContext: SiteInsightsDisplayContext;
|
||||
trackEvent: ReturnType<typeof useTrackEvent>;
|
||||
}): Promise<void> {
|
||||
const page =
|
||||
input.page?.trim() ||
|
||||
(input.currentPage ? formatAgentFeedbackPageRef(input.currentPage) : null);
|
||||
|
||||
if (!page) {
|
||||
throw new Error('No documentation page is currently open to leave feedback about.');
|
||||
}
|
||||
|
||||
const result = await submitAssistantFeedbackToTeam({
|
||||
feedback: input.feedback,
|
||||
goal: input.goal,
|
||||
page,
|
||||
asEmbeddable: input.asEmbeddable,
|
||||
});
|
||||
|
||||
if (!result.submitted) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
// Attribute to the page the reader is on, since the insights location only lets us override
|
||||
// the page — its space and revision come from the ambient context.
|
||||
const pageContext: InsightsEventPageContext = {
|
||||
pageId: input.currentPage?.pageId ?? null,
|
||||
displayContext: input.displayContext,
|
||||
};
|
||||
input.trackEvent({ type: 'agent_feedback' }, pageContext, { immediate: true });
|
||||
}
|
||||
@@ -80,7 +80,7 @@ export function useSubmitPageFeedbackTool(options: {
|
||||
() => ({
|
||||
name: 'submitPageFeedback',
|
||||
description:
|
||||
"Submit the feedback on behalf of the user about the documentation page they are currently viewing. Use this when the user is indicating a sentiment about the page, particularly a negative one, or pointing to incorrect or incoherent information on a page. Proactively suggest to submit feedback for the user to help alleviate frustration or indicate a content gap they've encountered. The user will be asked to confirm before the feedback is recorded. Provide a rating and, when the user gave one, a comment in their own words. This records their rating of the page — use `leaveUserFeedback` to pass a report of their own about the content on to the documentation team.",
|
||||
"Submit the feedback on behalf of the user about the documentation page they are currently viewing. Use this when the user is indicating a sentiment about the page, particularly a negative one, or pointing to incorrect or incoherent information on a page. Proactively suggest to submit feedback for the user to help alleviate frustration or indicate a content gap they've encountered. The user will be asked to confirm before the feedback is recorded. Provide a rating and, when the user gave one, a comment in their own words.",
|
||||
confirmation: (input) => {
|
||||
const parsed = SubmitPageFeedbackInputSchema.safeParse(input);
|
||||
const comment = parsed.success ? parsed.data.comment?.trim() : undefined;
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Icon } from '@gitbook/icons';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
import { Blocks } from '../Blocks';
|
||||
import { shouldShowHashLinks } from '../HashLinkButton';
|
||||
import { Inlines } from '../Inlines';
|
||||
import { Details } from './Details';
|
||||
import { ToggleChevron } from '@/components/primitives';
|
||||
@@ -32,8 +31,6 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
? await getSpaceLanguage(context.contentContext)
|
||||
: defaultLanguage;
|
||||
|
||||
const showHashLink = shouldShowHashLinks(context);
|
||||
|
||||
return (
|
||||
<Details
|
||||
id={id}
|
||||
@@ -44,8 +41,7 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
className={tcls(
|
||||
'cursor-pointer',
|
||||
'px-4',
|
||||
// Reserve room for the anchor icon pinned to the right edge
|
||||
showHashLink && 'pr-10',
|
||||
'pr-10',
|
||||
'py-4',
|
||||
'relative',
|
||||
'list-none',
|
||||
@@ -75,34 +71,32 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
context={context}
|
||||
ancestorInlines={[]}
|
||||
/>
|
||||
{showHashLink ? (
|
||||
<a
|
||||
href={`#${id}`}
|
||||
aria-label={tString(language, 'direct_link_to_heading')}
|
||||
<a
|
||||
href={`#${id}`}
|
||||
aria-label={tString(language, 'direct_link_to_heading')}
|
||||
className={tcls(
|
||||
'absolute',
|
||||
'top-2',
|
||||
'bottom-2',
|
||||
'right-4',
|
||||
'flex',
|
||||
'items-center',
|
||||
'dark:shadow-none',
|
||||
'dark:ring-0'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon="hashtag"
|
||||
className={tcls(
|
||||
'absolute',
|
||||
'top-2',
|
||||
'bottom-2',
|
||||
'right-4',
|
||||
'flex',
|
||||
'items-center',
|
||||
'dark:shadow-none',
|
||||
'dark:ring-0'
|
||||
'inline-block',
|
||||
'size-3',
|
||||
'transition-colors',
|
||||
'text-transparent',
|
||||
'group-hover/expandable:text-tint-subtle',
|
||||
'contrast-more:group-hover/expandable:text-tint-strong'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon="hashtag"
|
||||
className={tcls(
|
||||
'inline-block',
|
||||
'size-3',
|
||||
'transition-colors',
|
||||
'text-transparent',
|
||||
'group-hover/expandable:text-tint-subtle',
|
||||
'contrast-more:group-hover/expandable:text-tint-strong'
|
||||
)}
|
||||
/>
|
||||
</a>
|
||||
) : null}
|
||||
/>
|
||||
</a>
|
||||
</summary>
|
||||
<Blocks
|
||||
nodes={body.nodes}
|
||||
|
||||
@@ -2,22 +2,9 @@ import type { DocumentBlockHeading, DocumentBlockTabs } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { Link } from '../primitives';
|
||||
import type { DocumentContext } from './DocumentView';
|
||||
import { getBlockTextStyle } from './spacing';
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
* Whether blocks should render a visible anchor link icon.
|
||||
* Only the page body carries a page; search answers, AI chat and PDF export keep anchors.
|
||||
*/
|
||||
export function shouldShowHashLinks(context: DocumentContext): boolean {
|
||||
const contentContext = context.contentContext;
|
||||
if (!contentContext || !('page' in contentContext)) {
|
||||
return true;
|
||||
}
|
||||
return contentContext.page.layout.anchors !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hash icon which adds the block or active block item's ID in the URL hash.
|
||||
* The button needs to be wrapped in a container with `hashLinkButtonWrapperStyles`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { DocumentBlockHeading } from '@gitbook/api';
|
||||
|
||||
import type { BlockProps } from './Block';
|
||||
import { HashLinkButton, hashLinkButtonWrapperStyles, shouldShowHashLinks } from './HashLinkButton';
|
||||
import { HashLinkButton, hashLinkButtonWrapperStyles } from './HashLinkButton';
|
||||
import { HeadingRevealWrapper } from './HeadingRevealWrapper';
|
||||
import { Inlines } from './Inlines';
|
||||
import { getBlockTextStyle } from './spacing';
|
||||
@@ -24,8 +24,6 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
? await getSpaceLanguage(context.contentContext)
|
||||
: defaultLanguage;
|
||||
|
||||
const showHashLink = shouldShowHashLinks(context);
|
||||
|
||||
return (
|
||||
<HeadingRevealWrapper
|
||||
as={Tag}
|
||||
@@ -36,8 +34,7 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
'font-heading',
|
||||
'pdf-heading',
|
||||
'block',
|
||||
// Reserve room for the absolutely positioned anchor icon on coarse pointers
|
||||
showHashLink && 'pr-6',
|
||||
'pr-6',
|
||||
'pointer-fine:flex',
|
||||
'pointer-fine:items-baseline',
|
||||
'pointer-fine:pr-0',
|
||||
@@ -66,22 +63,20 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
<Inlines {...rest} context={context} nodes={block.nodes} ancestorInlines={[]} />
|
||||
</span>
|
||||
|
||||
{showHashLink ? (
|
||||
<HashLinkButton
|
||||
id={id}
|
||||
block={block}
|
||||
className={tcls(
|
||||
'absolute',
|
||||
block.type === 'heading-1'
|
||||
? '[transform:translateY(0.125em)]'
|
||||
: '[transform:translateY(0.17em)]',
|
||||
'pointer-fine:-ml-6 pointer-fine:relative pointer-fine:order-first pointer-fine:self-center pointer-fine:pr-2 pointer-fine:[transform:none]',
|
||||
'pointer-fine:[.flip-heading-hash_&]:order-last pointer-fine:[.flip-heading-hash_&]:ml-1 pointer-fine:[.flip-heading-hash_&]:pl-2'
|
||||
)}
|
||||
iconClassName={tcls('size-4')}
|
||||
label={tString(language, 'direct_link_to_heading')}
|
||||
/>
|
||||
) : null}
|
||||
<HashLinkButton
|
||||
id={id}
|
||||
block={block}
|
||||
className={tcls(
|
||||
'absolute',
|
||||
block.type === 'heading-1'
|
||||
? '[transform:translateY(0.125em)]'
|
||||
: '[transform:translateY(0.17em)]',
|
||||
'pointer-fine:-ml-6 pointer-fine:relative pointer-fine:order-first pointer-fine:self-center pointer-fine:pr-2 pointer-fine:[transform:none]',
|
||||
'pointer-fine:[.flip-heading-hash_&]:order-last pointer-fine:[.flip-heading-hash_&]:ml-1 pointer-fine:[.flip-heading-hash_&]:pl-2'
|
||||
)}
|
||||
iconClassName={tcls('size-4')}
|
||||
label={tString(language, 'direct_link_to_heading')}
|
||||
/>
|
||||
</HeadingRevealWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
const anchorElement = (
|
||||
<InlineLinkAnchor
|
||||
href={resolved.href}
|
||||
contentRef={resolved.resolvedRef ?? inline.data.ref}
|
||||
isExternal={(resolved.resolvedRef ?? inline.data.ref).kind === 'url'}
|
||||
contentRef={inline.data.ref}
|
||||
isExternal={inline.data.ref.kind === 'url'}
|
||||
>
|
||||
{inlinesElement}
|
||||
</InlineLinkAnchor>
|
||||
@@ -121,7 +121,7 @@ function InlineLinkTooltipWrapper(props: {
|
||||
|
||||
let breadcrumbs = resolved.ancestors ?? [];
|
||||
const isMailto = resolved.href.startsWith('mailto:');
|
||||
const isExternal = (resolved.resolvedRef ?? inline.data.ref).kind === 'url';
|
||||
const isExternal = inline.data.ref.kind === 'url';
|
||||
const isSamePage = inline.data.ref.kind === 'anchor' && inline.data.ref.page === undefined;
|
||||
|
||||
if (isMailto) {
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
|
||||
/** Buttons */
|
||||
.contentkit-button {
|
||||
@apply text-sm px-3 h-8 text-center inline-block py-1.5 rounded-md straight-corners:rounded-none ring-1 ring-tint hover:ring-tint-hover shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12 hover:scale-105 active:scale-100 transition-all truncate;
|
||||
@apply text-sm px-3 h-8 text-center inline-block py-1.5 rounded-md straight-corners:rounded-none place-self-start ring-1 ring-tint hover:ring-tint-hover shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12 hover:scale-105 active:scale-100 transition-all grow-0 shrink-0 truncate w-full;
|
||||
}
|
||||
|
||||
.contentkit-button-style-primary {
|
||||
@@ -130,38 +130,15 @@
|
||||
.contentkit-modal-header {
|
||||
@apply flex flex-col gap-2 px-4 py-2;
|
||||
}
|
||||
.contentkit-modal-header-with-close {
|
||||
@apply flex-row items-start gap-4 px-4 pb-0 pt-4;
|
||||
}
|
||||
.contentkit-modal-header-content {
|
||||
@apply min-w-0 flex-1;
|
||||
}
|
||||
|
||||
.contentkit-modal-title {
|
||||
@apply text-2xl font-medium text-tint-strong;
|
||||
}
|
||||
.contentkit-modal-header-with-close .contentkit-modal-subtitle {
|
||||
@apply break-words text-sm text-tint;
|
||||
}
|
||||
.contentkit-modal-header-with-close .contentkit-modal-title {
|
||||
@apply break-words;
|
||||
}
|
||||
|
||||
.contentkit-modal-body {
|
||||
@apply px-4 py-4;
|
||||
}
|
||||
|
||||
.contentkit-modal-footer {
|
||||
@apply flex justify-end gap-2 px-4 pb-4;
|
||||
}
|
||||
|
||||
.contentkit-modal-close {
|
||||
@apply flex size-8 shrink-0 items-center justify-center rounded-full text-tint transition-colors hover:bg-tint-hover hover:text-tint-strong focus-visible:outline-2 focus-visible:outline-primary;
|
||||
}
|
||||
.contentkit-modal-close-icon {
|
||||
@apply size-4;
|
||||
}
|
||||
|
||||
.contentkit-modal-header + .contentkit-modal-body {
|
||||
@apply pt-0;
|
||||
}
|
||||
@@ -231,6 +208,9 @@
|
||||
.contentkit-modal-confirm .contentkit-modal-footer {
|
||||
@apply flex gap-2 justify-end;
|
||||
}
|
||||
.contentkit-button-confirm {
|
||||
@apply w-auto flex-grow-0 flex-shrink-0;
|
||||
}
|
||||
.contentkit-button-style-danger {
|
||||
@apply bg-danger text-danger hover:bg-danger-hover hover:text-danger-strong contrast-more:bg-tint-subtle;
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { type PromptActionId, setPromptAction, usePromptAction } from './promptAction';
|
||||
import {
|
||||
Button,
|
||||
ButtonGroup,
|
||||
DropdownMenu,
|
||||
DropdownMenuItem,
|
||||
ToggleChevron,
|
||||
} from '@/components/primitives';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { AI_AGENTS, getAIAgent } from '@/lib/ai-agents';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
/** How long the copy button shows its confirmation. */
|
||||
const COPIED_MESSAGE_DURATION = 1000;
|
||||
|
||||
/**
|
||||
* Actions of a prompt block: copying the prompt, or handing it to a coding agent. The visitor's
|
||||
* last pick becomes the main button, here and in every other prompt block they come across.
|
||||
*/
|
||||
export function PromptActions(props: { prompt: string; openInAIProviders: boolean }) {
|
||||
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 copyPrompt = () => {
|
||||
navigator.clipboard.writeText(prompt);
|
||||
setCopied(true);
|
||||
};
|
||||
|
||||
// The pick follows the visitor from site to site, so fall back to copying wherever the agent
|
||||
// actions are turned off — and with nothing to hand over, an agent link would open an agent on
|
||||
// an empty prompt.
|
||||
const action: PromptActionId = openInAIProviders && prompt ? selectedAction : 'copy';
|
||||
const agent = action === 'copy' ? null : getAIAgent(action);
|
||||
|
||||
const mainButton = agent ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="xsmall"
|
||||
icon={agent.icon}
|
||||
label={tString(language, 'open_in', agent.label)}
|
||||
href={agent.getURL(prompt)}
|
||||
// The OS picks the deep link up and the page stays put, where `_blank` would strand the
|
||||
// visitor on a tab that never loads anything.
|
||||
target="_self"
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="xsmall"
|
||||
icon={copied ? 'check' : 'copy'}
|
||||
label={copied ? tString(language, 'code_copied') : tString(language, 'prompt_copy')}
|
||||
disabled={!prompt}
|
||||
onClick={copyPrompt}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
// Lifted above the header's overlay button, which otherwise swallows the clicks.
|
||||
<div className="relative z-20 flex shrink-0 items-center gap-2">
|
||||
{openInAIProviders ? (
|
||||
<ButtonGroup>
|
||||
{mainButton}
|
||||
<DropdownMenu
|
||||
align="end"
|
||||
className="!min-w-48 max-w-max"
|
||||
button={
|
||||
<Button
|
||||
label={tString(language, 'more')}
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
truncate={false}
|
||||
disabled={!prompt}
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<AgentIconStack />
|
||||
<ToggleChevron className="size-text-sm" />
|
||||
</span>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
active={action === 'copy'}
|
||||
leadingIcon="copy"
|
||||
onClick={() => {
|
||||
setPromptAction('copy');
|
||||
copyPrompt();
|
||||
}}
|
||||
>
|
||||
{tString(language, 'prompt_copy')}
|
||||
</DropdownMenuItem>
|
||||
{AI_AGENTS.map((item) => (
|
||||
<DropdownMenuItem
|
||||
key={item.id}
|
||||
active={action === item.id}
|
||||
leadingIcon={item.icon}
|
||||
href={item.getURL(prompt)}
|
||||
target="_self"
|
||||
onClick={() => setPromptAction(item.id)}
|
||||
>
|
||||
{tString(language, 'open_in', item.label)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenu>
|
||||
</ButtonGroup>
|
||||
) : (
|
||||
mainButton
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The agents on offer, overlapped into a stack, so the menu advertises what it holds without
|
||||
* spelling out three names next to a button that already has one.
|
||||
*/
|
||||
function AgentIconStack() {
|
||||
return (
|
||||
<span className="flex items-center">
|
||||
{AI_AGENTS.map((agent, index) => (
|
||||
<span
|
||||
key={agent.id}
|
||||
className={tcls(
|
||||
'flex size-4 shrink-0 items-center justify-center rounded-full border border-tint bg-tint-base',
|
||||
// Each chip's border cuts into the one behind it, so the marks stay legible
|
||||
// however tightly they are stacked.
|
||||
index > 0 && '-ms-1.5'
|
||||
)}
|
||||
>
|
||||
<Icon icon={agent.icon} className="size-2.5" />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -5,11 +5,14 @@ import React from 'react';
|
||||
import type { DocumentBlockPrompt } from '@gitbook/api';
|
||||
import { Icon, type IconName } from '@gitbook/icons';
|
||||
|
||||
import { PromptActions } from './PromptActions';
|
||||
import { ToggleChevron } from '@/components/primitives';
|
||||
import { Button, DropdownMenu, DropdownMenuItem, ToggleChevron } from '@/components/primitives';
|
||||
import { getURLForLLM } from '@/components/utils';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
const OPEN_IN_AI_PROVIDERS = ['claude', 'chatgpt', 'cursor'] as const;
|
||||
type AIProviders = (typeof OPEN_IN_AI_PROVIDERS)[number];
|
||||
|
||||
type PromptClientProps = DocumentBlockPrompt['data'] & {
|
||||
contentIcon: IconName | null;
|
||||
prompt: string;
|
||||
@@ -85,3 +88,106 @@ export function PromptClient(props: PromptClientProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptActions(props: { prompt: string; openInAIProviders: boolean }) {
|
||||
const { prompt, openInAIProviders } = props;
|
||||
|
||||
return (
|
||||
<div className="relative z-20 flex shrink-0 items-center gap-2">
|
||||
<CopyPromptButton prompt={prompt} />
|
||||
{openInAIProviders ? <OpenPromptDropdown prompt={prompt} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// time in milliseconds to show the "Copied" message after copying a prompt
|
||||
const COPIED_MESSAGE_DURATION = 1000;
|
||||
|
||||
function CopyPromptButton(props: { prompt: string }) {
|
||||
const { prompt } = props;
|
||||
const language = useLanguage();
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!copied) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, COPIED_MESSAGE_DURATION);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}, [copied]);
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="xsmall"
|
||||
label={copied ? tString(language, 'code_copied') : tString(language, 'prompt_copy')}
|
||||
disabled={!prompt}
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(prompt);
|
||||
setCopied(true);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function OpenPromptDropdown(props: { prompt: string }) {
|
||||
const { prompt } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
align="end"
|
||||
className="!min-w-48 max-w-max"
|
||||
button={
|
||||
<Button
|
||||
label={tString(language, 'open_in_ai')}
|
||||
trailing={<ToggleChevron className="size-text-sm" />}
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
className="max-sm:hidden"
|
||||
disabled={!prompt}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{OPEN_IN_AI_PROVIDERS.map((provider) => {
|
||||
const definition = getPromptOpenActionDefinition(provider);
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={provider}
|
||||
href={getURLForLLM(provider, prompt)}
|
||||
target="_blank"
|
||||
leadingIcon={definition.icon}
|
||||
>
|
||||
{tString(language, 'open_in', definition.label)}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function getPromptOpenActionDefinition(action: AIProviders): { icon: IconName; label: string } {
|
||||
switch (action) {
|
||||
case 'cursor':
|
||||
return {
|
||||
icon: 'cursor',
|
||||
label: 'Cursor',
|
||||
};
|
||||
case 'claude':
|
||||
return {
|
||||
icon: 'claude',
|
||||
label: 'Claude',
|
||||
};
|
||||
case 'chatgpt':
|
||||
return {
|
||||
icon: 'chatgpt',
|
||||
label: 'ChatGPT',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { type AIAgentId, isAIAgentId } from '@/lib/ai-agents';
|
||||
import { getLocalStorageItem, setLocalStorageItem } from '@/lib/browser';
|
||||
|
||||
/**
|
||||
* What a prompt block does when its main button is pressed: copy the prompt, or hand it to one of
|
||||
* the coding agents.
|
||||
*/
|
||||
export type PromptActionId = 'copy' | AIAgentId;
|
||||
|
||||
/**
|
||||
* Not namespaced per site: a visitor who works in Cursor works in Cursor everywhere, so the pick
|
||||
* follows them across sites the same way the `select` store's slugs do.
|
||||
*/
|
||||
const STORAGE_KEY = '@gitbook/prompt-action';
|
||||
|
||||
const DEFAULT_ACTION: PromptActionId = 'copy';
|
||||
|
||||
let state: PromptActionId = DEFAULT_ACTION;
|
||||
let loaded = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function isPromptActionId(value: unknown): value is PromptActionId {
|
||||
return value === 'copy' || isAIAgentId(value);
|
||||
}
|
||||
|
||||
function read(): PromptActionId {
|
||||
const stored = getLocalStorageItem<unknown>(STORAGE_KEY, DEFAULT_ACTION);
|
||||
return isPromptActionId(stored) ? stored : DEFAULT_ACTION;
|
||||
}
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt what's in storage, once per page load. Deferred to the first subscription rather than run at
|
||||
* module scope so the first client render still matches the server's, and the stored pick only
|
||||
* lands once React is listening.
|
||||
*/
|
||||
function load() {
|
||||
if (loaded || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
loaded = true;
|
||||
state = read();
|
||||
|
||||
// Another tab picking an action updates this one too.
|
||||
window.addEventListener('storage', (event) => {
|
||||
if (event.key !== null && event.key !== STORAGE_KEY) {
|
||||
return;
|
||||
}
|
||||
state = read();
|
||||
emitChange();
|
||||
});
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
load();
|
||||
listeners.add(listener);
|
||||
// Storage was only read just now, so nudge the subscriber to re-read the snapshot.
|
||||
listener();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Remember the action the visitor picked, for every prompt block on the page and the next one.
|
||||
*/
|
||||
export function setPromptAction(action: PromptActionId) {
|
||||
load();
|
||||
if (state === action) {
|
||||
return;
|
||||
}
|
||||
state = action;
|
||||
setLocalStorageItem(STORAGE_KEY, action);
|
||||
emitChange();
|
||||
}
|
||||
|
||||
/**
|
||||
* The action the visitor last picked, defaulting to copying the prompt.
|
||||
*/
|
||||
export function usePromptAction(): PromptActionId {
|
||||
return React.useSyncExternalStore(
|
||||
subscribe,
|
||||
() => state,
|
||||
() => DEFAULT_ACTION
|
||||
);
|
||||
}
|
||||
@@ -226,10 +226,11 @@ function SelectFilterDropdown(props: { column: TableSelectColumn }) {
|
||||
key={option.value}
|
||||
active={selected}
|
||||
leadingIcon={selected ? 'check' : undefined}
|
||||
// `closeOnClick={false}` keeps the menu open so several options can be
|
||||
// toggled at once.
|
||||
closeOnClick={false}
|
||||
onClick={() => toggleOption(column.id, option.value)}
|
||||
onSelect={(event) => {
|
||||
// Keep the menu open so several options can be toggled at once.
|
||||
event.preventDefault();
|
||||
toggleOption(column.id, option.value);
|
||||
}}
|
||||
>
|
||||
{option.label || option.value}
|
||||
</DropdownMenuItem>
|
||||
|
||||
@@ -5,12 +5,7 @@ import { validateIconName } from '@gitbook/icons/icons';
|
||||
import type { BlockProps } from '../Block';
|
||||
import { Blocks } from '../Blocks';
|
||||
import { DynamicTabs } from './DynamicTabs';
|
||||
import {
|
||||
generateSelectCSS,
|
||||
resolveSelectSlug,
|
||||
selectSetClassName,
|
||||
slugifySelectValue,
|
||||
} from '@/lib/select';
|
||||
import { generateSelectCSS, selectSetClassName, slugifySelectValue } from '@/lib/select';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export function Tabs(props: BlockProps<DocumentBlockTabs>) {
|
||||
@@ -31,7 +26,6 @@ export function Tabs(props: BlockProps<DocumentBlockTabs>) {
|
||||
return {
|
||||
id: tab.meta?.id ?? tab.key,
|
||||
title: tab.data.title ?? '',
|
||||
slug: tab.data.slug,
|
||||
icon,
|
||||
body: (
|
||||
<Blocks
|
||||
@@ -100,20 +94,19 @@ function SelectGroupStyle({ slugs }: { slugs: string[] }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a `select` slug for each tab: its explicit slug when set, else one derived from its title.
|
||||
* Untitled tabs fall back to their (stable) id so they stay selectable.
|
||||
* Derive a `select` slug for each tab from its title. Untitled tabs fall back to their (stable) id
|
||||
* so they stay selectable.
|
||||
*
|
||||
* Same-named tabs deliberately share a slug — selecting one syncs every tab of that name, here and
|
||||
* on other pages, which is the whole point of name-based selection. We don't disambiguate duplicates
|
||||
* with a positional suffix: that would desync the duplicate and make a stored selection retarget
|
||||
* whenever tabs are renamed or reordered. An explicit slug is the way out for a tab that needs to
|
||||
* keep its identity across a rename.
|
||||
* whenever tabs are renamed or reordered.
|
||||
*/
|
||||
function withSelectSlugs<T extends { id: string; title: string; slug?: string }>(
|
||||
function withSelectSlugs<T extends { id: string; title: string }>(
|
||||
items: T[]
|
||||
): (T & { slug: string })[] {
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
slug: resolveSelectSlug(item) || slugifySelectValue(item.id) || item.id,
|
||||
slug: slugifySelectValue(item.title) || slugifySelectValue(item.id) || item.id,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export function SpacesDropdown(
|
||||
id: siteSp.id,
|
||||
title: getLocalizedTitle(siteSp, currentLanguage),
|
||||
url: getSiteSpaceURL(context, siteSp),
|
||||
isActive: siteSp.id === siteSpace.id,
|
||||
path: siteSp.path,
|
||||
spaceId: siteSp.space.id,
|
||||
}));
|
||||
|
||||
@@ -46,6 +46,7 @@ export function SpacesDropdown(
|
||||
className={className}
|
||||
dropdownClassName={dropdownClassName}
|
||||
slimSpaces={slimSpaces}
|
||||
siteSpaceId={siteSpace.id}
|
||||
curPath={siteSpace.path}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
import type { IconName } from '@gitbook/icons';
|
||||
|
||||
import { useSelectedSiteSpaceId } from '../hooks';
|
||||
import { Button, type ButtonProps, ToggleChevron } from '../primitives';
|
||||
import { DropdownMenu } from '../primitives/DropdownMenu';
|
||||
import { SpacesDropdownMenuItems } from './SpacesDropdownMenuItem';
|
||||
import { SpacesDropdownMenuItems, type VariantSpace } from './SpacesDropdownMenuItem';
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
@@ -17,16 +18,16 @@ export function SpacesDropdownClient(props: {
|
||||
variant: ButtonProps['variant'];
|
||||
className?: ClassValue;
|
||||
dropdownClassName: string;
|
||||
slimSpaces: {
|
||||
id: string;
|
||||
title: string;
|
||||
url: string;
|
||||
isActive: boolean;
|
||||
spaceId: string;
|
||||
}[];
|
||||
slimSpaces: VariantSpace[];
|
||||
/** Site space the server rendered as selected, used as a fallback. */
|
||||
siteSpaceId: string;
|
||||
curPath: string;
|
||||
}) {
|
||||
const { title, icon, variant, className, dropdownClassName, slimSpaces, curPath } = props;
|
||||
const { title, icon, variant, className, dropdownClassName, slimSpaces, siteSpaceId, curPath } =
|
||||
props;
|
||||
|
||||
const selectedId = useSelectedSiteSpaceId(siteSpaceId);
|
||||
const selected = selectedId ? slimSpaces.find((space) => space.id === selectedId) : undefined;
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
@@ -40,11 +41,15 @@ export function SpacesDropdownClient(props: {
|
||||
trailing={<ToggleChevron />}
|
||||
className={tcls('bg-tint-base', className)}
|
||||
>
|
||||
<span className="button-content">{title}</span>
|
||||
<span className="button-content">{selected?.title ?? title}</span>
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<SpacesDropdownMenuItems slimSpaces={slimSpaces} curPath={curPath} />
|
||||
<SpacesDropdownMenuItems
|
||||
slimSpaces={slimSpaces}
|
||||
selectedId={selectedId}
|
||||
curPath={selected?.path ?? curPath}
|
||||
/>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ export interface VariantSpace {
|
||||
id: string;
|
||||
title: string;
|
||||
url: string;
|
||||
isActive: boolean;
|
||||
path: string;
|
||||
spaceId: string;
|
||||
}
|
||||
|
||||
@@ -66,8 +66,12 @@ export function SpacesDropdownMenuItem(props: {
|
||||
);
|
||||
}
|
||||
|
||||
export function SpacesDropdownMenuItems(props: { slimSpaces: VariantSpace[]; curPath: string }) {
|
||||
const { slimSpaces, curPath } = props;
|
||||
export function SpacesDropdownMenuItems(props: {
|
||||
slimSpaces: VariantSpace[];
|
||||
selectedId: string | null;
|
||||
curPath: string;
|
||||
}) {
|
||||
const { slimSpaces, selectedId, curPath } = props;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -75,7 +79,7 @@ export function SpacesDropdownMenuItems(props: { slimSpaces: VariantSpace[]; cur
|
||||
<SpacesDropdownMenuItem
|
||||
key={space.id}
|
||||
variantSpace={space}
|
||||
active={space.isActive}
|
||||
active={space.id === selectedId}
|
||||
currentSpacePath={curPath}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -123,9 +123,12 @@ export async function PageHeader(props: {
|
||||
id: siteSpace.id,
|
||||
title: getLocalizedTitle(siteSpace, context.locale),
|
||||
url: getSiteSpaceURL(context, siteSpace),
|
||||
isActive: siteSpace.id === currentSiteSpace.id,
|
||||
path: siteSpace.path,
|
||||
spaceId: siteSpace.space.id,
|
||||
})),
|
||||
// The breadcrumbs are rendered with the page's own context, so the selection is
|
||||
// accurate here and doesn't need the client-side patching the shared shell does.
|
||||
selectedId: currentSiteSpace.id,
|
||||
curPath: currentSiteSpace.path,
|
||||
},
|
||||
});
|
||||
@@ -329,7 +332,7 @@ type BreadcrumbContextCrumb = {
|
||||
* Present only for the variant crumb: the header's variant switcher data, whose dropdown entries
|
||||
* resolve to the current page in each variant. Rendered instead of `siblings`.
|
||||
*/
|
||||
variantSwitcher?: { slimSpaces: VariantSpace[]; curPath: string };
|
||||
variantSwitcher?: { slimSpaces: VariantSpace[]; selectedId: string; curPath: string };
|
||||
};
|
||||
|
||||
/** Render a context crumb (section group / section / variant) with its sibling dropdown. */
|
||||
@@ -345,6 +348,7 @@ function ContextCrumb({ crumb }: { crumb: BreadcrumbContextCrumb }) {
|
||||
{crumb.variantSwitcher ? (
|
||||
<SpacesDropdownMenuItems
|
||||
slimSpaces={crumb.variantSwitcher.slimSpaces}
|
||||
selectedId={crumb.variantSwitcher.selectedId}
|
||||
curPath={crumb.variantSwitcher.curPath}
|
||||
/>
|
||||
) : undefined}
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
import './globals.css';
|
||||
import { getContentLocale, getSpaceLanguage } from '@/intl/server';
|
||||
import { getAssetURL } from '@/lib/assets';
|
||||
import type { GitBookAnyContext } from '@/lib/context';
|
||||
import type { GitBookAnyContext, GitBookSiteScopeContext } from '@/lib/context';
|
||||
import { GITBOOK_FONTS_URL, GITBOOK_ICONS_TOKEN, GITBOOK_ICONS_URL } from '@/lib/env';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
@@ -73,7 +73,7 @@ export async function CustomizationRootLayout(props: {
|
||||
/** The class name to apply to the body element. */
|
||||
bodyClassName?: string;
|
||||
forcedTheme?: CustomizationDefaultThemeMode | null;
|
||||
context: GitBookAnyContext;
|
||||
context: GitBookAnyContext | GitBookSiteScopeContext;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { htmlClassName, bodyClassName, context, forcedTheme, children } = props;
|
||||
@@ -111,12 +111,15 @@ export async function CustomizationRootLayout(props: {
|
||||
preloadFont(headingFontData);
|
||||
}
|
||||
const iconStyle = getCustomizationIconStyle(customization);
|
||||
// A site scope context has no revision: its page and tag icons are provided further down the
|
||||
// tree, by a component that resolves the revision under its own cache scope.
|
||||
const revision = 'revision' in context ? context.revision : null;
|
||||
const iconSources = await getInlineIconSources([
|
||||
...getDefaultInlineIconSourceRequests(iconStyle),
|
||||
...getContentInlineIconSourceRequests({
|
||||
iconStyle,
|
||||
pages: context.revision.pages,
|
||||
tags: context.revision.tags,
|
||||
pages: revision?.pages,
|
||||
tags: revision?.tags,
|
||||
sections:
|
||||
'sections' in context
|
||||
? [...(context.sections?.list ?? []), ...(context.visibleSections?.list ?? [])]
|
||||
|
||||
@@ -16,10 +16,18 @@ import { SearchInput } from './SearchInput';
|
||||
import { SearchLiveResultsAnnouncer } from './SearchLiveResultsAnnouncer';
|
||||
import { SearchScopeControl } from './SearchScopeControl';
|
||||
import { useSearchController } from './useSearchController';
|
||||
import { useSearchPopupFocusTrap } from './useSearchPopupFocusTrap';
|
||||
import { t, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
const SEARCH_POPUP_FOCUSABLE_SELECTOR = [
|
||||
'a[href]:not([aria-disabled="true"])',
|
||||
'button:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
const SearchFrame = dynamic(() => import('./SearchFrame').then((mod) => mod.SearchFrame), {
|
||||
ssr: false,
|
||||
});
|
||||
@@ -136,7 +144,54 @@ export function SearchContainer({
|
||||
? Boolean(state?.open || state?.query || wasSearchOpened)
|
||||
: Boolean(state?.query || withAI);
|
||||
|
||||
useSearchPopupFocusTrap({ close, searchInputRef, searchPopup, usesSideSheet });
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
usesSideSheet ||
|
||||
!isSearchOpen ||
|
||||
!shouldShowSearchFrame ||
|
||||
!searchInputRef.current ||
|
||||
!searchPopup
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const searchInput = searchInputRef.current.querySelector<HTMLElement>(
|
||||
'[data-testid="search-input"]'
|
||||
);
|
||||
if (!searchInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Tab') {
|
||||
return;
|
||||
}
|
||||
|
||||
const popupControls = Array.from(
|
||||
searchPopup.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
|
||||
).filter((element) => element.getClientRects().length > 0);
|
||||
const focusableElements = [searchInput, ...popupControls];
|
||||
const currentIndex = focusableElements.indexOf(document.activeElement as HTMLElement);
|
||||
const nextIndex =
|
||||
currentIndex === -1
|
||||
? event.shiftKey
|
||||
? focusableElements.length - 1
|
||||
: 0
|
||||
: event.shiftKey
|
||||
? currentIndex - 1
|
||||
: currentIndex + 1;
|
||||
const wrappedIndex = (nextIndex + focusableElements.length) % focusableElements.length;
|
||||
|
||||
event.preventDefault();
|
||||
focusableElements[wrappedIndex]?.focus();
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown, true);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown, true);
|
||||
};
|
||||
}, [isSearchOpen, searchPopup, shouldShowSearchFrame, usesSideSheet]);
|
||||
|
||||
const scopeControlNode =
|
||||
searchProps.withVariants || searchProps.withSections ? (
|
||||
|
||||
@@ -5,7 +5,6 @@ import { motion } from 'framer-motion';
|
||||
import React from 'react';
|
||||
|
||||
import { Button, SkeletonParagraph, SkeletonSmall } from '../primitives';
|
||||
import { isExternalLink } from '../utils/link';
|
||||
import { addRecentSearchQuery } from './recent-queries';
|
||||
import { SearchPageResultItem } from './SearchPageResultItem';
|
||||
import { SearchQuestionResultItem } from './SearchQuestionResultItem';
|
||||
@@ -219,16 +218,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
addRecentSearchQuery(siteSpaceId, query, 'search');
|
||||
}
|
||||
|
||||
// The popover's focus manager re-focuses the popup when the focused
|
||||
// result is torn down during close (base-ui `restoreFocus`), and that
|
||||
// focus() scrolls the popup — anchored at the top of the page — into
|
||||
// view, undoing the scroll to the section the result linked to.
|
||||
// A click that opens elsewhere leaves the search open, and keyboard
|
||||
// users should keep their place in it.
|
||||
if (navigatesCurrentWindow(event)) {
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
|
||||
onResultSelect?.();
|
||||
};
|
||||
const resultItemProps = {
|
||||
@@ -396,19 +385,3 @@ const SearchResultsSkeleton = (props: { items: number }) => {
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether clicking a result navigates the current window, and so closes the search — as opposed
|
||||
* to opening a new tab or window (modifier keys, `target="_blank"`, or an external destination,
|
||||
* which an embed opens in a new tab).
|
||||
*/
|
||||
function navigatesCurrentWindow(event: React.MouseEvent<HTMLAnchorElement>) {
|
||||
const link = event.currentTarget;
|
||||
return (
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
link.target !== '_blank' &&
|
||||
!isExternalLink(link.href, window.location.origin)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
const SEARCH_POPUP_FOCUSABLE_SELECTOR = [
|
||||
'a[href]:not([aria-disabled="true"])',
|
||||
'button:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
/**
|
||||
* Traps Tab/Shift+Tab within the search input and its popup while it's open, and hands focus
|
||||
* off to the adjacent page element once the trap's boundary is reached.
|
||||
*/
|
||||
export function useSearchPopupFocusTrap({
|
||||
close,
|
||||
searchInputRef,
|
||||
searchPopup,
|
||||
usesSideSheet,
|
||||
}: {
|
||||
close: () => void;
|
||||
searchInputRef: React.RefObject<HTMLDivElement | null>;
|
||||
searchPopup: HTMLDivElement | null;
|
||||
usesSideSheet: boolean;
|
||||
}) {
|
||||
React.useEffect(() => {
|
||||
if (usesSideSheet || !searchInputRef.current || !searchPopup) {
|
||||
return;
|
||||
}
|
||||
|
||||
const searchInput = searchInputRef.current.querySelector<HTMLElement>(
|
||||
'[data-testid="search-input"]'
|
||||
);
|
||||
if (!searchInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Finds the next (or previous) focusable element in real document order,
|
||||
// skipping the popup's own content as well as Base UI's internal focus-guard
|
||||
// sentinels — both live in a portal, so their DOM position doesn't match their
|
||||
// visual position after the search input, and would otherwise re-trap focus.
|
||||
const findAdjacentPageElement = (direction: 'next' | 'previous') => {
|
||||
const step = direction === 'next' ? 1 : -1;
|
||||
const pageFocusable = Array.from(
|
||||
document.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
|
||||
).filter(
|
||||
(element) =>
|
||||
element.getClientRects().length > 0 &&
|
||||
!element.closest('[data-base-ui-portal], [data-base-ui-focus-guard]')
|
||||
);
|
||||
return pageFocusable[pageFocusable.indexOf(searchInput) + step];
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Tab') {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeElement = document.activeElement as HTMLElement | null;
|
||||
// Whether or not the popover ever visibly opened, Base UI still keeps a pair
|
||||
// of hidden, tabbable focus-guard nodes mounted in its portal — reachable by
|
||||
// Tab regardless of open state, and otherwise a dead end.
|
||||
const isOnOwnFocusGuard = Boolean(
|
||||
activeElement?.hasAttribute('data-base-ui-focus-guard') &&
|
||||
searchPopup.closest('[data-base-ui-portal]')?.contains(activeElement)
|
||||
);
|
||||
|
||||
const popupControls = Array.from(
|
||||
searchPopup.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
|
||||
).filter((element) => element.getClientRects().length > 0);
|
||||
const focusableElements = [searchInput, ...popupControls];
|
||||
const currentIndex = focusableElements.indexOf(activeElement as HTMLElement);
|
||||
|
||||
if (currentIndex === -1 && !isOnOwnFocusGuard) {
|
||||
// Focus isn't within the search widget — leave native Tab handling alone.
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.shiftKey && currentIndex === 0) {
|
||||
// Search input is a regular DOM node, so the browser's native Shift+Tab
|
||||
// already moves focus to whatever precedes it once we close the popover.
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.shiftKey && (isOnOwnFocusGuard || currentIndex === -1)) {
|
||||
event.preventDefault();
|
||||
close();
|
||||
findAdjacentPageElement('previous')?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!event.shiftKey &&
|
||||
(isOnOwnFocusGuard || currentIndex === focusableElements.length - 1)
|
||||
) {
|
||||
event.preventDefault();
|
||||
close();
|
||||
findAdjacentPageElement('next')?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const nextIndex = event.shiftKey ? currentIndex - 1 : currentIndex + 1;
|
||||
event.preventDefault();
|
||||
focusableElements[nextIndex]?.focus();
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown, true);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown, true);
|
||||
};
|
||||
}, [close, searchPopup, usesSideSheet]);
|
||||
}
|
||||
@@ -5,13 +5,18 @@ import { useCallback, useSyncExternalStore } from 'react';
|
||||
import { selectStore } from '@/lib/select';
|
||||
|
||||
/**
|
||||
* Setters for the site-wide `select` state. Deliberately does not subscribe: the store notifies on
|
||||
* every activation anywhere on the page, so returning the recency list here would re-render every
|
||||
* block that only ever wanted to *write* a selection. To read one, use {@link useResolvedSlug},
|
||||
* which re-renders a block only when its own resolved option changes.
|
||||
* Subscribe to the site-wide `select` state. Returns the current recency list plus the setters.
|
||||
* Consumers that only need "which of my options is active" should prefer {@link useResolvedSlug}.
|
||||
*/
|
||||
export function useSelect() {
|
||||
const slugs = useSyncExternalStore(
|
||||
selectStore.subscribe,
|
||||
selectStore.getState,
|
||||
selectStore.getState
|
||||
).slugs;
|
||||
|
||||
return {
|
||||
slugs,
|
||||
activate: selectStore.activate,
|
||||
deactivate: selectStore.deactivate,
|
||||
};
|
||||
|
||||
@@ -3,19 +3,20 @@ import Script from 'next/script';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
|
||||
import { CustomizationDefaultThemeMode } from '@gitbook/api';
|
||||
|
||||
import { AIContextProvider } from '../AI';
|
||||
import { Announcement } from '../Announcement';
|
||||
import { RocketLoaderDetector } from './RocketLoaderDetector';
|
||||
import { SiteLayoutClientContexts } from './SiteLayoutClientContexts';
|
||||
import { AdminToolbar } from '@/components/AdminToolbar';
|
||||
import { CookiesToast } from '@/components/Cookies';
|
||||
import { Footer } from '@/components/Footer';
|
||||
import { LoadIntegrations } from '@/components/Integrations';
|
||||
import { SpaceLayout } from '@/components/SpaceLayout';
|
||||
import { WebMCP } from '@/components/WebMCP/WebMCP';
|
||||
import { SpaceHeader, SpaceLayout, SpaceTableOfContents } from '@/components/SpaceLayout';
|
||||
import type { VisitorAuthClaims } from '@/lib/adaptive';
|
||||
import { buildVersion } from '@/lib/build';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import type { GitBookSiteContext, GitBookSiteScopeContext } from '@/lib/context';
|
||||
import { GITBOOK_API_PUBLIC_URL, GITBOOK_ASSETS_URL, GITBOOK_ICONS_URL } from '@/lib/env';
|
||||
import { getResizedImageURL } from '@/lib/images';
|
||||
import { isSiteIndexable } from '@/lib/seo';
|
||||
@@ -46,16 +47,67 @@ function isDeferrableScript(script: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Layout when rendering a site.
|
||||
* Parts of the layout that can only be rendered from a full site context, as they read the
|
||||
* revision. A site scope context has to provide them itself.
|
||||
*/
|
||||
export async function SiteLayout(props: {
|
||||
context: GitBookSiteContext;
|
||||
export type SiteLayoutSlots = {
|
||||
announcement: React.ReactNode;
|
||||
header: React.ReactNode;
|
||||
tableOfContents: React.ReactNode;
|
||||
footer: React.ReactNode;
|
||||
adminToolbar: React.ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Build the default slots of the layout from a full site context.
|
||||
*/
|
||||
export function getSiteLayoutSlots(context: GitBookSiteContext): SiteLayoutSlots {
|
||||
return {
|
||||
announcement: <Announcement context={context} />,
|
||||
header: <SpaceHeader context={context} />,
|
||||
tableOfContents: <SpaceTableOfContents context={context} />,
|
||||
footer: <Footer context={context} />,
|
||||
adminToolbar: <AdminToolbar context={context} />,
|
||||
};
|
||||
}
|
||||
|
||||
type SiteLayoutProps = {
|
||||
forcedTheme?: CustomizationDefaultThemeMode | null;
|
||||
withTracking: boolean;
|
||||
visitorAuthClaims: VisitorAuthClaims;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { context, forcedTheme, withTracking, visitorAuthClaims, children } = props;
|
||||
clientNavigationSelection?: boolean;
|
||||
} & (
|
||||
| {
|
||||
context: GitBookSiteContext;
|
||||
/** Overrides of the slots that would otherwise be rendered from the context. */
|
||||
slots?: Partial<SiteLayoutSlots>;
|
||||
}
|
||||
| {
|
||||
context: GitBookSiteScopeContext;
|
||||
/** A site scope context can't render any of them, so they are all required. */
|
||||
slots: SiteLayoutSlots;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Layout when rendering a site.
|
||||
*/
|
||||
export async function SiteLayout(props: SiteLayoutProps) {
|
||||
const {
|
||||
context,
|
||||
forcedTheme,
|
||||
withTracking,
|
||||
visitorAuthClaims,
|
||||
children,
|
||||
clientNavigationSelection,
|
||||
} = props;
|
||||
|
||||
// The prop type guarantees `slots` is complete whenever the context can't build them itself.
|
||||
const slots = {
|
||||
...('revision' in context ? getSiteLayoutSlots(context) : null),
|
||||
...props.slots,
|
||||
} as SiteLayoutSlots;
|
||||
|
||||
const { customization } = context;
|
||||
const { ai } = customization;
|
||||
@@ -112,15 +164,17 @@ export async function SiteLayout(props: {
|
||||
context={context}
|
||||
withTracking={withTracking}
|
||||
visitorAuthClaims={visitorAuthClaims}
|
||||
announcementSlot={slots.announcement}
|
||||
headerSlot={slots.header}
|
||||
tableOfContentsSlot={slots.tableOfContents}
|
||||
footerSlot={slots.footer}
|
||||
clientNavigationSelection={clientNavigationSelection}
|
||||
>
|
||||
{children}
|
||||
</SpaceLayout>
|
||||
</AIContextProvider>
|
||||
|
||||
<LoadIntegrations />
|
||||
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
|
||||
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
|
||||
) : null}
|
||||
{scripts.map(({ script }) =>
|
||||
isDeferrableScript(script) ? (
|
||||
<Script key={script} src={script} strategy="lazyOnload" />
|
||||
@@ -137,12 +191,14 @@ export async function SiteLayout(props: {
|
||||
|
||||
<RocketLoaderDetector />
|
||||
|
||||
<AdminToolbar context={context} />
|
||||
{slots.adminToolbar}
|
||||
</SiteLayoutClientContexts>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateSiteLayoutViewport(context: GitBookSiteContext): Promise<Viewport> {
|
||||
export async function generateSiteLayoutViewport(
|
||||
context: GitBookSiteContext | GitBookSiteScopeContext
|
||||
): Promise<Viewport> {
|
||||
const { customization } = context;
|
||||
return {
|
||||
colorScheme: customization.themes.toggeable
|
||||
@@ -160,7 +216,9 @@ export async function generateSiteLayoutViewport(context: GitBookSiteContext): P
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateSiteLayoutMetadata(context: GitBookSiteContext): Promise<Metadata> {
|
||||
export async function generateSiteLayoutMetadata(
|
||||
context: GitBookSiteContext | GitBookSiteScopeContext
|
||||
): Promise<Metadata> {
|
||||
const { site, customization, linker, imageResizer } = context;
|
||||
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : null;
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import { cacheLife } from 'next/cache';
|
||||
|
||||
import { IconsProvider } from '@gitbook/icons';
|
||||
|
||||
import { SitePage, generateSitePageMetadata, generateSitePageViewport } from './SitePage';
|
||||
import {
|
||||
type RouteLayoutParams,
|
||||
type RouteParams,
|
||||
getPPRStaticSiteContext,
|
||||
getPagePathFromParams,
|
||||
} from '@/app/utils';
|
||||
import { AdminToolbar } from '@/components/AdminToolbar';
|
||||
import { Announcement } from '@/components/Announcement';
|
||||
import { Footer } from '@/components/Footer';
|
||||
import { SpaceHeader, SpaceTableOfContents } from '@/components/SpaceLayout';
|
||||
import {
|
||||
getContentInlineIconSourceRequests,
|
||||
getCustomizationIconStyle,
|
||||
getInlineIconSources,
|
||||
} from '@/lib/icons/inline';
|
||||
|
||||
// Each component below resolves its context under its own PPR cache scope. The scope is part of the
|
||||
// cache key of every data fetcher, so the tags they emit are scoped too and propagate up to the
|
||||
// entry here — making the component and the data it read a single revalidatable unit. No explicit
|
||||
// `cacheTag` is needed, and adding one would only duplicate a propagated tag.
|
||||
|
||||
/**
|
||||
* Render the header from cache without carrying a request-scoped data fetcher into the cache key.
|
||||
*/
|
||||
export async function PPRHeader(props: { params: RouteLayoutParams }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'header');
|
||||
|
||||
return <SpaceHeader context={context} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the table of contents independently so navigation changes do not invalidate the header.
|
||||
*/
|
||||
export async function PPRTableOfContents(props: { params: RouteLayoutParams }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'toc');
|
||||
|
||||
return <SpaceTableOfContents context={context} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the announcement banner, which resolves its link against the revision.
|
||||
*/
|
||||
export async function PPRAnnouncement(props: { params: RouteLayoutParams }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'toc');
|
||||
|
||||
return <Announcement context={context} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the footer, whose links resolve against the revision.
|
||||
*/
|
||||
export async function PPRFooter(props: { params: RouteLayoutParams }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'toc');
|
||||
|
||||
return <Footer context={context} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the admin toolbar, which reports on the revision and its change request.
|
||||
*/
|
||||
export async function PPRAdminToolbar(props: { params: RouteLayoutParams }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'toc');
|
||||
|
||||
return <AdminToolbar context={context} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide the icons of the pages and tags of the revision to the tree below.
|
||||
*
|
||||
* The header and the body both render them, so they are resolved once here rather than duplicated
|
||||
* in every per-page cache entry. The provider merges with the one of the root layout, which carries
|
||||
* the site-level icons.
|
||||
*/
|
||||
export async function PPRRevisionIconsProvider(
|
||||
props: React.PropsWithChildren<{ params: RouteLayoutParams }>
|
||||
) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'toc');
|
||||
const iconSources = await getInlineIconSources(
|
||||
getContentInlineIconSourceRequests({
|
||||
iconStyle: getCustomizationIconStyle(context.customization),
|
||||
pages: context.revision.pages,
|
||||
tags: context.revision.tags,
|
||||
})
|
||||
);
|
||||
|
||||
return <IconsProvider iconSources={iconSources}>{props.children}</IconsProvider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the page body independently from the shared navigation shell.
|
||||
*/
|
||||
export async function PPRPageBody(props: { params: RouteParams; pathname: string }) {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(props.params, 'body');
|
||||
|
||||
return <SitePage context={context} pageParams={{ pathname: props.pathname }} staticRoute />;
|
||||
}
|
||||
|
||||
export async function cachedGenerateSitePageMetadata(routeParams: RouteParams): Promise<Metadata> {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(routeParams, 'body');
|
||||
const pathname = getPagePathFromParams(routeParams);
|
||||
|
||||
return generateSitePageMetadata({ context, pageParams: { pathname } });
|
||||
}
|
||||
|
||||
export async function cachedGenerateSitePageViewport(routeParams: RouteParams): Promise<Viewport> {
|
||||
'use cache: remote';
|
||||
cacheLife('days'); // Cache for 1 day
|
||||
|
||||
const { context } = await getPPRStaticSiteContext(routeParams, 'body');
|
||||
|
||||
return generateSitePageViewport(context);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import type { PageMetaLinks } from './SitePage';
|
||||
@@ -33,6 +33,7 @@ export function PageClientLayout({ pageMetaLinks }: { pageMetaLinks: PageMetaLin
|
||||
* so we need to remove the fallback parameter.
|
||||
*/
|
||||
function useStripFallbackQueryParam() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
@@ -40,14 +41,9 @@ function useStripFallbackQueryParam() {
|
||||
if (searchParams?.has('fallback')) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete('fallback');
|
||||
const query = params.toString();
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
`${pathname}${query ? `?${query}` : ''}${window.location.hash}`
|
||||
);
|
||||
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
|
||||
}
|
||||
}, [pathname, searchParams]);
|
||||
}, [router, pathname, searchParams]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { fetchPageData } = await import('./fetch');
|
||||
|
||||
const page = {
|
||||
id: 'page-1',
|
||||
title: 'Introduction',
|
||||
kind: 'sheet',
|
||||
type: 'document',
|
||||
path: 'readme',
|
||||
slug: 'readme',
|
||||
pages: [],
|
||||
} as RevisionPageDocument;
|
||||
|
||||
const git = {
|
||||
oid: 'abc123',
|
||||
path: 'README.md',
|
||||
};
|
||||
|
||||
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
|
||||
const getRevisionPageByPath = mock(async () => ({
|
||||
data: {
|
||||
...page,
|
||||
git,
|
||||
},
|
||||
}));
|
||||
|
||||
const context = {
|
||||
revision: { pages: [page] },
|
||||
revisionId: 'revision-1',
|
||||
customization: {
|
||||
pageActions: {
|
||||
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
|
||||
},
|
||||
},
|
||||
space: {
|
||||
id: 'space-1',
|
||||
gitSync:
|
||||
options.gitSync === false
|
||||
? undefined
|
||||
: {
|
||||
url: 'https://github.com/gitbook/example/tree/main',
|
||||
},
|
||||
},
|
||||
dataFetcher: { getRevisionPageByPath },
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
return { context, getRevisionPageByPath };
|
||||
}
|
||||
|
||||
describe('fetchPageData', () => {
|
||||
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).toHaveBeenCalledWith({
|
||||
spaceId: 'space-1',
|
||||
revisionId: 'revision-1',
|
||||
path: 'readme',
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
expect(result.pageTarget?.page.git).toEqual(git);
|
||||
expect(result.context.page?.git).toEqual(git);
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata when the action is disabled', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result.pageTarget?.page.git).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not fetch Git metadata without Git Sync', async () => {
|
||||
const { context, getRevisionPageByPath } = createContext({
|
||||
gitEnabled: true,
|
||||
gitSync: false,
|
||||
});
|
||||
|
||||
const result = await fetchPageData(context, { pageId: page.id });
|
||||
|
||||
expect(getRevisionPageByPath).not.toHaveBeenCalled();
|
||||
expect(result.pageTarget?.page.git).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
} from '@gitbook/api';
|
||||
@@ -27,34 +26,7 @@ export type PageParams = PagePathParams | PageIdParams;
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
|
||||
let pageTarget = await resolvePage(context, params);
|
||||
|
||||
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
|
||||
if (
|
||||
pageTarget &&
|
||||
!pageTarget.page.git &&
|
||||
context.space.gitSync?.url &&
|
||||
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
|
||||
) {
|
||||
const response = await context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
path: pageTarget.page.path,
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
const pageWithMetadata = response.data;
|
||||
|
||||
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
|
||||
pageTarget = {
|
||||
...pageTarget,
|
||||
page: {
|
||||
...pageTarget.page,
|
||||
git: pageWithMetadata.git,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const pageTarget = await resolvePage(context, params);
|
||||
|
||||
return {
|
||||
context: {
|
||||
@@ -117,21 +89,7 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
|
||||
})
|
||||
));
|
||||
if (resolvedSiteRedirect) {
|
||||
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
|
||||
const isPublicLiveContext =
|
||||
!shareKey &&
|
||||
!context.changeRequest &&
|
||||
!context.preview &&
|
||||
context.revisionId === context.space.revision &&
|
||||
!context.isLoggedInVisitor;
|
||||
if (
|
||||
resolvedSiteRedirect.redirect?.permanent &&
|
||||
!resolvedSiteRedirect.redirect.draft &&
|
||||
isPublicLiveContext
|
||||
) {
|
||||
return permanentRedirect(destination);
|
||||
}
|
||||
return redirect(destination);
|
||||
return redirect(linker.toLinkForContent(resolvedSiteRedirect.target));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from './SitePageNotFound';
|
||||
export * from './SitePage';
|
||||
export * from './PPRSitePage';
|
||||
export * from './fetch';
|
||||
export * from './SitePageSkeleton';
|
||||
|
||||
@@ -6,12 +6,11 @@ import React from 'react';
|
||||
|
||||
import type { IconName } from '@gitbook/icons';
|
||||
|
||||
import { useToggleAnimation } from '../hooks';
|
||||
import { useSelectedSiteSectionId, useToggleAnimation } from '../hooks';
|
||||
import { Link, ToggleChevron } from '../primitives';
|
||||
import { ScrollContainer } from '../primitives/ScrollContainer';
|
||||
import type {
|
||||
ClientSiteNavigationItem,
|
||||
ClientSiteSection,
|
||||
ClientSiteSectionGroup,
|
||||
ClientSiteSections,
|
||||
} from './encodeClientSiteSections';
|
||||
@@ -30,6 +29,8 @@ export function SiteSectionList(props: { sections: ClientSiteSections; className
|
||||
className,
|
||||
} = props;
|
||||
|
||||
const currentSectionId = useSelectedSiteSectionId(currentSection.id);
|
||||
|
||||
return (
|
||||
sectionsAndGroups.length > 0 && (
|
||||
<nav
|
||||
@@ -43,7 +44,7 @@ export function SiteSectionList(props: { sections: ClientSiteSections; className
|
||||
orientation="vertical"
|
||||
style={{ maxHeight: `${MAX_ITEMS * 3 + 2}rem` }}
|
||||
className="pb-4"
|
||||
active={`#${currentSection.id}`}
|
||||
active={currentSectionId ? `#${currentSectionId}` : undefined}
|
||||
>
|
||||
<div className="flex w-full flex-col px-2">
|
||||
{sectionsAndGroups.map((item) => {
|
||||
@@ -53,7 +54,7 @@ export function SiteSectionList(props: { sections: ClientSiteSections; className
|
||||
<SiteSectionGroupItem
|
||||
key={item.id}
|
||||
group={item}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
/>
|
||||
);
|
||||
case 'site-section':
|
||||
@@ -63,7 +64,7 @@ export function SiteSectionList(props: { sections: ClientSiteSections; className
|
||||
item={item}
|
||||
isActive={
|
||||
item.object === 'site-section' &&
|
||||
item.id === currentSection.id
|
||||
item.id === currentSectionId
|
||||
}
|
||||
key={item.id}
|
||||
/>
|
||||
@@ -139,13 +140,14 @@ export function SiteSectionListItem(props: {
|
||||
|
||||
export function SiteSectionGroupItem(props: {
|
||||
group: ClientSiteSectionGroup;
|
||||
currentSection: ClientSiteSection;
|
||||
currentSectionId: string | null;
|
||||
level?: number;
|
||||
}) {
|
||||
const { group, currentSection, level = 0 } = props;
|
||||
const { group, currentSectionId, level = 0 } = props;
|
||||
|
||||
const hasDescendants = group.children.length > 0;
|
||||
const isActiveGroup = Boolean(findSectionInGroup(group, currentSection.id));
|
||||
const isActiveGroup =
|
||||
currentSectionId !== null && Boolean(findSectionInGroup(group, currentSectionId));
|
||||
const shouldOpen = hasDescendants && isActiveGroup;
|
||||
const [isOpen, setIsOpen] = React.useState(shouldOpen);
|
||||
|
||||
@@ -236,7 +238,7 @@ export function SiteSectionGroupItem(props: {
|
||||
item={child}
|
||||
isActive={
|
||||
child.object === 'site-section' &&
|
||||
child.id === currentSection.id
|
||||
child.id === currentSectionId
|
||||
}
|
||||
key={child.id}
|
||||
/>
|
||||
@@ -245,7 +247,7 @@ export function SiteSectionGroupItem(props: {
|
||||
return (
|
||||
<SiteSectionGroupItem
|
||||
group={child}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
key={child.id}
|
||||
level={level + 1}
|
||||
/>
|
||||
|
||||
@@ -5,13 +5,10 @@ import React from 'react';
|
||||
|
||||
import type { IconName } from '@gitbook/icons';
|
||||
|
||||
import { useSelectedSiteSectionId } from '../hooks';
|
||||
import { CONTAINER_STYLE } from '../layout';
|
||||
import { ScrollContainer } from '../primitives/ScrollContainer';
|
||||
import type {
|
||||
ClientSiteSection,
|
||||
ClientSiteSections,
|
||||
ClientSiteStructureNode,
|
||||
} from './encodeClientSiteSections';
|
||||
import type { ClientSiteSections, ClientSiteStructureNode } from './encodeClientSiteSections';
|
||||
import { SectionIcon } from './SectionIcon';
|
||||
import { Button, Link, ToggleChevron } from '@/components/primitives';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -47,6 +44,8 @@ export function SiteSectionTabs(props: {
|
||||
children,
|
||||
} = props;
|
||||
|
||||
const currentSectionId = useSelectedSiteSectionId(currentSection.id);
|
||||
|
||||
// Portalled into the tabs container rather than <body>, to keep inheriting the header's theming.
|
||||
const containerRef = React.useRef<HTMLElement>(null);
|
||||
|
||||
@@ -79,7 +78,7 @@ export function SiteSectionTabs(props: {
|
||||
? 'md:-mr-8 -mr-4 sm:-mr-6'
|
||||
: 'after:contents[] after:absolute after:inset-y-2 after:right-0 after:border-transparent after:border-r after:transition-colors'
|
||||
)}
|
||||
active={`#${currentSection.id}`}
|
||||
active={currentSectionId ? `#${currentSectionId}` : undefined}
|
||||
trailing={{
|
||||
fade: true,
|
||||
button: true,
|
||||
@@ -100,10 +99,11 @@ export function SiteSectionTabs(props: {
|
||||
const isGroup = structureItem.object === 'site-section-group';
|
||||
const isActiveGroup =
|
||||
isGroup &&
|
||||
Boolean(findSectionInGroup(structureItem, currentSection.id));
|
||||
currentSectionId !== null &&
|
||||
Boolean(findSectionInGroup(structureItem, currentSectionId));
|
||||
const isActive =
|
||||
isActiveGroup ||
|
||||
(structureItem.object === 'site-section' && id === currentSection.id);
|
||||
(structureItem.object === 'site-section' && id === currentSectionId);
|
||||
return (
|
||||
<NavigationMenu.Item key={id} value={id} id={id}>
|
||||
{isGroup && structureItem.children.length > 0 ? (
|
||||
@@ -129,7 +129,7 @@ export function SiteSectionTabs(props: {
|
||||
>
|
||||
<SectionGroupTileList
|
||||
items={structureItem.children}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
/>
|
||||
</NavigationMenu.Content>
|
||||
</>
|
||||
@@ -227,9 +227,9 @@ const SectionTab = React.forwardRef(function SectionTab(
|
||||
*/
|
||||
function SectionGroupTileList(props: {
|
||||
items: ClientSiteStructureNode[];
|
||||
currentSection: ClientSiteSection;
|
||||
currentSectionId: string | null;
|
||||
}) {
|
||||
const { items, currentSection } = props;
|
||||
const { items, currentSectionId } = props;
|
||||
|
||||
// Separate navigable items (sections, external links) from grouped items.
|
||||
const navigableItems = items.filter((item) => item.object !== 'site-section-group');
|
||||
@@ -269,7 +269,7 @@ function SectionGroupTileList(props: {
|
||||
<SectionGroupTile
|
||||
key={item.id}
|
||||
child={item}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
invertIcon={navigableItemsRecessed}
|
||||
/>
|
||||
))}
|
||||
@@ -309,7 +309,7 @@ function SectionGroupTileList(props: {
|
||||
<SectionGroupTile
|
||||
key={group.id}
|
||||
child={group}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
isMasonry={isMasonryLayout}
|
||||
invertIcon={groupsRecessed}
|
||||
/>
|
||||
@@ -340,16 +340,16 @@ function SectionGroupTileList(props: {
|
||||
*/
|
||||
function SectionGroupTile(props: {
|
||||
child: ClientSiteStructureNode;
|
||||
currentSection: ClientSiteSection;
|
||||
currentSectionId: string | null;
|
||||
invertIcon?: boolean;
|
||||
/** Whether the tile is a top-level group of the dropdown's masonry layout. */
|
||||
isMasonry?: boolean;
|
||||
}) {
|
||||
const { child, currentSection, invertIcon, isMasonry } = props;
|
||||
const { child, currentSectionId, invertIcon, isMasonry } = props;
|
||||
|
||||
if (child.object !== 'site-section-group') {
|
||||
const { url, icon, title, description } = child;
|
||||
const isActive = child.object === 'site-section' && child.id === currentSection.id;
|
||||
const isActive = child.object === 'site-section' && child.id === currentSectionId;
|
||||
return (
|
||||
<li className="group/section-tile flex w-full min-w-0 shrink-0 grow md:max-w-[var(--site-section-tile-max-width)]">
|
||||
<Link
|
||||
@@ -429,7 +429,7 @@ function SectionGroupTile(props: {
|
||||
<SectionGroupTile
|
||||
key={nestedChild.id}
|
||||
child={nestedChild}
|
||||
currentSection={currentSection}
|
||||
currentSectionId={currentSectionId}
|
||||
invertIcon={invertIcon}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -6,9 +6,8 @@ import { AdaptiveVisitorContextProvider } from '../Adaptive';
|
||||
import { AIChatProvider } from '../AI';
|
||||
import type { RenderAIMessageOptions } from '../AI';
|
||||
import { AIChat, AskAITextSelection } from '../AIChat';
|
||||
import { Announcement } from '../Announcement';
|
||||
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
|
||||
import { CurrentContentProvider } from '../hooks';
|
||||
import { ClientNavigationSelectionProvider, CurrentContentProvider } from '../hooks';
|
||||
import { InsightsProvider, VisitorProvider } from '../Insights';
|
||||
import { CONTAINER_STYLE } from '../layout';
|
||||
import { NavigationLoader } from '../primitives/NavigationLoader';
|
||||
@@ -20,17 +19,16 @@ import {
|
||||
} from '../SiteSections';
|
||||
import { categorizeVariants } from './categorizeVariants';
|
||||
import { SpaceLayoutContextProvider } from './SpaceLayoutContext';
|
||||
import { Footer } from '@/components/Footer';
|
||||
import { Header, HeaderLogo } from '@/components/Header';
|
||||
import { TableOfContents } from '@/components/TableOfContents';
|
||||
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
|
||||
import type { VisitorAuthClaims } from '@/lib/adaptive';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import type { GitBookSiteContext, GitBookSiteScopeContext } from '@/lib/context';
|
||||
import { GITBOOK_APP_URL } from '@/lib/env';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
type SpaceLayoutProps = {
|
||||
context: GitBookSiteContext;
|
||||
context: GitBookSiteScopeContext;
|
||||
|
||||
/** Whether to enable tracking of events into site insights. */
|
||||
withTracking: boolean;
|
||||
@@ -43,14 +41,41 @@ type SpaceLayoutProps = {
|
||||
|
||||
/** The children of the layout. */
|
||||
children: React.ReactNode;
|
||||
|
||||
// The slots below all read the revision, which a site scope context doesn't carry, so they are
|
||||
// rendered by the caller rather than from `context`.
|
||||
|
||||
/** Announcement banner, rendered above the header. */
|
||||
announcementSlot?: React.ReactNode;
|
||||
|
||||
/** Site header. */
|
||||
headerSlot?: React.ReactNode;
|
||||
|
||||
/** Table of contents. */
|
||||
tableOfContentsSlot?: React.ReactNode;
|
||||
|
||||
/** Site footer, rendered only when the customization asks for one. */
|
||||
footerSlot?: React.ReactNode;
|
||||
|
||||
/**
|
||||
* Resolve the selected section/space/page on the client instead of trusting the server render.
|
||||
* Set when the navigation shell comes from a cache shared across pages (PPR).
|
||||
*/
|
||||
clientNavigationSelection?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Provide all contexts for a space.
|
||||
*/
|
||||
export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
const { context, withTracking, visitorAuthClaims, aiChatRenderMessageOptions, children } =
|
||||
props;
|
||||
const {
|
||||
context,
|
||||
withTracking,
|
||||
visitorAuthClaims,
|
||||
aiChatRenderMessageOptions,
|
||||
clientNavigationSelection = false,
|
||||
children,
|
||||
} = props;
|
||||
|
||||
const { customization } = context;
|
||||
const siteAdaptiveAuthLoginHref =
|
||||
@@ -58,15 +83,15 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
? context.linker.toPathInSite('~gitbook/auth/login')
|
||||
: null;
|
||||
|
||||
// Kept relative: a prerendered page has no request to read the host from, so an absolute URL
|
||||
// pins the configured host and turns these fetches cross-origin when it differs (apex vs www).
|
||||
const eventParams = new URLSearchParams({
|
||||
o: context.organizationId,
|
||||
s: context.site.id,
|
||||
});
|
||||
const eventUrl = `${context.linker.toPathInSite('/~gitbook/__evt')}?${eventParams}`;
|
||||
const eventUrl = new URL(
|
||||
context.linker.toAbsoluteURL(context.linker.toPathInSite('/~gitbook/__evt'))
|
||||
);
|
||||
eventUrl.searchParams.set('o', context.organizationId);
|
||||
eventUrl.searchParams.set('s', context.site.id);
|
||||
|
||||
const getVisitorClaimsUrl = context.linker.toPathInSite('/~gitbook/visitor');
|
||||
const getVisitorClaimsUrl = context.linker.toAbsoluteURL(
|
||||
context.linker.toPathInSite('/~gitbook/visitor')
|
||||
);
|
||||
|
||||
return (
|
||||
<SpaceLayoutContextProvider
|
||||
@@ -84,7 +109,7 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
siteSectionId={context.sections?.current?.id ?? null}
|
||||
siteSpaceId={context.siteSpace.id}
|
||||
siteShareKey={context.shareKey ?? null}
|
||||
spaceId={context.space.id}
|
||||
spaceId={context.siteSpace.space.id}
|
||||
revisionId={context.revisionId}
|
||||
visitorAuthClaims={visitorAuthClaims}
|
||||
>
|
||||
@@ -92,12 +117,16 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
appURL={GITBOOK_APP_URL}
|
||||
visitorCookieTrackingEnabled={customization.insights?.trackingCookie}
|
||||
>
|
||||
<InsightsProvider enabled={withTracking} eventUrl={eventUrl}>
|
||||
<InsightsProvider enabled={withTracking} eventUrl={eventUrl.toString()}>
|
||||
<AIChatProvider
|
||||
renderMessageOptions={aiChatRenderMessageOptions}
|
||||
withPageFeedback={customization.feedback.enabled}
|
||||
>
|
||||
{children}
|
||||
<ClientNavigationSelectionProvider
|
||||
enabled={clientNavigationSelection}
|
||||
>
|
||||
{children}
|
||||
</ClientNavigationSelectionProvider>
|
||||
</AIChatProvider>
|
||||
</InsightsProvider>
|
||||
</VisitorProvider>
|
||||
@@ -107,17 +136,118 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the site header from a site context.
|
||||
*/
|
||||
export function SpaceHeader(props: { context: GitBookSiteContext }) {
|
||||
const { context } = props;
|
||||
const withTopHeader = context.customization.header.preset !== CustomizationHeaderPreset.None;
|
||||
|
||||
return (
|
||||
<Header
|
||||
withTopHeader={withTopHeader}
|
||||
variants={categorizeVariants(context)}
|
||||
context={context}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the table of contents and its site-specific controls from a site context.
|
||||
*/
|
||||
export function SpaceTableOfContents(props: { context: GitBookSiteContext }) {
|
||||
const { context } = props;
|
||||
const { siteSpace, customization, visibleSections } = context;
|
||||
const searchProps = getSearchBaseProps(context);
|
||||
const withTopHeader = customization.header.preset !== CustomizationHeaderPreset.None;
|
||||
const withSections = shouldRenderSiteSectionNavigation(visibleSections);
|
||||
const variants = categorizeVariants(context);
|
||||
|
||||
return (
|
||||
<TableOfContents
|
||||
context={context}
|
||||
header={
|
||||
<div
|
||||
className={tcls(
|
||||
'pr-4',
|
||||
'flex',
|
||||
withTopHeader ? 'lg:hidden' : '',
|
||||
'grow-0',
|
||||
'dark:shadow-light/1',
|
||||
'text-base/tight',
|
||||
'items-center',
|
||||
// On bold themes also color the TOC header so the logo looks correct.
|
||||
'site-header:theme-bold:bg-header-background',
|
||||
'site-header:theme-bold:m-[-1.5rem_-1px_-0.5rem_-2rem]',
|
||||
'site-header:theme-bold:p-[1rem_1rem_1rem_2rem]'
|
||||
)}
|
||||
>
|
||||
<HeaderLogo context={context} />
|
||||
{variants.translations.length > 1 ? (
|
||||
<TranslationsDropdown
|
||||
context={context}
|
||||
siteSpace={
|
||||
variants.translations.find((space) => space.id === siteSpace.id) ??
|
||||
siteSpace
|
||||
}
|
||||
siteSpaces={variants.translations}
|
||||
className="[&_.button-leading-icon]:block! ml-auto py-2 [&_.button-content]:hidden"
|
||||
variant="header"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
// Displays the search button and/or the space dropdown in the ToC
|
||||
// according to the header/variant settings.
|
||||
// E.g if there is no header, the search button will be displayed in the ToC.
|
||||
innerHeader={
|
||||
!withTopHeader || variants.generic.length > 1 ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'my-5 sidebar-default:mt-2 flex flex-col gap-2 px-5 empty:hidden',
|
||||
variants.generic.length > 1 ? '' : 'max-lg:hidden'
|
||||
)}
|
||||
>
|
||||
{!withTopHeader && (
|
||||
<div className="flex gap-2 max-lg:hidden">
|
||||
<SearchContainer
|
||||
{...searchProps}
|
||||
style={CustomizationSearchStyle.Subtle}
|
||||
viewport="desktop"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!withTopHeader && withSections && visibleSections && (
|
||||
<SiteSectionList
|
||||
className="hidden lg:block"
|
||||
sections={encodeClientSiteSections(context, visibleSections)}
|
||||
/>
|
||||
)}
|
||||
{variants.generic.length > 1 ? (
|
||||
<SpacesDropdown
|
||||
context={context}
|
||||
siteSpace={siteSpace}
|
||||
siteSpaces={variants.generic}
|
||||
className="w-full px-3"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the entire layout of the space (header, table of contents, footer).
|
||||
*/
|
||||
export function SpaceLayout(props: SpaceLayoutProps) {
|
||||
const { context, children } = props;
|
||||
const { siteSpace, customization, visibleSections } = context;
|
||||
const searchProps = getSearchBaseProps(context);
|
||||
const { context, children, headerSlot, tableOfContentsSlot, announcementSlot, footerSlot } =
|
||||
props;
|
||||
const { customization } = context;
|
||||
|
||||
const withTopHeader = customization.header.preset !== CustomizationHeaderPreset.None;
|
||||
|
||||
const withSections = shouldRenderSiteSectionNavigation(visibleSections);
|
||||
const variants = categorizeVariants(context);
|
||||
const socialLinks = customization.socialAccounts.filter((account) => account.display?.footer);
|
||||
|
||||
@@ -129,9 +259,15 @@ export function SpaceLayout(props: SpaceLayoutProps) {
|
||||
customization.footer.groups?.length;
|
||||
|
||||
return (
|
||||
<SpaceLayoutServerContext {...props}>
|
||||
<Announcement context={context} />
|
||||
<Header withTopHeader={withTopHeader} variants={variants} context={context} />
|
||||
<SpaceLayoutServerContext
|
||||
context={context}
|
||||
withTracking={props.withTracking}
|
||||
visitorAuthClaims={props.visitorAuthClaims}
|
||||
aiChatRenderMessageOptions={props.aiChatRenderMessageOptions}
|
||||
clientNavigationSelection={props.clientNavigationSelection}
|
||||
>
|
||||
{announcementSlot}
|
||||
{headerSlot}
|
||||
<NavigationLoader />
|
||||
{isAIChatEnabled(customization.ai?.mode) ? (
|
||||
<>
|
||||
@@ -164,86 +300,12 @@ export function SpaceLayout(props: SpaceLayoutProps) {
|
||||
: 'lg:min-h-screen'
|
||||
)}
|
||||
>
|
||||
<TableOfContents
|
||||
context={context}
|
||||
header={
|
||||
<div
|
||||
className={tcls(
|
||||
'pr-4',
|
||||
'flex',
|
||||
withTopHeader ? 'lg:hidden' : '',
|
||||
'grow-0',
|
||||
'dark:shadow-light/1',
|
||||
'text-base/tight',
|
||||
'items-center',
|
||||
// On bold themes also color the TOC header so the logo looks correct.
|
||||
'site-header:theme-bold:bg-header-background',
|
||||
'site-header:theme-bold:m-[-1.5rem_-1px_-0.5rem_-2rem]',
|
||||
'site-header:theme-bold:p-[1rem_1rem_1rem_2rem]'
|
||||
)}
|
||||
>
|
||||
<HeaderLogo context={context} />
|
||||
{variants.translations.length > 1 ? (
|
||||
<TranslationsDropdown
|
||||
context={context}
|
||||
siteSpace={
|
||||
variants.translations.find(
|
||||
(space) => space.id === siteSpace.id
|
||||
) ?? siteSpace
|
||||
}
|
||||
siteSpaces={variants.translations}
|
||||
className="[&_.button-leading-icon]:block! ml-auto py-2 [&_.button-content]:hidden"
|
||||
variant="header"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
// Displays the search button and/or the space dropdown in the ToC
|
||||
// according to the header/variant settings.
|
||||
// E.g if there is no header, the search button will be displayed in the ToC.
|
||||
innerHeader={
|
||||
!withTopHeader || variants.generic.length > 1 ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'my-5 sidebar-default:mt-2 flex flex-col gap-2 px-5 empty:hidden',
|
||||
variants.generic.length > 1 ? '' : 'max-lg:hidden'
|
||||
)}
|
||||
>
|
||||
{!withTopHeader && (
|
||||
<div className="flex gap-2 max-lg:hidden">
|
||||
<SearchContainer
|
||||
{...searchProps}
|
||||
style={CustomizationSearchStyle.Subtle}
|
||||
viewport="desktop"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!withTopHeader && withSections && visibleSections && (
|
||||
<SiteSectionList
|
||||
className="hidden lg:block"
|
||||
sections={encodeClientSiteSections(
|
||||
context,
|
||||
visibleSections
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{variants.generic.length > 1 ? (
|
||||
<SpacesDropdown
|
||||
context={context}
|
||||
siteSpace={siteSpace}
|
||||
siteSpaces={variants.generic}
|
||||
className="w-full px-3"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
{tableOfContentsSlot}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{withFooter ? <Footer context={context} /> : null}
|
||||
{withFooter ? footerSlot : null}
|
||||
</SpaceLayoutServerContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { languages } from '@/intl/translations';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import type { GitBookSiteScopeContext } from '@/lib/context';
|
||||
import { getSiteSpaceLanguages, normalizeLanguage } from '@/lib/sites';
|
||||
|
||||
/**
|
||||
* Categorize the variants of the space into generic and translation variants.
|
||||
*/
|
||||
export function categorizeVariants(context: GitBookSiteContext) {
|
||||
export function categorizeVariants(context: GitBookSiteScopeContext) {
|
||||
const { siteSpace } = context;
|
||||
|
||||
// By default, variants only include visible spaces.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import React, { useRef } from 'react';
|
||||
|
||||
import { useCurrentPagePath } from '../hooks';
|
||||
import { useSelectedPagePath } from '../hooks';
|
||||
import { Button, Link, type LinkInsightsProps, type LinkProps, ToggleChevron } from '../primitives';
|
||||
|
||||
/**
|
||||
@@ -20,10 +20,13 @@ export function ToggleableLinkItem(
|
||||
) {
|
||||
const { href, children, descendants, pathnames, insights, icon, tag } = props;
|
||||
|
||||
const currentPagePath = useCurrentPagePath();
|
||||
const isActive = pathnames.some((pathname) => pathname === currentPagePath);
|
||||
const currentPagePath = useSelectedPagePath();
|
||||
const isActive =
|
||||
currentPagePath !== null && pathnames.some((pathname) => pathname === currentPagePath);
|
||||
const defaultIsOpen =
|
||||
isActive || pathnames.some((pathname) => currentPagePath.startsWith(`${pathname}/`));
|
||||
isActive ||
|
||||
(currentPagePath !== null &&
|
||||
pathnames.some((pathname) => currentPagePath.startsWith(`${pathname}/`)));
|
||||
const [isOpen, setIsOpen] = React.useState(defaultIsOpen);
|
||||
const hasBeenToggled = useRef(false);
|
||||
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
// Subset of the WebMCP `ModelContext` interface (https://webmachinelearning.github.io/webmcp/).
|
||||
type ModelContext = {
|
||||
registerTool: (
|
||||
tool: {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema?: object;
|
||||
execute: (input: object, options?: { signal?: AbortSignal }) => Promise<unknown>;
|
||||
},
|
||||
options?: { signal?: AbortSignal }
|
||||
) => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose the site's MCP tools (`~gitbook/mcp`) to browser agents through WebMCP, so anything
|
||||
* added to the server is automatically available to them. Renders nothing.
|
||||
*/
|
||||
export function WebMCP(props: { mcpURL: string }) {
|
||||
const { mcpURL } = props;
|
||||
|
||||
React.useEffect(() => {
|
||||
const modelContext = (document as { modelContext?: ModelContext }).modelContext;
|
||||
if (!modelContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Aborting unregisters the tools and discards a load still in flight.
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
|
||||
(async () => {
|
||||
// The MCP SDK is imported lazily: only agentic browsers pay for it.
|
||||
const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([
|
||||
import('@modelcontextprotocol/sdk/client/index.js'),
|
||||
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
|
||||
]);
|
||||
// Tagged so WebMCP calls are distinguishable in insights (the request URL is tracked).
|
||||
const url = new URL(mcpURL, window.location.href);
|
||||
url.searchParams.set('client', 'webmcp');
|
||||
const client = new Client({ name: 'gitbook-webmcp', version: '1.0.0' });
|
||||
await client.connect(new StreamableHTTPClientTransport(url));
|
||||
const { tools } = await client.listTools();
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const tool of tools) {
|
||||
// Answer synthesis takes 20-30s and browser agents abort tool calls around 30s.
|
||||
if (tool.name === 'askQuestion') {
|
||||
continue;
|
||||
}
|
||||
await modelContext.registerTool(
|
||||
{
|
||||
name: tool.name,
|
||||
description: tool.description ?? tool.name,
|
||||
inputSchema: tool.inputSchema,
|
||||
// The MCP result (`content` blocks, plus `isError` on failure) is passed through.
|
||||
execute: (input, options) =>
|
||||
client.callTool(
|
||||
{ name: tool.name, arguments: input as Record<string, unknown> },
|
||||
undefined,
|
||||
{ signal: options?.signal }
|
||||
),
|
||||
},
|
||||
{ signal }
|
||||
);
|
||||
}
|
||||
})().catch((error) => {
|
||||
// oxlint-disable-next-line no-console
|
||||
console.warn('WebMCP: could not expose the site MCP tools', error);
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [mcpURL]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -10,3 +10,4 @@ export * from './useNow';
|
||||
export * from './useListOverflow';
|
||||
export * from './useCurrentPageMetadata';
|
||||
export * from './useBackToSpace';
|
||||
export * from './useSelectedNavigation';
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Geometry rule behind {@link useListOverflow}, kept free of React so it can be tested directly
|
||||
* against rects measured in a real browser.
|
||||
*/
|
||||
|
||||
export interface MeasuredRect {
|
||||
left: number;
|
||||
right: number;
|
||||
}
|
||||
|
||||
export interface MeasuredItem {
|
||||
id: string;
|
||||
rect: MeasuredRect;
|
||||
}
|
||||
|
||||
/** Sub-pixel tolerance, so a row that fits exactly isn't reported as overflowing. */
|
||||
const EPSILON = 1;
|
||||
|
||||
/**
|
||||
* Decide which items don't fit the container.
|
||||
*
|
||||
* Items are expected to be measured with the overflow affordance (a "more" menu, say) already
|
||||
* rendered *ahead* of them, which is what lets a single measurement answer both questions: the space
|
||||
* before the first item is the width that affordance is reserving, so subtracting it gives the
|
||||
* position each item would have without it. The list only has to make room for the affordance if it
|
||||
* overflows without one — otherwise a row that fits on its own would give up its last item to a menu
|
||||
* it never needed.
|
||||
*
|
||||
* Returns `null` when the measurement carries no information — an empty list, or a container with no
|
||||
* width because an ancestor is hidden (a pane behind an inactive tab). Callers should keep their
|
||||
* previous result and re-measure once it is visible.
|
||||
*/
|
||||
export function resolveOverflowingItems(
|
||||
container: MeasuredRect & { width: number },
|
||||
items: MeasuredItem[]
|
||||
): Set<string> | null {
|
||||
if (container.width <= 0 || items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const reserved = Math.min(...items.map((item) => item.rect.left)) - container.left;
|
||||
const fitsUnaided = items.every(
|
||||
(item) => item.rect.right - reserved <= container.right + EPSILON
|
||||
);
|
||||
|
||||
if (fitsUnaided) {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
return new Set(
|
||||
items.filter((item) => item.rect.right > container.right + EPSILON).map((item) => item.id)
|
||||
);
|
||||
}
|
||||
@@ -20,11 +20,19 @@ export type CurrentContentContext = {
|
||||
|
||||
const ReactCurrentContentContext = React.createContext<CurrentContentContext | null>(null);
|
||||
|
||||
/**
|
||||
* Hook to get the current content, or null outside of a `CurrentContentProvider`.
|
||||
* Some surfaces (embeddable docs, PDF) render navigation components without the provider.
|
||||
*/
|
||||
export function useOptionalCurrentContent(): CurrentContentContext | null {
|
||||
return React.useContext(ReactCurrentContentContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get the current content.
|
||||
*/
|
||||
export function useCurrentContent(): CurrentContentContext {
|
||||
const context = React.useContext(ReactCurrentContentContext);
|
||||
const context = useOptionalCurrentContent();
|
||||
if (!context) {
|
||||
throw new Error('useCurrentContent must be used within a CurrentContentProvider');
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
'use client';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
import { resolveOverflowingItems } from './listOverflow';
|
||||
|
||||
interface OverflowState {
|
||||
/**
|
||||
* Ref for the container element.
|
||||
@@ -26,23 +24,12 @@ interface OverflowState {
|
||||
* Detects which items are overflowing in a horizontal list.
|
||||
* The items must have unique IDs set on their elements.
|
||||
*
|
||||
* In the measuring phase indicated by `isMeasuring`, all items must be rendered. Whatever the list
|
||||
* shows *because* items overflow (a "more" menu, say) has to be rendered ahead of the items in that
|
||||
* phase: the measurement discounts the space taken before the first item, so a list that fits on its
|
||||
* own is not reported as overflowing merely because that menu was reserving room for itself.
|
||||
* In the measuring phase indicated by `isMeasuring`, all items must be rendered.
|
||||
*/
|
||||
export function useListOverflow(): OverflowState {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [overflowing, setOverflowing] = useState<Set<string>>(new Set());
|
||||
// Measuring is a request/completed pair of counters rather than a boolean, because a boolean
|
||||
// reset can be swallowed: the observer re-arms measuring from a rAF, and when that lands in the
|
||||
// same batch as the measure effect's reset the net value is unchanged, so React bails out and the
|
||||
// effect — keyed on that value — never runs again, leaving the list stuck measuring with its
|
||||
// "more" menu permanently on show. Counters only increase, so a request can't cancel a
|
||||
// completion; it just queues another pass.
|
||||
const [measureRequest, setMeasureRequest] = useState(0);
|
||||
const [measureCompleted, setMeasureCompleted] = useState(0);
|
||||
const isMeasuring = measureRequest !== measureCompleted;
|
||||
const [isMeasuring, setIsMeasuring] = useState(false);
|
||||
const itemRefs = useRef(new Map<string, HTMLElement>());
|
||||
const rafRef = useRef(0);
|
||||
|
||||
@@ -56,19 +43,19 @@ export function useListOverflow(): OverflowState {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const requestMeasure = useCallback(() => setMeasureRequest((request) => request + 1), []);
|
||||
|
||||
// Measure on mount and when container size changes
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestMeasure();
|
||||
setIsMeasuring(true);
|
||||
|
||||
const ro = new ResizeObserver(() => {
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = requestAnimationFrame(requestMeasure);
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
setIsMeasuring(true);
|
||||
});
|
||||
});
|
||||
|
||||
ro.observe(containerRef.current);
|
||||
@@ -77,7 +64,7 @@ export function useListOverflow(): OverflowState {
|
||||
ro.disconnect();
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
};
|
||||
}, [requestMeasure]);
|
||||
}, []);
|
||||
|
||||
// Measure which items are overflowing
|
||||
useLayoutEffect(() => {
|
||||
@@ -85,32 +72,29 @@ export function useListOverflow(): OverflowState {
|
||||
return;
|
||||
}
|
||||
|
||||
const newOverflowing = resolveOverflowingItems(
|
||||
containerRef.current.getBoundingClientRect(),
|
||||
Array.from(itemRefs.current, ([id, element]) => ({
|
||||
id,
|
||||
rect: element.getBoundingClientRect(),
|
||||
}))
|
||||
);
|
||||
const containerRect = containerRef.current.getBoundingClientRect();
|
||||
const newOverflowing = new Set<string>();
|
||||
|
||||
// `null` means the measurement said nothing (hidden ancestor, or no items) — keep what we
|
||||
// had and wait for the observer to fire once it is visible.
|
||||
if (newOverflowing) {
|
||||
setOverflowing((previous) => {
|
||||
if (previous.size !== newOverflowing.size) {
|
||||
itemRefs.current.forEach((el, id) => {
|
||||
const elRect = el.getBoundingClientRect();
|
||||
if (elRect.right > containerRect.right + 1) {
|
||||
newOverflowing.add(id);
|
||||
}
|
||||
});
|
||||
|
||||
setOverflowing((previous) => {
|
||||
if (previous.size !== newOverflowing.size) {
|
||||
return newOverflowing;
|
||||
}
|
||||
for (const id of previous) {
|
||||
if (!newOverflowing.has(id)) {
|
||||
return newOverflowing;
|
||||
}
|
||||
for (const id of previous) {
|
||||
if (!newOverflowing.has(id)) {
|
||||
return newOverflowing;
|
||||
}
|
||||
}
|
||||
return previous;
|
||||
});
|
||||
}
|
||||
|
||||
setMeasureCompleted(measureRequest);
|
||||
}, [isMeasuring, measureRequest]);
|
||||
}
|
||||
return previous;
|
||||
});
|
||||
setIsMeasuring(false);
|
||||
}, [isMeasuring]);
|
||||
|
||||
return { containerRef, itemRef, overflowing, isMeasuring };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { useOptionalCurrentContent } from './useCurrentContent';
|
||||
import { useCurrentPagePath } from './useCurrentPagePath';
|
||||
import { useIsMounted } from './useIsMounted';
|
||||
|
||||
const ClientNavigationSelectionContext = React.createContext(false);
|
||||
|
||||
/**
|
||||
* Mark a subtree whose server-rendered selection cannot be trusted.
|
||||
* Under PPR the header and the table of contents are cached fragments shared across pages, so the
|
||||
* "where am I" state they were rendered with belongs to another page and has to be recomputed here.
|
||||
*/
|
||||
export function ClientNavigationSelectionProvider(
|
||||
props: React.PropsWithChildren<{ enabled: boolean }>
|
||||
) {
|
||||
const { enabled, children } = props;
|
||||
|
||||
return (
|
||||
<ClientNavigationSelectionContext.Provider value={enabled}>
|
||||
{children}
|
||||
</ClientNavigationSelectionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the page path to mark as selected, or null while it hasn't been resolved on the client.
|
||||
*/
|
||||
export function useSelectedPagePath(): string | null {
|
||||
// The page path always comes from the route, it just can't be trusted before hydration.
|
||||
const pagePath = useCurrentPagePath();
|
||||
return useSelected(pagePath, pagePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the site section to mark as selected, or null while it hasn't been resolved on the client.
|
||||
*/
|
||||
export function useSelectedSiteSectionId(serverValue: string | null): string | null {
|
||||
return useSelected(serverValue, useOptionalCurrentContent()?.siteSectionId ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the site space to mark as selected, or null while it hasn't been resolved on the client.
|
||||
*/
|
||||
export function useSelectedSiteSpaceId(serverValue: string | null): string | null {
|
||||
return useSelected(serverValue, useOptionalCurrentContent()?.siteSpaceId ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick between the value the server rendered with and the one resolved on the client.
|
||||
* Nothing is selected until mount, so a stale highlight is never painted and the first client
|
||||
* render still matches the cached markup (which was produced by this same branch).
|
||||
*/
|
||||
function useSelected<T>(serverValue: T, clientValue: T): T | null {
|
||||
const enabled = React.useContext(ClientNavigationSelectionContext);
|
||||
const isMounted = useIsMounted();
|
||||
|
||||
if (!enabled) {
|
||||
return serverValue;
|
||||
}
|
||||
|
||||
return isMounted ? clientValue : null;
|
||||
}
|
||||
@@ -3,13 +3,15 @@ import assertNever from 'assert-never';
|
||||
/**
|
||||
* Returns the URL to open the page in a LLM with a pre-filled prompt.
|
||||
*/
|
||||
export function getURLForLLM(provider: 'chatgpt' | 'claude', prompt: string) {
|
||||
export function getURLForLLM(provider: 'chatgpt' | 'claude' | 'cursor', prompt: string) {
|
||||
const encodedPrompt = encodeURIComponent(prompt);
|
||||
switch (provider) {
|
||||
case 'chatgpt':
|
||||
return `https://chat.openai.com/?q=${encodedPrompt}`;
|
||||
case 'claude':
|
||||
return `https://claude.ai/new?q=${encodedPrompt}`;
|
||||
case 'cursor':
|
||||
return `https://cursor.com/link/prompt?text=${encodedPrompt}`;
|
||||
default:
|
||||
assertNever(provider);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
isAvailableLanguage,
|
||||
loadLanguage,
|
||||
} from './translations';
|
||||
import type { GitBookAnyContext } from '@/lib/context';
|
||||
import type { GitBookAnyContext, GitBookSiteScopeContext } from '@/lib/context';
|
||||
|
||||
export * from './translate';
|
||||
|
||||
@@ -15,7 +15,7 @@ export const DEFAULT_LOCALE = 'en' satisfies TranslationLocale;
|
||||
* Get the locale to use for the HTML lang attribute.
|
||||
* This returns the actual content language even if we don't have UI translations for it.
|
||||
*/
|
||||
export function getContentLocale(context: GitBookAnyContext): string {
|
||||
export function getContentLocale(context: GitBookAnyContext | GitBookSiteScopeContext): string {
|
||||
if (context.locale) {
|
||||
return context.locale;
|
||||
}
|
||||
@@ -31,7 +31,9 @@ export function getContentLocale(context: GitBookAnyContext): string {
|
||||
/**
|
||||
* Get the locale to use for a space.
|
||||
*/
|
||||
export function getSpaceLocale(context: GitBookAnyContext): TranslationLocale {
|
||||
export function getSpaceLocale(
|
||||
context: GitBookAnyContext | GitBookSiteScopeContext
|
||||
): TranslationLocale {
|
||||
const customization = 'site' in context ? context.customization : null;
|
||||
|
||||
// If the language is configured in the space, use it in priority
|
||||
@@ -55,7 +57,9 @@ export function getSpaceLocale(context: GitBookAnyContext): TranslationLocale {
|
||||
/**
|
||||
* Create the translation context for a space to use in the server components.
|
||||
*/
|
||||
export async function getSpaceLanguage(context: GitBookAnyContext): Promise<TranslationLanguage> {
|
||||
export async function getSpaceLanguage(
|
||||
context: GitBookAnyContext | GitBookSiteScopeContext
|
||||
): Promise<TranslationLanguage> {
|
||||
const locale = getSpaceLocale(context);
|
||||
const language = locale === DEFAULT_LOCALE ? defaultLanguage : await loadLanguage(locale);
|
||||
|
||||
|
||||
@@ -148,7 +148,6 @@ export const ar: TranslationLanguage = {
|
||||
ai_chat_tools_submit_feedback: 'إرسال الملاحظات',
|
||||
ai_chat_tools_submit_assistant_feedback: 'قيّم رسالة المساعد السابقة بأنها ${1}',
|
||||
ai_chat_tools_submitted_feedback: 'تم إرسال ملاحظاتك',
|
||||
ai_chat_tools_shared_feedback_with_team: 'تم إرسال الملاحظات إلى فريق التوثيق',
|
||||
ai_chat_tools_mcp_tool: 'تم استدعاء ${1}',
|
||||
ai_chat_ask: 'اسأل ${1}',
|
||||
ai_chat_ask_about: 'اسأل ${1} عن ${2}',
|
||||
|
||||
@@ -152,8 +152,6 @@ export const bg: TranslationLanguage = {
|
||||
ai_chat_tools_submit_feedback: 'Изпращане на обратна връзка',
|
||||
ai_chat_tools_submit_assistant_feedback: 'Оценете предишното съобщение на асистента като ${1}',
|
||||
ai_chat_tools_submitted_feedback: 'Обратната връзка е изпратена',
|
||||
ai_chat_tools_shared_feedback_with_team:
|
||||
'Обратната връзка е изпратена на екипа по документацията',
|
||||
ai_chat_tools_mcp_tool: 'Извика ${1}',
|
||||
ai_chat_ask: 'Попитайте ${1}',
|
||||
ai_chat_ask_about: 'Попитайте ${1} за ${2}',
|
||||
|
||||
@@ -150,7 +150,6 @@ export const cs: TranslationLanguage = {
|
||||
ai_chat_tools_submit_feedback: 'Odeslat zpětnou vazbu',
|
||||
ai_chat_tools_submit_assistant_feedback: 'Ohodnotit předchozí zprávu asistenta jako ${1}',
|
||||
ai_chat_tools_submitted_feedback: 'Zpětná vazba odeslána',
|
||||
ai_chat_tools_shared_feedback_with_team: 'Zpětná vazba odeslána týmu dokumentace',
|
||||
ai_chat_tools_mcp_tool: 'Zavolal ${1}',
|
||||
ai_chat_ask: 'Zeptat se ${1}',
|
||||
ai_chat_ask_about: 'Zeptat se ${1} na ${2}',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user