mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-25 20:03:16 +00:00
Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f720f1dbd6 | |||
| 59bc231ccd | |||
| 3c177f04a2 | |||
| 1d648a9391 | |||
| c7d042a733 | |||
| e94a5085eb | |||
| 3ae1524a88 | |||
| b967b248e7 | |||
| a9e6814744 | |||
| 5725da19e2 | |||
| 05cff0a03b | |||
| 1e8c34a426 | |||
| cd881f9ac1 | |||
| 39316fc205 | |||
| c08d05ade5 | |||
| b9453a92f8 | |||
| 2c4d40ad97 | |||
| 688515efcf | |||
| 931cbe717e | |||
| 3ef1802e7e | |||
| 8a0e0df84e | |||
| a9041a309a | |||
| 625c108196 | |||
| 8e87856501 | |||
| 9b822abbb6 | |||
| 81dba6455b | |||
| 1faa57b812 | |||
| 40150f0a6c | |||
| bf29570bd5 | |||
| e8e979b6c0 | |||
| 1f250d1fa8 | |||
| 46b3a18b25 | |||
| 2ff77e15b5 | |||
| d7c867aa63 | |||
| bcd1c41aa1 | |||
| 77058e3f17 | |||
| 8ad7465801 | |||
| 1b7ac0e41b |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Simplify carousel overflow with symmetric edge masks and visible-item paging. Replaces complex negative-margin bleed logic with transparent edge fades and page-by-visible-item scrolling.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Include published page descriptions in the page's Markdown output.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix select filters not working on table and cards blocks.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix inline Ask AI buttons opening a configured custom assistant.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix ContentKit buttons to size to their content instead of stretching to the full container width.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Hide heading and expandable anchor links on pages whose layout disables anchors (landing pages).
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Hide the Intercom launcher while the Assistant panel is open, so it no longer overlaps the message box.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Bump `@gitbook/api` to 0.199.0, and record a markdown request made from the page actions menu as a page action rather than an agent request.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix the page-actions dropdown closing before the "Copied" confirmation could be shown when copying the MCP server URL, an MCP install command, or the page as Markdown.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Serve Markdown responses to ChatGPT with a `text/plain` Content-Type for compatibility.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Preserve the full site preview path and query parameters when redirecting users to log in.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Keep current-space search results inside revision previews.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Render horizontal and vertical merged table cells on published pages.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gitbook/react-contentkit": patch
|
||||
---
|
||||
|
||||
Show a close button on ContentKit modals rendered on published sites.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"@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 `{}`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Scroll to the top when selecting a search result for the page already being viewed.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Add end-to-end coverage for root and nested external links in site section navigation.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix section links in search results opening the page without scrolling to the section.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix keyboard focus getting trapped inside the header search popover, allowing Tab/Shift+Tab to exit it as expected.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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
|
||||
---
|
||||
|
||||
Skip redundant class and style writes on `<html>` and the site header during initial load; each one re-styled the whole document.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Fix tabs nested inside another tab group rendering an empty body once a tab in the outer group was selected.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Remove the fallback query parameter after successful page navigation without adding a browser history entry.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Restore Edit on Git page actions for Git-synced pages.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Expose the site's MCP tools to browser agents through WebMCP when the MCP page action is enabled.
|
||||
@@ -69,6 +69,7 @@ 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
|
||||
|
||||
@@ -75,6 +75,7 @@ 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
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,30 @@
|
||||
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,3 +29,6 @@ yarn-error.log*
|
||||
|
||||
# Bun pack artifacts
|
||||
packages/*/*.tgz
|
||||
|
||||
# Playwright MCP artifacts
|
||||
.playwright-mcp/
|
||||
|
||||
@@ -275,6 +275,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "catalog:",
|
||||
"bun-types": "catalog:",
|
||||
"react": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
@@ -354,7 +355,7 @@
|
||||
},
|
||||
"catalog": {
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"@gitbook/api": "0.198.0",
|
||||
"@gitbook/api": "0.202.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@tsconfig/node20": "^20.1.6",
|
||||
"@tsconfig/strictest": "^2.0.6",
|
||||
@@ -726,7 +727,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.198.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-ZGXqYip6YFsCM5rqlJ+n8/Esw1bMNK4whqiMoWMeQgMKEX5YXVQaBuVRxU1jDEI49kup+T56xPq3I9g6Wcayng=="],
|
||||
"@gitbook/api": ["@gitbook/api@0.202.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-qhrjEQbNNmCljR0AgP79+BsVh9yelh9TIBg9X3TyYx5a3lJwDiT3sw1ND9DFQSxGHp8hH5w+20KJHn/IDpTbaw=="],
|
||||
|
||||
"@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.198.0",
|
||||
"@gitbook/api": "0.202.0",
|
||||
"@scalar/api-client-react": "^1.3.46",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
CustomizationDepth,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationIconsStyle,
|
||||
CustomizationPageActionType,
|
||||
CustomizationSidebarListStyle,
|
||||
SiteSocialAccountPlatform,
|
||||
} from '@gitbook/api';
|
||||
@@ -158,7 +159,7 @@ const searchTestCases: Test[] = [
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search - Keyboard focus stays within search',
|
||||
name: 'Search - Keyboard focus exits to the next page control',
|
||||
url: getCustomizationURL({
|
||||
ai: {
|
||||
mode: CustomizationAIMode.Search,
|
||||
@@ -179,13 +180,16 @@ 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(searchInput).toBeFocused();
|
||||
await expect(searchPopup).toBeHidden();
|
||||
await expect(nextPageControl).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(finalPopupControl).toBeFocused();
|
||||
await expect(searchInput).toBeFocused();
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -245,6 +249,43 @@ 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({
|
||||
@@ -513,6 +554,24 @@ 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',
|
||||
@@ -535,8 +594,11 @@ 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')
|
||||
await page.waitForURL(
|
||||
(url) =>
|
||||
url.pathname.includes(
|
||||
'api-multi-versions/2.0/reference/api-reference/pets'
|
||||
) && !url.searchParams.has('fallback')
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -707,6 +769,150 @@ const testCases: TestsCase[] = [
|
||||
await page.waitForURL((url) => url.pathname.includes('/sections/sections-4'));
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Root external link renders in the configured position',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const rootSections = page.locator('[data-gb-sections]');
|
||||
const rootItems = rootSections.locator(':scope > li');
|
||||
|
||||
await expect(rootItems).toHaveCount(4);
|
||||
await expect(rootItems.nth(0)).toContainText('Home');
|
||||
await expect(rootItems.nth(1)).toContainText('Test Section Group 1');
|
||||
await expect(rootItems.nth(2)).toContainText('Test Section Group 2');
|
||||
await expect(rootItems.last()).toContainText('Gitbook Docs');
|
||||
await expect(
|
||||
rootSections.getByRole('link', { name: 'Gitbook Docs' })
|
||||
).toBeVisible();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Root external link has the configured contract',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
const rootLink = page
|
||||
.locator('[data-gb-sections]')
|
||||
.getByRole('link', { name: 'Gitbook Docs' });
|
||||
|
||||
await expect(rootLink).toBeVisible();
|
||||
await expect(rootLink).toHaveAttribute('href', 'https://gitbook.com/docs');
|
||||
await expect(rootLink).not.toHaveAttribute('target');
|
||||
await expect(rootLink).not.toHaveAttribute('rel');
|
||||
await expect(rootLink).toHaveAttribute('data-active', 'false');
|
||||
await expect(rootLink).not.toHaveAttribute('aria-current');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Nested external link renders in the configured position',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
await page
|
||||
.locator('[data-gb-sections]')
|
||||
.getByRole('button', { name: 'Test Section Group 2' })
|
||||
.hover();
|
||||
|
||||
const nestedLink = page.getByRole('link', { name: 'Gitbook Site' });
|
||||
await expect(nestedLink).toBeVisible();
|
||||
|
||||
const nestedItems = nestedLink
|
||||
.locator('xpath=ancestor::ul[1]')
|
||||
.locator(':scope > li');
|
||||
await expect(nestedItems).toHaveCount(3);
|
||||
await expect(nestedItems.nth(0)).toContainText('Section C');
|
||||
await expect(nestedItems.nth(1)).toContainText('Section with longer title');
|
||||
await expect(nestedItems.last()).toContainText('Gitbook Site');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Nested external link has the configured contract',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
await page
|
||||
.locator('[data-gb-sections]')
|
||||
.getByRole('button', { name: 'Test Section Group 2' })
|
||||
.hover();
|
||||
|
||||
const nestedLink = page.getByRole('link', { name: 'Gitbook Site' });
|
||||
await expect(nestedLink).toBeVisible();
|
||||
await expect(nestedLink).toHaveAttribute('href', 'https://gitbook.com');
|
||||
await expect(nestedLink).not.toHaveAttribute('target');
|
||||
await expect(nestedLink).not.toHaveAttribute('rel');
|
||||
await expect(nestedLink).not.toHaveAttribute('aria-current');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'External links use the configured window open behavior',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
await waitForHydration(page);
|
||||
|
||||
const windowOpenCalls: {
|
||||
url: string;
|
||||
target: string;
|
||||
features: string | undefined;
|
||||
}[] = [];
|
||||
await page.exposeFunction(
|
||||
'recordExternalWindowOpen',
|
||||
(url: string, target: string, features?: string) => {
|
||||
windowOpenCalls.push({ url, target, features });
|
||||
}
|
||||
);
|
||||
await page.evaluate(() => {
|
||||
const recordExternalWindowOpen = (
|
||||
window as unknown as {
|
||||
recordExternalWindowOpen: (
|
||||
url: string,
|
||||
target: string,
|
||||
features?: string
|
||||
) => void;
|
||||
}
|
||||
).recordExternalWindowOpen;
|
||||
window.open = ((url, target, features) => {
|
||||
void recordExternalWindowOpen(
|
||||
url?.toString() ?? '',
|
||||
target ?? '',
|
||||
features
|
||||
);
|
||||
return null;
|
||||
}) as typeof window.open;
|
||||
});
|
||||
|
||||
const initialURL = page.url();
|
||||
await page
|
||||
.locator('[data-gb-sections]')
|
||||
.getByRole('link', { name: 'Gitbook Docs' })
|
||||
.click();
|
||||
await expect.poll(() => windowOpenCalls.length).toBe(1);
|
||||
expect(windowOpenCalls[0]).toEqual({
|
||||
url: 'https://gitbook.com/docs',
|
||||
target: '_self',
|
||||
features: undefined,
|
||||
});
|
||||
await expect(page).toHaveURL(initialURL);
|
||||
|
||||
await page
|
||||
.locator('[data-gb-sections]')
|
||||
.getByRole('button', { name: 'Test Section Group 2' })
|
||||
.hover();
|
||||
await page.getByRole('link', { name: 'Gitbook Site' }).click();
|
||||
await expect.poll(() => windowOpenCalls.length).toBe(2);
|
||||
expect(windowOpenCalls[1]).toEqual({
|
||||
url: 'https://gitbook.com',
|
||||
target: '_self',
|
||||
features: undefined,
|
||||
});
|
||||
await expect(page).toHaveURL(initialURL);
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -1428,6 +1634,70 @@ 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/',
|
||||
@@ -1480,7 +1750,6 @@ const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'Without previewed ads',
|
||||
url: 'text-page?ads_preview=1',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -236,3 +236,99 @@ test.describe('select syncing across groups (click-driven)', () => {
|
||||
await expectGroupShows(page, 'b', other, 'go');
|
||||
});
|
||||
});
|
||||
|
||||
interface NestedSpec {
|
||||
outer: string[];
|
||||
inner: string[];
|
||||
/** Which of the outer options hosts the nested group. */
|
||||
host: string;
|
||||
/**
|
||||
* Emit the nested group's stylesheet before the outer one, as happens when a group with the
|
||||
* same option set appears earlier on the page and its deduped sheet lands in `<head>` first.
|
||||
*/
|
||||
innerStyleFirst?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a group nested inside one of another group's panes, mirroring the DOM `DynamicTabs`
|
||||
* produces: panes are direct children of the element carrying the set class, and a pane's body is
|
||||
* wrapped in a padding div before the nested group.
|
||||
*/
|
||||
async function renderNestedGroups(page: Page, spec: NestedSpec) {
|
||||
const { outer, inner, host, innerStyleFirst = false } = spec;
|
||||
const outerScope = selectSetClassName(outer);
|
||||
const innerScope = selectSetClassName(inner);
|
||||
|
||||
const innerPanes = inner
|
||||
.map(
|
||||
(slug, index) =>
|
||||
`<div data-testid="inner-pane-${slug}" data-select-option="${slug}"${index === 0 ? ' data-select-default' : ''}>${slug}</div>`
|
||||
)
|
||||
.join('');
|
||||
const innerGroup = `<div class="${innerScope}" data-select-group>${innerPanes}</div>`;
|
||||
|
||||
const outerPanes = outer
|
||||
.map(
|
||||
(slug, index) =>
|
||||
`<div data-testid="outer-pane-${slug}" data-select-option="${slug}"${index === 0 ? ' data-select-default' : ''}><div>${slug}${slug === host ? innerGroup : ''}</div></div>`
|
||||
)
|
||||
.join('');
|
||||
|
||||
const styles = [generateSelectCSS(outer), generateSelectCSS(inner)];
|
||||
if (innerStyleFirst) {
|
||||
styles.reverse();
|
||||
}
|
||||
|
||||
await page.setContent(
|
||||
`<!doctype html><html><head>${styles.map((css) => `<style>${css}</style>`).join('')}</head><body><div class="${outerScope}" data-select-group>${outerPanes}</div></body></html>`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A group's stylesheet must resolve only its own panes. Because every pane of a nested group is also
|
||||
* a descendant of the outer group, a sheet that reached descendants instead of children would hide
|
||||
* the nested panes whenever an outer option was active, leaving the nested tab bar with an empty body.
|
||||
*/
|
||||
test.describe('select CSS visibility in nested groups', () => {
|
||||
const outer = ['macos', 'windows'];
|
||||
const inner = ['npm', 'yarn'];
|
||||
|
||||
test('shows both defaults when nothing is selected', async ({ page }) => {
|
||||
await renderNestedGroups(page, { outer, inner, host: 'macos' });
|
||||
await expect(page.getByTestId('outer-pane-macos')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-npm')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-yarn')).toBeHidden();
|
||||
});
|
||||
|
||||
test('keeps the nested group resolved when an outer option is activated', async ({ page }) => {
|
||||
await renderNestedGroups(page, { outer, inner, host: 'macos' });
|
||||
await applySelection(page, ['macos']);
|
||||
await expect(page.getByTestId('outer-pane-macos')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-npm')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-yarn')).toBeHidden();
|
||||
});
|
||||
|
||||
test('resolves a nested group hosted by a non-default outer option', async ({ page }) => {
|
||||
await renderNestedGroups(page, { outer, inner, host: 'windows' });
|
||||
await applySelection(page, ['windows']);
|
||||
await expect(page.getByTestId('outer-pane-windows')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-npm')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-yarn')).toBeHidden();
|
||||
});
|
||||
|
||||
test('resolves each group against its own options', async ({ page }) => {
|
||||
await renderNestedGroups(page, { outer, inner, host: 'macos' });
|
||||
await applySelection(page, ['yarn', 'macos']);
|
||||
await expect(page.getByTestId('outer-pane-macos')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-yarn')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-npm')).toBeHidden();
|
||||
});
|
||||
|
||||
test('resolves the same way whichever stylesheet comes first', async ({ page }) => {
|
||||
await renderNestedGroups(page, { outer, inner, host: 'macos', innerStyleFirst: true });
|
||||
await applySelection(page, ['yarn', 'macos']);
|
||||
await expect(page.getByTestId('outer-pane-macos')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-yarn')).toBeVisible();
|
||||
await expect(page.getByTestId('inner-pane-npm')).toBeHidden();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -465,7 +465,11 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
|
||||
socialAccounts: [],
|
||||
};
|
||||
|
||||
const encoded = rison.encode_object(deepMerge(DEFAULT_CUSTOMIZATION, partial));
|
||||
const encoded = rison.encode_object(
|
||||
deepMerge(DEFAULT_CUSTOMIZATION, partial, {
|
||||
arrayMerge: (_target, source) => source,
|
||||
})
|
||||
);
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('customization', encoded);
|
||||
|
||||
@@ -94,6 +94,7 @@ const nextConfig = {
|
||||
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,
|
||||
|
||||
@@ -132,7 +132,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 --project=chromium",
|
||||
"e2e": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.spec.ts e2e/tabs-overflow.spec.ts --project=chromium",
|
||||
"e2e-customers": "playwright test e2e/customers.spec.ts --project=chromium",
|
||||
"e2e-style-perf": "playwright test e2e/style-perf.spec.ts --project=chromium --reporter=list",
|
||||
"unit": "bun run generate:assets && bun test {src,packages} --preload ./tests/preload-bun.ts",
|
||||
|
||||
+45
-77
@@ -2,10 +2,21 @@ import { createMcpHandler } from 'mcp-handler';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { CustomizationPageActionType, SiteInsightsDisplayContext } from '@gitbook/api';
|
||||
import {
|
||||
AgentFeedbackSource,
|
||||
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';
|
||||
@@ -353,26 +364,14 @@ export async function handleMcpRequest(
|
||||
content: z
|
||||
.string()
|
||||
.min(1)
|
||||
.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.'
|
||||
),
|
||||
.max(AGENT_FEEDBACK_MAX_LENGTH)
|
||||
.describe(agentFeedbackDescriptions.finding),
|
||||
pageUrl: z
|
||||
.string()
|
||||
.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.`
|
||||
)
|
||||
.describe(agentFeedbackDescriptions.pageURL(siteUrl))
|
||||
.transform((value, ctx) => {
|
||||
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:')
|
||||
) {
|
||||
const url = parseAgentFeedbackPageURL(value, siteUrl);
|
||||
if (!url) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `"${value}" is not a valid URL on this site. Expected a full URL like ${siteUrl}/getting-started`,
|
||||
@@ -380,14 +379,13 @@ export async function handleMcpRequest(
|
||||
return z.NEVER;
|
||||
}
|
||||
|
||||
return candidate.toString();
|
||||
return url;
|
||||
}),
|
||||
goal: z
|
||||
.string()
|
||||
.max(AGENT_FEEDBACK_GOAL_MAX_LENGTH)
|
||||
.optional()
|
||||
.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.'
|
||||
),
|
||||
.describe(agentFeedbackDescriptions.goal),
|
||||
},
|
||||
{
|
||||
title: 'Send feedback',
|
||||
@@ -398,66 +396,36 @@ export async function handleMcpRequest(
|
||||
},
|
||||
async ({ content, pageUrl, goal }) => {
|
||||
try {
|
||||
const match = findSiteSpaceByUrl(context.structure, pageUrl);
|
||||
if (!match) {
|
||||
const result = await submitAgentFeedback(context, {
|
||||
feedback: content,
|
||||
goal,
|
||||
page: pageUrl,
|
||||
source: AgentFeedbackSource.Mcp,
|
||||
});
|
||||
|
||||
if (!result.submitted) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Page not found: "${pageUrl}"` }],
|
||||
content: [{ type: 'text', text: result.error }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
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 } : {}),
|
||||
}
|
||||
);
|
||||
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,
|
||||
});
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Feedback recorded. Thank you.' }],
|
||||
|
||||
+149
-3
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type { SearchPageResult, SearchSpaceResult, SiteSpace } from '@gitbook/api';
|
||||
import type {
|
||||
RevisionPage,
|
||||
RevisionPageDocument,
|
||||
SearchPageResult,
|
||||
SearchSpaceResult,
|
||||
SiteSpace,
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { orderSearchResultGroups } from './orderSearchResults';
|
||||
import { createLinker } from '@/lib/links';
|
||||
@@ -16,6 +22,13 @@ 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',
|
||||
@@ -63,6 +76,33 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,12 +123,92 @@ describe('transformSitePageResult', () => {
|
||||
expect(transformPage(createPageResult({ path: destination }), true).href).toBe(destination);
|
||||
});
|
||||
|
||||
it('resolves a relative page path through the published site URL', () => {
|
||||
it('keeps published search results on their published destination', () => {
|
||||
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);
|
||||
|
||||
@@ -126,7 +246,33 @@ describe('transformSitePageResult', () => {
|
||||
spaceItem,
|
||||
});
|
||||
|
||||
expect(result.href).toBe('/guides/getting-started');
|
||||
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');
|
||||
});
|
||||
|
||||
it('preserves ranks, scores, and result ordering', () => {
|
||||
|
||||
+34
-12
@@ -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 } from '@/lib/sites';
|
||||
import { findSiteSpaceBy, getLinkerForSiteSpace } 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 }] = await Promise.all([
|
||||
const [searchResults, { structure }, revision] = await Promise.all([
|
||||
throwIfDataError(
|
||||
context.dataFetcher.searchSiteContent({
|
||||
organizationId: siteURLData.organization,
|
||||
@@ -38,8 +38,24 @@ 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') {
|
||||
@@ -55,25 +71,31 @@ export async function POST(request: NextRequest) {
|
||||
return { type: 'context' as const, results: [result] };
|
||||
}
|
||||
|
||||
const found = findSiteSpaceBy(
|
||||
structure,
|
||||
(siteSpace) => siteSpace.space.id === resultItem.id
|
||||
);
|
||||
const isCurrentRevisionSpace = Boolean(revision && resultItem.id === siteURLData.space);
|
||||
const found =
|
||||
isCurrentRevisionSpace && currentSiteSpace
|
||||
? currentSiteSpace
|
||||
: findSiteSpaceBy(
|
||||
structure,
|
||||
(siteSpace) => siteSpace.space.id === resultItem.id
|
||||
);
|
||||
|
||||
return {
|
||||
type: 'pages' as const,
|
||||
results: resultItem.pages.map((pageItem) => ({
|
||||
rank: pageItem.rank,
|
||||
result: transformSitePageResult({
|
||||
results: resultItem.pages.flatMap((pageItem) => {
|
||||
const result = transformSitePageResult({
|
||||
asEmbeddable: Boolean(asEmbeddable),
|
||||
linker: context.linker,
|
||||
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
|
||||
pageItem,
|
||||
spaceItem: resultItem,
|
||||
siteSpace: found?.siteSpace,
|
||||
siteSection: found?.siteSection ?? undefined,
|
||||
siteSectionGroup: found?.siteSectionGroup ?? undefined,
|
||||
}),
|
||||
})),
|
||||
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
|
||||
});
|
||||
|
||||
return result ? [{ rank: pageItem.rank, result }] : [];
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
GITBOOK_API_URL,
|
||||
GITBOOK_APP_URL,
|
||||
GITBOOK_ASSETS_URL,
|
||||
GITBOOK_DISABLE_INSIGHTS,
|
||||
GITBOOK_DISABLE_TRACKING,
|
||||
GITBOOK_FONTS_URL,
|
||||
GITBOOK_ICONS_URL,
|
||||
@@ -35,6 +36,7 @@ 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,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
'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,3 +1,4 @@
|
||||
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 } from '@/lib/references';
|
||||
import { resolveContentRef, resolveStringContentRef, toContentRefPath } from '@/lib/references';
|
||||
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
|
||||
import { traceErrorOnly } from '@/lib/tracing';
|
||||
|
||||
@@ -21,15 +21,7 @@ export async function resolveAINavigationLink(
|
||||
const baseContext = await getServerActionBaseContext();
|
||||
const context = await fetchServerActionSiteContext(baseContext);
|
||||
|
||||
// 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);
|
||||
const contentRef = resolveStringContentRef(toContentRefPath(url));
|
||||
if (contentRef) {
|
||||
const resolved = await resolveContentRef(contentRef, context);
|
||||
if (!resolved) {
|
||||
|
||||
@@ -18,10 +18,12 @@ 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,
|
||||
@@ -240,7 +242,6 @@ export function AIChatProvider(props: {
|
||||
const setSearchStateInURL = useSetSearchState();
|
||||
const { siteSpaceId } = useCurrentContent();
|
||||
const language = useLanguage();
|
||||
|
||||
const displayContext = renderMessageOptions?.asEmbeddable
|
||||
? SiteInsightsDisplayContext.Embed
|
||||
: SiteInsightsDisplayContext.Site;
|
||||
@@ -256,6 +257,10 @@ 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.
|
||||
@@ -265,22 +270,41 @@ 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 page-feedback tool is gated on the site's "Was this helpful?" setting.
|
||||
// rating), while the tools carrying the reader's own feedback are gated on the site's
|
||||
// "Was this helpful?" setting.
|
||||
const builtInTools = React.useMemo(() => {
|
||||
const tools = [navigateToPageTool, submitAssistantFeedbackTool];
|
||||
const tools = [navigateToPageTool, submitAssistantFeedbackTool, leaveAgentFeedbackTool];
|
||||
if (withPageFeedback) {
|
||||
tools.push(submitPageFeedbackTool);
|
||||
tools.push(submitPageFeedbackTool, leaveUserFeedbackTool);
|
||||
}
|
||||
return tools;
|
||||
}, [navigateToPageTool, submitAssistantFeedbackTool, submitPageFeedbackTool, withPageFeedback]);
|
||||
}, [
|
||||
navigateToPageTool,
|
||||
submitAssistantFeedbackTool,
|
||||
leaveAgentFeedbackTool,
|
||||
leaveUserFeedbackTool,
|
||||
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 }));
|
||||
|
||||
@@ -297,6 +321,8 @@ 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
|
||||
@@ -711,6 +737,7 @@ 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,
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
'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.",
|
||||
"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.",
|
||||
confirmation: (input) => {
|
||||
const parsed = SubmitPageFeedbackInputSchema.safeParse(input);
|
||||
const comment = parsed.success ? parsed.data.comment?.trim() : undefined;
|
||||
|
||||
+3
-1
@@ -53,8 +53,10 @@ export function AskAIParagraphButton(props: { content: string; className?: Class
|
||||
'hover:visible hover:opacity-100 group-hover/ask-ai:visible group-hover/ask-ai:opacity-100',
|
||||
// Never shown on touch / hover-less contexts.
|
||||
'not-pointer-fine:hidden',
|
||||
// Hidden where an overflow-clipped ancestor would cut it off (tables, record cards).
|
||||
// Hidden where an overflow-clipped ancestor would cut it off (ARIA and native
|
||||
// tables, record cards).
|
||||
'in-[[role=table]]:hidden',
|
||||
'in-[table]:hidden',
|
||||
'in-[[data-card]]:hidden',
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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';
|
||||
@@ -31,6 +32,8 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
? await getSpaceLanguage(context.contentContext)
|
||||
: defaultLanguage;
|
||||
|
||||
const showHashLink = shouldShowHashLinks(context);
|
||||
|
||||
return (
|
||||
<Details
|
||||
id={id}
|
||||
@@ -41,7 +44,8 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
className={tcls(
|
||||
'cursor-pointer',
|
||||
'px-4',
|
||||
'pr-10',
|
||||
// Reserve room for the anchor icon pinned to the right edge
|
||||
showHashLink && 'pr-10',
|
||||
'py-4',
|
||||
'relative',
|
||||
'list-none',
|
||||
@@ -71,32 +75,34 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
|
||||
context={context}
|
||||
ancestorInlines={[]}
|
||||
/>
|
||||
<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"
|
||||
{showHashLink ? (
|
||||
<a
|
||||
href={`#${id}`}
|
||||
aria-label={tString(language, 'direct_link_to_heading')}
|
||||
className={tcls(
|
||||
'inline-block',
|
||||
'size-3',
|
||||
'transition-colors',
|
||||
'text-transparent',
|
||||
'group-hover/expandable:text-tint-subtle',
|
||||
'contrast-more:group-hover/expandable:text-tint-strong'
|
||||
'absolute',
|
||||
'top-2',
|
||||
'bottom-2',
|
||||
'right-4',
|
||||
'flex',
|
||||
'items-center',
|
||||
'dark:shadow-none',
|
||||
'dark:ring-0'
|
||||
)}
|
||||
/>
|
||||
</a>
|
||||
>
|
||||
<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}
|
||||
</summary>
|
||||
<Blocks
|
||||
nodes={body.nodes}
|
||||
|
||||
@@ -2,9 +2,22 @@ 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 } from './HashLinkButton';
|
||||
import { HashLinkButton, hashLinkButtonWrapperStyles, shouldShowHashLinks } from './HashLinkButton';
|
||||
import { HeadingRevealWrapper } from './HeadingRevealWrapper';
|
||||
import { Inlines } from './Inlines';
|
||||
import { getBlockTextStyle } from './spacing';
|
||||
@@ -24,6 +24,8 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
? await getSpaceLanguage(context.contentContext)
|
||||
: defaultLanguage;
|
||||
|
||||
const showHashLink = shouldShowHashLinks(context);
|
||||
|
||||
return (
|
||||
<HeadingRevealWrapper
|
||||
as={Tag}
|
||||
@@ -34,7 +36,8 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
'font-heading',
|
||||
'pdf-heading',
|
||||
'block',
|
||||
'pr-6',
|
||||
// Reserve room for the absolutely positioned anchor icon on coarse pointers
|
||||
showHashLink && 'pr-6',
|
||||
'pointer-fine:flex',
|
||||
'pointer-fine:items-baseline',
|
||||
'pointer-fine:pr-0',
|
||||
@@ -63,20 +66,22 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
|
||||
<Inlines {...rest} context={context} nodes={block.nodes} ancestorInlines={[]} />
|
||||
</span>
|
||||
|
||||
<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')}
|
||||
/>
|
||||
{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}
|
||||
</HeadingRevealWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
'use client';
|
||||
import { useAI, useAIChatController, useAIChatState } from '../AI';
|
||||
import { useAI, useAIChatState } from '../AI';
|
||||
import { Button, type ButtonProps, Input } from '../primitives';
|
||||
import { useSetSearchState } from '../Search';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
@@ -18,17 +18,13 @@ export function InlineActionButton(
|
||||
const { action, query, buttonProps } = props;
|
||||
|
||||
const { assistants } = useAI();
|
||||
const chatController = useAIChatController();
|
||||
const chatState = useAIChatState();
|
||||
const setSearchState = useSetSearchState();
|
||||
const language = useLanguage();
|
||||
|
||||
const handleSubmit = (value: string) => {
|
||||
if (action === 'ask') {
|
||||
chatController.open();
|
||||
if (value ?? query) {
|
||||
chatController.postMessage({ message: value ?? query });
|
||||
}
|
||||
assistants[0]?.open(value || query);
|
||||
} else if (action === 'search') {
|
||||
setSearchState((prev) => ({
|
||||
...prev,
|
||||
|
||||
@@ -52,8 +52,8 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
const anchorElement = (
|
||||
<InlineLinkAnchor
|
||||
href={resolved.href}
|
||||
contentRef={inline.data.ref}
|
||||
isExternal={inline.data.ref.kind === 'url'}
|
||||
contentRef={resolved.resolvedRef ?? inline.data.ref}
|
||||
isExternal={(resolved.resolvedRef ?? 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 = inline.data.ref.kind === 'url';
|
||||
const isExternal = (resolved.resolvedRef ?? 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 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;
|
||||
@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;
|
||||
}
|
||||
|
||||
.contentkit-button-style-primary {
|
||||
@@ -130,15 +130,38 @@
|
||||
.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;
|
||||
}
|
||||
@@ -208,9 +231,6 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
'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,14 +5,11 @@ import React from 'react';
|
||||
import type { DocumentBlockPrompt } from '@gitbook/api';
|
||||
import { Icon, type IconName } from '@gitbook/icons';
|
||||
|
||||
import { Button, DropdownMenu, DropdownMenuItem, ToggleChevron } from '@/components/primitives';
|
||||
import { getURLForLLM } from '@/components/utils';
|
||||
import { PromptActions } from './PromptActions';
|
||||
import { ToggleChevron } from '@/components/primitives';
|
||||
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;
|
||||
@@ -88,106 +85,3 @@ 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',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
'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
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { getTableCellMerge } from './cellMerges';
|
||||
import { getColumnWidth, getViewGridLayout, hasVisibleHeader } from './layout';
|
||||
import { RecordColumnValue } from './RecordColumnValue';
|
||||
import { StickyViewGrid } from './StickyViewGrid';
|
||||
import type { TableGridViewProps } from './Table';
|
||||
import { TableHoverTable } from './TableHoverTable';
|
||||
import { TableSearchTableBody } from './TableSearch';
|
||||
import { type VerticalAlignment, getColumnAlignment, getColumnVerticalAlignment } from './utils';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
/** Semantic table renderer used when a cell spans multiple records. */
|
||||
export function NativeViewGrid(props: TableGridViewProps) {
|
||||
const { block, view, context, style } = props;
|
||||
const { tableWidth } = getViewGridLayout({
|
||||
block,
|
||||
view,
|
||||
mode: context.mode,
|
||||
});
|
||||
const tableContainerClassName = tableWidth === 'w-full' ? 'min-w-full w-fit' : tableWidth;
|
||||
const withHeader = hasVisibleHeader(block, view);
|
||||
const withStickyHeader = withHeader && context.mode !== 'print' && view.stickyHeader === true;
|
||||
const withStickyFirstColumn = context.mode !== 'print' && view.stickyFirstColumn === true;
|
||||
const header = withHeader ? (
|
||||
<NativeViewGridHeader
|
||||
{...props}
|
||||
stickyHeader={withStickyHeader}
|
||||
stickyFirstColumn={withStickyFirstColumn}
|
||||
className={tcls(
|
||||
withStickyHeader
|
||||
? [
|
||||
'mb-0 border-t border-r border-l',
|
||||
'group-data-[scrollable=false]/table:mb-1',
|
||||
'group-data-[scrollable=false]/table:rounded-b-lg',
|
||||
'group-data-[scrollable=true]/table:border-t-0',
|
||||
'group-data-[scrollable=true]/table:border-x-0',
|
||||
]
|
||||
: undefined
|
||||
)}
|
||||
/>
|
||||
) : undefined;
|
||||
const body = (
|
||||
<NativeViewGridBody
|
||||
{...props}
|
||||
withHeader={withHeader}
|
||||
stickyFirstColumn={withStickyFirstColumn}
|
||||
/>
|
||||
);
|
||||
|
||||
if (withStickyHeader || withStickyFirstColumn) {
|
||||
return (
|
||||
<StickyViewGrid
|
||||
className={tcls(style, 'relative mx-auto grid w-full min-w-0')}
|
||||
stickyHeader={withStickyHeader}
|
||||
tableClassName={tableContainerClassName}
|
||||
withTableRole={false}
|
||||
header={header}
|
||||
>
|
||||
{body}
|
||||
</StickyViewGrid>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={tcls(style, 'relative mx-auto grid w-full min-w-0')}>
|
||||
<div className="w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle">
|
||||
<div className={tcls('flex flex-col', tableContainerClassName)}>
|
||||
{header}
|
||||
{body}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeViewGridHeader(
|
||||
props: TableGridViewProps & {
|
||||
stickyHeader: boolean;
|
||||
stickyFirstColumn: boolean;
|
||||
className?: string;
|
||||
}
|
||||
) {
|
||||
const { block, view, stickyHeader, stickyFirstColumn, className } = props;
|
||||
const firstVisibleColumn = view.columns[0];
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className={tcls(
|
||||
'mb-1 rounded-lg border border-tint-subtle bg-tint',
|
||||
stickyHeader || !stickyFirstColumn ? 'overflow-hidden' : undefined,
|
||||
className
|
||||
)}
|
||||
>
|
||||
<table className="w-full table-fixed border-separate border-spacing-0">
|
||||
<NativeViewGridColumns {...props} />
|
||||
<thead>
|
||||
<tr>
|
||||
{view.columns.map((column) => {
|
||||
const definition = block.data.definition[column];
|
||||
if (!definition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isStickyFirstColumn =
|
||||
stickyFirstColumn && column === firstVisibleColumn;
|
||||
return (
|
||||
<th
|
||||
key={column}
|
||||
scope="col"
|
||||
className={tcls(
|
||||
'relative px-3 py-2 font-medium text-sm text-tint-strong',
|
||||
isStickyFirstColumn
|
||||
? stickyHeader
|
||||
? 'z-20 bg-tint'
|
||||
: 'sticky left-0 z-20 bg-tint'
|
||||
: undefined,
|
||||
getColumnAlignment(definition)
|
||||
)}
|
||||
style={{
|
||||
left:
|
||||
stickyHeader && isStickyFirstColumn
|
||||
? 'calc(-1 * var(--table-sticky-scroll-left, 0px))'
|
||||
: undefined,
|
||||
}}
|
||||
title={definition.title}
|
||||
>
|
||||
{definition.title}
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeViewGridBody(
|
||||
props: TableGridViewProps & {
|
||||
withHeader: boolean;
|
||||
stickyFirstColumn: boolean;
|
||||
}
|
||||
) {
|
||||
const { block, view, records, withHeader, stickyFirstColumn, cellMergeLayout } = props;
|
||||
const firstVisibleColumn = view.columns[0];
|
||||
const lastVisibleColumn = view.columns.at(-1);
|
||||
const recordsById = new Map(records.map((record) => [record[0], record] as const));
|
||||
const recordIndexes = new Map(records.map((record, index) => [record[0], index] as const));
|
||||
|
||||
return (
|
||||
<TableHoverTable
|
||||
className={tcls(
|
||||
'w-full table-fixed border-separate border-spacing-0',
|
||||
'[&>tbody>tr>td[data-table-hovered]]:bg-tint-hover',
|
||||
'[&>tbody>tr+tr>td]:border-t',
|
||||
'[&>tbody+tbody>tr:first-child>td]:border-t'
|
||||
)}
|
||||
>
|
||||
<NativeViewGridColumns {...props} />
|
||||
{withHeader ? (
|
||||
<thead className="sr-only">
|
||||
<tr>
|
||||
{view.columns.map((column) => {
|
||||
const definition = block.data.definition[column];
|
||||
return definition ? (
|
||||
<th key={column} scope="col">
|
||||
{definition.title}
|
||||
</th>
|
||||
) : null;
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
) : null}
|
||||
{cellMergeLayout.recordGroups.map((recordGroup) => (
|
||||
<TableSearchTableBody key={recordGroup[0]} recordIds={recordGroup}>
|
||||
{recordGroup.map((recordId) => {
|
||||
const record = recordsById.get(recordId);
|
||||
const recordIndex = recordIndexes.get(recordId);
|
||||
if (!record || recordIndex === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<tr key={recordId}>
|
||||
{view.columns.map((column) => {
|
||||
const cellMerge = getTableCellMerge(
|
||||
cellMergeLayout,
|
||||
recordId,
|
||||
column
|
||||
);
|
||||
if (cellMerge && !cellMerge.isAnchor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const definition = block.data.definition[column];
|
||||
if (!definition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const verticalAlignment =
|
||||
getColumnVerticalAlignment(definition);
|
||||
const renderedColumns = cellMerge?.merge.columns ?? [column];
|
||||
const isLastColumn =
|
||||
renderedColumns.at(-1) === lastVisibleColumn;
|
||||
const isStickyFirstColumn =
|
||||
stickyFirstColumn && column === firstVisibleColumn;
|
||||
const rowSpan =
|
||||
cellMerge && cellMerge.merge.rowSpan > 1
|
||||
? cellMerge.merge.rowSpan
|
||||
: undefined;
|
||||
const colSpan =
|
||||
cellMerge && cellMerge.merge.colSpan > 1
|
||||
? cellMerge.merge.colSpan
|
||||
: undefined;
|
||||
return (
|
||||
<td
|
||||
key={column}
|
||||
rowSpan={rowSpan}
|
||||
colSpan={colSpan}
|
||||
aria-rowspan={rowSpan}
|
||||
aria-colspan={colSpan}
|
||||
data-table-row-start={recordIndex}
|
||||
data-table-row-end={
|
||||
recordIndex + (cellMerge?.merge.rowSpan ?? 1) - 1
|
||||
}
|
||||
className={tcls(
|
||||
'relative px-3 py-2 text-sm transition-colors',
|
||||
!isLastColumn
|
||||
? 'border-tint-subtle border-r'
|
||||
: undefined,
|
||||
getNativeCellVerticalAlignment(verticalAlignment),
|
||||
isStickyFirstColumn
|
||||
? 'sticky left-0 z-10 bg-tint-base'
|
||||
: undefined
|
||||
)}
|
||||
>
|
||||
<RecordColumnValue
|
||||
{...props}
|
||||
record={record}
|
||||
column={column}
|
||||
verticalAlignment={verticalAlignment}
|
||||
/>
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</TableSearchTableBody>
|
||||
))}
|
||||
</TableHoverTable>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeViewGridColumns(props: TableGridViewProps) {
|
||||
const { block, view, context } = props;
|
||||
const { columnWidths, autoSizedColumns, fixedColumns } = getViewGridLayout({
|
||||
block,
|
||||
view,
|
||||
mode: context.mode,
|
||||
});
|
||||
|
||||
return (
|
||||
<colgroup>
|
||||
{view.columns.map((column) => (
|
||||
<col
|
||||
key={column}
|
||||
style={{
|
||||
width: getColumnWidth({
|
||||
column,
|
||||
columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</colgroup>
|
||||
);
|
||||
}
|
||||
|
||||
function getNativeCellVerticalAlignment(verticalAlignment: VerticalAlignment) {
|
||||
switch (verticalAlignment) {
|
||||
case 'self-start':
|
||||
return 'align-top';
|
||||
case 'self-end':
|
||||
return 'align-bottom';
|
||||
case 'self-center':
|
||||
return 'align-middle';
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,19 @@
|
||||
import type { DocumentTableViewGrid } from '@gitbook/api';
|
||||
|
||||
import { getMergedCellWidth, getTableCellMerge } from './cellMerges';
|
||||
import { getColumnWidth } from './layout';
|
||||
import { RecordColumnValue } from './RecordColumnValue';
|
||||
import type { TableRecordKV, TableViewProps } from './Table';
|
||||
import type { TableGridViewProps, TableRecordKV } from './Table';
|
||||
import { TableSearchRecord } from './TableSearch';
|
||||
import { getColumnVerticalAlignment } from './utils';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export function RecordRow(
|
||||
props: TableViewProps<DocumentTableViewGrid> & {
|
||||
props: TableGridViewProps & {
|
||||
record: TableRecordKV;
|
||||
autoSizedColumns: string[];
|
||||
fixedColumns: string[];
|
||||
}
|
||||
) {
|
||||
const { view, record, autoSizedColumns, fixedColumns, block, context } = props;
|
||||
const { view, record, autoSizedColumns, fixedColumns, block, context, cellMergeLayout } = props;
|
||||
const stickyFirstColumn = context.mode !== 'print' && view.stickyFirstColumn === true;
|
||||
const firstVisibleColumn = view.columns[0];
|
||||
|
||||
@@ -31,12 +30,22 @@ export function RecordRow(
|
||||
)}
|
||||
>
|
||||
{view.columns.map((column) => {
|
||||
const columnWidth = getColumnWidth({
|
||||
column,
|
||||
columnWidths: context.mode === 'print' ? undefined : view.columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
});
|
||||
const cellMerge = getTableCellMerge(cellMergeLayout, record[0], column);
|
||||
if (cellMerge && !cellMerge.isAnchor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const renderedColumns = cellMerge?.merge.columns ?? [column];
|
||||
const columnWidth = getMergedCellWidth(
|
||||
renderedColumns.map((mergedColumn) =>
|
||||
getColumnWidth({
|
||||
column: mergedColumn,
|
||||
columnWidths: context.mode === 'print' ? undefined : view.columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
})
|
||||
)
|
||||
);
|
||||
const isStickyFirstColumnCell = stickyFirstColumn && column === firstVisibleColumn;
|
||||
// @ts-expect-error
|
||||
const verticalAlignment = getColumnVerticalAlignment(block.data.definition[column]);
|
||||
@@ -45,6 +54,7 @@ export function RecordRow(
|
||||
<div
|
||||
key={column}
|
||||
role="cell"
|
||||
aria-colspan={cellMerge?.merge.colSpan}
|
||||
className={tcls(
|
||||
'relative flex flex-1 border-r px-3 py-2 align-middle text-sm last:border-r-0',
|
||||
'border-tint-subtle',
|
||||
|
||||
@@ -9,6 +9,7 @@ interface StickyViewGridProps {
|
||||
header?: ReactNode;
|
||||
stickyHeader?: boolean;
|
||||
tableClassName?: string;
|
||||
withTableRole?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
@@ -23,6 +24,7 @@ function DefaultHeaderScrollGrid({
|
||||
className,
|
||||
header,
|
||||
tableClassName,
|
||||
withTableRole = true,
|
||||
children,
|
||||
}: StickyViewGridProps) {
|
||||
const resolvedTableClassName = tableClassName ?? 'w-fit';
|
||||
@@ -30,7 +32,7 @@ function DefaultHeaderScrollGrid({
|
||||
return (
|
||||
<div className={className}>
|
||||
<div
|
||||
role="table"
|
||||
role={withTableRole ? 'table' : undefined}
|
||||
className="group/table relative flex w-full min-w-0 max-w-full flex-col rounded-lg border-tint-subtle"
|
||||
>
|
||||
<div className="w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle">
|
||||
@@ -48,6 +50,7 @@ function StickyHeaderOverlayScrollGrid({
|
||||
className,
|
||||
header,
|
||||
tableClassName,
|
||||
withTableRole = true,
|
||||
children,
|
||||
}: StickyViewGridProps) {
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
@@ -141,7 +144,7 @@ function StickyHeaderOverlayScrollGrid({
|
||||
ref={rootRef}
|
||||
className="group/table relative flex w-full min-w-0 max-w-full flex-col rounded-lg border-tint-subtle data-[scrollable=true]:border"
|
||||
data-scrollable="false"
|
||||
role="table"
|
||||
role={withTableRole ? 'table' : undefined}
|
||||
>
|
||||
{header ? (
|
||||
<div
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
import type { DocumentBlockTable } from '@gitbook/api';
|
||||
import type { DocumentBlockTable, DocumentTableViewGrid } from '@gitbook/api';
|
||||
|
||||
import type { BlockProps } from '../Block';
|
||||
import { isBlockOffscreen } from '../utils';
|
||||
import { type TableCellMergeLayout, createTableCellMergeLayout } from './cellMerges';
|
||||
import { getViewGridLayout, hasVisibleHeader } from './layout';
|
||||
import { NativeViewGrid } from './NativeViewGrid';
|
||||
import {
|
||||
type TableRecordKV,
|
||||
getTableCheckboxColumns,
|
||||
@@ -26,6 +28,10 @@ export interface TableViewProps<View> extends BlockProps<DocumentBlockTable> {
|
||||
isOffscreen: boolean;
|
||||
}
|
||||
|
||||
export interface TableGridViewProps extends TableViewProps<DocumentTableViewGrid> {
|
||||
cellMergeLayout: TableCellMergeLayout;
|
||||
}
|
||||
|
||||
export function Table(props: BlockProps<DocumentBlockTable>) {
|
||||
const { block, ancestorBlocks, document, context, style } = props;
|
||||
const isOffscreen = isBlockOffscreen({ block, ancestorBlocks, document });
|
||||
@@ -45,9 +51,18 @@ export function Table(props: BlockProps<DocumentBlockTable>) {
|
||||
const searchRecords = showSearch
|
||||
? records.map(([id, record]) => ({ id, ...getTableRecordSearchData(block, record) }))
|
||||
: [];
|
||||
const cellMergeLayout = createTableCellMergeLayout(
|
||||
block,
|
||||
records.map(([recordId]) => recordId)
|
||||
);
|
||||
|
||||
return (
|
||||
<TableSearchProvider records={searchRecords}>
|
||||
<TableSearchProvider
|
||||
records={searchRecords}
|
||||
recordGroups={
|
||||
block.data.view.type === 'grid' ? cellMergeLayout.recordGroups : undefined
|
||||
}
|
||||
>
|
||||
<div className={tcls(style, 'flex flex-col gap-3')}>
|
||||
{showSearch ? (
|
||||
<TableSearchInput
|
||||
@@ -55,7 +70,12 @@ export function Table(props: BlockProps<DocumentBlockTable>) {
|
||||
checkboxColumns={getTableCheckboxColumns(block)}
|
||||
/>
|
||||
) : null}
|
||||
<TableView {...props} isOffscreen={isOffscreen} records={records} />
|
||||
<TableView
|
||||
{...props}
|
||||
isOffscreen={isOffscreen}
|
||||
records={records}
|
||||
cellMergeLayout={cellMergeLayout}
|
||||
/>
|
||||
<TableSearchEmpty />
|
||||
</div>
|
||||
</TableSearchProvider>
|
||||
@@ -68,8 +88,13 @@ export function Table(props: BlockProps<DocumentBlockTable>) {
|
||||
function TableView({
|
||||
isOffscreen,
|
||||
records,
|
||||
cellMergeLayout,
|
||||
...props
|
||||
}: BlockProps<DocumentBlockTable> & { isOffscreen: boolean; records: TableRecordKV[] }) {
|
||||
}: BlockProps<DocumentBlockTable> & {
|
||||
isOffscreen: boolean;
|
||||
records: TableRecordKV[];
|
||||
cellMergeLayout: TableCellMergeLayout;
|
||||
}) {
|
||||
const { block, context, style } = props;
|
||||
|
||||
switch (block.data.view.type) {
|
||||
@@ -88,6 +113,7 @@ function TableView({
|
||||
view: block.data.view,
|
||||
isOffscreen,
|
||||
records,
|
||||
cellMergeLayout,
|
||||
};
|
||||
const { tableWidth } = getViewGridLayout({
|
||||
block,
|
||||
@@ -102,6 +128,10 @@ function TableView({
|
||||
const withStickyFirstColumn =
|
||||
context.mode !== 'print' && block.data.view.stickyFirstColumn === true;
|
||||
|
||||
if (cellMergeLayout.hasVerticalMerges) {
|
||||
return <NativeViewGrid {...gridProps} />;
|
||||
}
|
||||
|
||||
if (withStickyHeader || withStickyFirstColumn) {
|
||||
return (
|
||||
<StickyViewGrid
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { type TableRowRange, tableRowRangesIntersect } from './TableHoverTable';
|
||||
|
||||
const CELL_RANGES = {
|
||||
A: { rowStart: 0, rowEnd: 1 },
|
||||
B: { rowStart: 0, rowEnd: 0 },
|
||||
C: { rowStart: 0, rowEnd: 0 },
|
||||
D: { rowStart: 1, rowEnd: 1 },
|
||||
E: { rowStart: 1, rowEnd: 2 },
|
||||
F: { rowStart: 2, rowEnd: 2 },
|
||||
G: { rowStart: 2, rowEnd: 2 },
|
||||
} satisfies Record<string, TableRowRange>;
|
||||
|
||||
function getHighlightedCells(hoveredCell: keyof typeof CELL_RANGES) {
|
||||
const hoveredRange = CELL_RANGES[hoveredCell];
|
||||
return Object.entries(CELL_RANGES)
|
||||
.filter(([, cellRange]) => tableRowRangesIntersect(cellRange, hoveredRange))
|
||||
.map(([cell]) => cell);
|
||||
}
|
||||
|
||||
describe('tableRowRangesIntersect', () => {
|
||||
it.each([
|
||||
['A', ['A', 'B', 'C', 'D', 'E']],
|
||||
['B', ['A', 'B', 'C']],
|
||||
['D', ['A', 'D', 'E']],
|
||||
['E', ['A', 'D', 'E', 'F', 'G']],
|
||||
] as const)(
|
||||
'highlights cells intersecting %s without transitive expansion',
|
||||
(cell, expected) => {
|
||||
expect(getHighlightedCells(cell)).toEqual([...expected]);
|
||||
}
|
||||
);
|
||||
|
||||
it('treats a horizontal merge as a single-row range', () => {
|
||||
const horizontalMerge = { rowStart: 1, rowEnd: 1 };
|
||||
|
||||
expect(
|
||||
Object.entries(CELL_RANGES)
|
||||
.filter(([, cellRange]) => tableRowRangesIntersect(cellRange, horizontalMerge))
|
||||
.map(([cell]) => cell)
|
||||
).toEqual(['A', 'D', 'E']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client';
|
||||
|
||||
import { type ComponentPropsWithoutRef, type MouseEvent as ReactMouseEvent, useRef } from 'react';
|
||||
|
||||
const TABLE_CELL_SELECTOR = 'td[data-table-row-start][data-table-row-end]';
|
||||
|
||||
export interface TableRowRange {
|
||||
rowStart: number;
|
||||
rowEnd: number;
|
||||
}
|
||||
|
||||
export function tableRowRangesIntersect(left: TableRowRange, right: TableRowRange) {
|
||||
return left.rowStart <= right.rowEnd && right.rowStart <= left.rowEnd;
|
||||
}
|
||||
|
||||
/** Applies hover feedback to cells intersecting the hovered cell's original row span. */
|
||||
export function TableHoverTable(props: ComponentPropsWithoutRef<'table'>) {
|
||||
const { onMouseOver, onMouseLeave, ...rest } = props;
|
||||
const hoveredCellRef = useRef<HTMLTableCellElement | null>(null);
|
||||
const highlightedCellsRef = useRef<Set<HTMLTableCellElement>>(new Set());
|
||||
|
||||
const clearHighlightedCells = () => {
|
||||
for (const cell of highlightedCellsRef.current) {
|
||||
cell.removeAttribute('data-table-hovered');
|
||||
}
|
||||
highlightedCellsRef.current.clear();
|
||||
hoveredCellRef.current = null;
|
||||
};
|
||||
|
||||
const handleMouseOver = (event: ReactMouseEvent<HTMLTableElement>) => {
|
||||
onMouseOver?.(event);
|
||||
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) {
|
||||
clearHighlightedCells();
|
||||
return;
|
||||
}
|
||||
|
||||
const hoveredCell = target.closest<HTMLTableCellElement>(TABLE_CELL_SELECTOR);
|
||||
if (!hoveredCell || !event.currentTarget.contains(hoveredCell)) {
|
||||
clearHighlightedCells();
|
||||
return;
|
||||
}
|
||||
if (hoveredCellRef.current === hoveredCell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hoveredRange = getTableCellRowRange(hoveredCell);
|
||||
if (!hoveredRange) {
|
||||
clearHighlightedCells();
|
||||
return;
|
||||
}
|
||||
|
||||
const highlightedCells = new Set<HTMLTableCellElement>();
|
||||
for (const cell of event.currentTarget.querySelectorAll<HTMLTableCellElement>(
|
||||
TABLE_CELL_SELECTOR
|
||||
)) {
|
||||
const cellRange = getTableCellRowRange(cell);
|
||||
const highlighted =
|
||||
cellRange !== null && tableRowRangesIntersect(cellRange, hoveredRange);
|
||||
cell.toggleAttribute('data-table-hovered', highlighted);
|
||||
if (highlighted) {
|
||||
highlightedCells.add(cell);
|
||||
}
|
||||
}
|
||||
|
||||
for (const cell of highlightedCellsRef.current) {
|
||||
if (!highlightedCells.has(cell)) {
|
||||
cell.removeAttribute('data-table-hovered');
|
||||
}
|
||||
}
|
||||
|
||||
hoveredCellRef.current = hoveredCell;
|
||||
highlightedCellsRef.current = highlightedCells;
|
||||
};
|
||||
|
||||
const handleMouseLeave = (event: ReactMouseEvent<HTMLTableElement>) => {
|
||||
onMouseLeave?.(event);
|
||||
clearHighlightedCells();
|
||||
};
|
||||
|
||||
return <table {...rest} onMouseOver={handleMouseOver} onMouseLeave={handleMouseLeave} />;
|
||||
}
|
||||
|
||||
function getTableCellRowRange(cell: HTMLTableCellElement): TableRowRange | null {
|
||||
const rowStart = Number(cell.dataset.tableRowStart);
|
||||
const rowEnd = Number(cell.dataset.tableRowEnd);
|
||||
if (!Number.isInteger(rowStart) || !Number.isInteger(rowEnd) || rowEnd < rowStart) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { rowStart, rowEnd };
|
||||
}
|
||||
@@ -5,7 +5,11 @@ import React from 'react';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import type { TableCheckboxColumn, TableSelectColumn } from './search';
|
||||
import { type SelectedOptions, recordMatches } from './searchMatch';
|
||||
import {
|
||||
type SelectedOptions,
|
||||
type TableSearchRecordData,
|
||||
getVisibleTableRecordIds,
|
||||
} from './searchMatch';
|
||||
import { Button, Checkbox, DropdownMenu, DropdownMenuItem, Input } from '@/components/primitives';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
@@ -18,15 +22,6 @@ import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
* once and exposes the set of visible ids; each row/card just looks itself up by id.
|
||||
*/
|
||||
|
||||
/** Per-record matching data, computed on the server. */
|
||||
export interface TableSearchRecordData {
|
||||
/** Record key, matching the `key` passed to `<TableSearchRecord>`. */
|
||||
id: string;
|
||||
searchText: string;
|
||||
selectValues?: Record<string, string[]>;
|
||||
checkboxValues?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
type TableSearchContextValue = {
|
||||
query: string;
|
||||
setQuery: (query: string) => void;
|
||||
@@ -51,9 +46,10 @@ const TableSearchContext = React.createContext<TableSearchContextValue | null>(n
|
||||
*/
|
||||
export function TableSearchProvider(props: {
|
||||
records?: TableSearchRecordData[];
|
||||
recordGroups?: readonly (readonly string[])[];
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { records = [] } = props;
|
||||
const { records = [], recordGroups = [] } = props;
|
||||
const [query, setQuery] = React.useState('');
|
||||
const [selectedOptions, setSelectedOptions] = React.useState<SelectedOptions>(() => ({}));
|
||||
const [checkedColumns, setCheckedColumns] = React.useState<ReadonlySet<string>>(
|
||||
@@ -91,32 +87,18 @@ export function TableSearchProvider(props: {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const hasActiveFilters =
|
||||
query.trim() !== '' || Object.keys(selectedOptions).length > 0 || checkedColumns.size > 0;
|
||||
|
||||
// Match every record once, here, rather than in each row — rows just look themselves up by id.
|
||||
const visibleIds = React.useMemo(() => {
|
||||
if (!hasActiveFilters) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ids = new Set<string>();
|
||||
for (const record of records) {
|
||||
if (
|
||||
recordMatches(
|
||||
record.searchText,
|
||||
record.selectValues,
|
||||
record.checkboxValues,
|
||||
query,
|
||||
selectedOptions,
|
||||
checkedColumns
|
||||
)
|
||||
) {
|
||||
ids.add(record.id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [records, query, selectedOptions, checkedColumns, hasActiveFilters]);
|
||||
const visibleIds = React.useMemo(
|
||||
() =>
|
||||
getVisibleTableRecordIds({
|
||||
records,
|
||||
recordGroups,
|
||||
query,
|
||||
selectedOptions,
|
||||
checkedColumns,
|
||||
}),
|
||||
[records, recordGroups, query, selectedOptions, checkedColumns]
|
||||
);
|
||||
|
||||
const isEmpty = visibleIds !== null && records.length > 0 && visibleIds.size === 0;
|
||||
|
||||
@@ -244,11 +226,10 @@ function SelectFilterDropdown(props: { column: TableSelectColumn }) {
|
||||
key={option.value}
|
||||
active={selected}
|
||||
leadingIcon={selected ? 'check' : undefined}
|
||||
onSelect={(event) => {
|
||||
// Keep the menu open so several options can be toggled at once.
|
||||
event.preventDefault();
|
||||
toggleOption(column.id, option.value);
|
||||
}}
|
||||
// `closeOnClick={false}` keeps the menu open so several options can be
|
||||
// toggled at once.
|
||||
closeOnClick={false}
|
||||
onClick={() => toggleOption(column.id, option.value)}
|
||||
>
|
||||
{option.label || option.value}
|
||||
</DropdownMenuItem>
|
||||
@@ -310,3 +291,13 @@ export function TableSearchRecord(props: TableSearchRecordProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Keeps a complete native table row group visible when any of its records matches. */
|
||||
export function TableSearchTableBody(
|
||||
props: React.HTMLAttributes<HTMLTableSectionElement> & { recordIds: readonly string[] }
|
||||
) {
|
||||
const { recordIds, children, ...rest } = props;
|
||||
const { visibleIds } = useTableSearch();
|
||||
const matches = visibleIds === null || recordIds.some((recordId) => visibleIds.has(recordId));
|
||||
return matches ? <tbody {...rest}>{children}</tbody> : null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
|
||||
import { IconsProvider } from '@gitbook/icons';
|
||||
|
||||
import { TranslateContext } from '@/intl/client';
|
||||
import { en } from '@/intl/translations/en';
|
||||
|
||||
mock.module('./RecordCard', () => ({
|
||||
RecordCard: () => <div data-testid="record-card" />,
|
||||
}));
|
||||
|
||||
mock.module('./TableSearch', () => ({
|
||||
TableSearchRecord: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
|
||||
const { ViewCards } = await import('./ViewCards');
|
||||
|
||||
function makeProps(wrap: boolean) {
|
||||
return {
|
||||
block: { data: { fullWidth: false } },
|
||||
view: { type: 'cards', wrap, cardSize: 'medium' },
|
||||
records: [
|
||||
['record-1', {}],
|
||||
['record-2', {}],
|
||||
['record-3', {}],
|
||||
] as any,
|
||||
context: { mode: 'default' },
|
||||
style: undefined,
|
||||
} as any;
|
||||
}
|
||||
|
||||
function renderWithContext(children: React.ReactNode) {
|
||||
return renderToStaticMarkup(
|
||||
<IconsProvider assetsURL="https://icons.example.com">
|
||||
<TranslateContext.Provider value={en}>{children}</TranslateContext.Provider>
|
||||
</IconsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ViewCards', () => {
|
||||
it('renders the carousel with a symmetric peek and conditional edge masks', () => {
|
||||
const markup = renderWithContext(<ViewCards {...makeProps(false)} />);
|
||||
|
||||
expect(markup).toContain('-mx-12');
|
||||
expect(markup).toContain('px-12');
|
||||
expect(markup).toContain('scroll-px-12');
|
||||
expect(markup).toContain('left-0');
|
||||
expect(markup).toContain('ml-8');
|
||||
expect(markup).toContain('right-0');
|
||||
expect(markup).toContain('mr-8');
|
||||
expect(markup).not.toContain('before:bg-linear-to-r');
|
||||
expect(markup).not.toContain('after:bg-linear-to-l');
|
||||
expect(markup).toContain('snap-mandatory');
|
||||
});
|
||||
|
||||
it('renders the wrapping grid by default', () => {
|
||||
const markup = renderWithContext(<ViewCards {...makeProps(true)} />);
|
||||
|
||||
expect(markup).toContain('inline-grid');
|
||||
});
|
||||
});
|
||||
@@ -53,11 +53,9 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
|
||||
* The carousel layout: cards lay out in a single horizontally-scrolling row that
|
||||
* snaps to the leftmost card. Reuses ScrollContainer for the scroll buttons.
|
||||
*
|
||||
* Rather than fading the edges, the row breaks out of the content column so it can
|
||||
* scroll to the page edges. Negative margins on the outer wrapper pull it out; matching
|
||||
* padding + scroll-padding on the scroller keep the first/last cards aligned with the
|
||||
* body text at rest and snapping to that edge, while cards bleed to the edge mid-scroll.
|
||||
* See `bleedVars` below for how far each side reaches.
|
||||
* The row extends by a small, symmetric peek on each side. The matching padding keeps
|
||||
* the first and last cards aligned with the content column while the edge masks fade only
|
||||
* the cards in that peek area.
|
||||
*/
|
||||
function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
const { view, records } = props;
|
||||
@@ -69,65 +67,10 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
? 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]'
|
||||
: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]';
|
||||
|
||||
// Break the row out of the content column so it bleeds to the page edges instead of
|
||||
// fading. `--cards-bleed-l/r` are the distances to pull each side out by; they drive the
|
||||
// negative margins (on the wrapper) and the matching padding + scroll-padding (on the
|
||||
// scroller), so the first/last cards stay aligned with the body text at rest while cards
|
||||
// bleed to the edge mid-scroll. Kept as literals here since it's a single block.
|
||||
//
|
||||
// The bleed only makes sense on the default layout, where the 48rem column leaves wide
|
||||
// empty margins to reclaim. The wide layout (max-w-6xl) already fills the usable width,
|
||||
// so from `lg` we suppress the bleed entirely — otherwise the page gutter would push the
|
||||
// row past where every other block ends, jutting into the window frame.
|
||||
//
|
||||
// On the default layout:
|
||||
// - Left is capped at the page gutter (1/1.5/2rem) so it never slides under the TOC.
|
||||
// - Right reaches the viewport edge from `lg`. The 48rem column is centred in the space
|
||||
// beside the TOC, so the gap to the viewport edge is `50vw` minus half the column
|
||||
// (24rem), minus half the TOC (10.5rem of the 21rem `w-72`+`mr-12`) when one is shown.
|
||||
// `html` clips horizontal overflow, so a small overshoot is harmless.
|
||||
// - Right collapses to 0 once an outline occupies that column (shown from `xl`), so
|
||||
// cards never slide under it.
|
||||
const bleedVars = tcls(
|
||||
'[--cards-bleed-l:1rem]',
|
||||
'sm:[--cards-bleed-l:1.5rem]',
|
||||
'md:[--cards-bleed-l:2rem]',
|
||||
'layout-default:md:max-lg:[--cards-bleed-l:max(calc(50vw-24.5rem),2rem)]',
|
||||
'lg:[--cards-bleed-l:max(calc(50vw-34rem),3rem)]',
|
||||
'xl:[--cards-bleed-l:3rem]',
|
||||
|
||||
'[--cards-bleed-r:1rem]',
|
||||
'sm:[--cards-bleed-r:1.5rem]',
|
||||
'md:[--cards-bleed-r:2rem]',
|
||||
'layout-default:md:max-lg:[--cards-bleed-r:max(calc(50vw-24.5rem),2rem)]',
|
||||
'layout-default:lg:[--cards-bleed-r:max(calc(50vw-35rem),3rem)]',
|
||||
'layout-default:xl:[--cards-bleed-r:3rem]',
|
||||
|
||||
'hover:layout-default:no-sidebar:lg:max-xl:[--cards-bleed-l:max(calc(50vw-24.5rem),2rem)]',
|
||||
'hover:layout-default:no-sidebar:lg:max-xl:[--cards-bleed-r:max(calc(50vw-24.5rem),2rem)]',
|
||||
|
||||
// Default centered
|
||||
'hover:layout-default:no-sidebar:xl:[--cards-bleed-l:max(calc(50vw-22.5rem),2rem)]',
|
||||
'hover:layout-default:xl:[--cards-bleed-r:max(calc(50vw-26.5rem),19rem)]',
|
||||
|
||||
// Full width, no outline
|
||||
'hover:layout-wide:page-no-outline:2xl:[--cards-bleed-r:max(calc(50vw-43.5rem),0rem)]',
|
||||
|
||||
// Full width centered
|
||||
'layout-wide:no-sidebar:page-no-outline:2xl:[--cards-bleed-l:max(calc(50vw-36.5rem),0rem)]',
|
||||
'layout-wide:no-sidebar:page-no-outline:2xl:[--cards-bleed-r:max(calc(50vw-36.5rem),0rem)]'
|
||||
);
|
||||
|
||||
return (
|
||||
<ScrollContainer
|
||||
orientation="horizontal"
|
||||
className={tcls(
|
||||
bleedVars,
|
||||
'ml-[calc(var(--cards-bleed-l)*-1)]',
|
||||
'mr-[calc(var(--cards-bleed-r)*-1)]',
|
||||
'xl:transition-[margin]',
|
||||
'hover:z-11'
|
||||
)}
|
||||
className={tcls('-mx-12', 'hover:z-11')}
|
||||
// `py-1` keeps the card ring/shadow from being clipped by the scroll overflow;
|
||||
// `snap-mandatory` + the scroll-padding snap each card to the content edge.
|
||||
contentClassName={tcls(
|
||||
@@ -136,21 +79,19 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
|
||||
'-mt-px',
|
||||
'pb-6',
|
||||
'-mb-6',
|
||||
'pl-[var(--cards-bleed-l)]',
|
||||
'pr-[var(--cards-bleed-r)]',
|
||||
'scroll-pl-[var(--cards-bleed-l)]',
|
||||
'scroll-pr-[var(--cards-bleed-r)]',
|
||||
'px-12',
|
||||
'scroll-px-12',
|
||||
'snap-x',
|
||||
'snap-mandatory',
|
||||
'xl:transition-[padding]'
|
||||
'snap-mandatory'
|
||||
)}
|
||||
scrollByVisibleItems
|
||||
leading={{
|
||||
fade: true,
|
||||
button: { size: 'small', className: 'ml-[calc(var(--cards-bleed-l)-1rem)]' },
|
||||
button: { size: 'small', className: 'ml-8' },
|
||||
}}
|
||||
trailing={{
|
||||
fade: true,
|
||||
button: { size: 'small', className: 'mr-[calc(var(--cards-bleed-r)-1rem)]' },
|
||||
button: { size: 'small', className: 'mr-8' },
|
||||
}}
|
||||
>
|
||||
{records.map((record) => {
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
import type { DocumentTableViewGrid } from '@gitbook/api';
|
||||
|
||||
import { getColumnWidth, getViewGridLayout } from './layout';
|
||||
import { RecordRow } from './RecordRow';
|
||||
import type { TableViewProps } from './Table';
|
||||
import type { TableGridViewProps } from './Table';
|
||||
import { getColumnAlignment } from './utils';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
interface ViewGridHeaderProps extends TableViewProps<DocumentTableViewGrid> {
|
||||
interface ViewGridHeaderProps extends TableGridViewProps {
|
||||
className?: string;
|
||||
tableClassName?: string;
|
||||
}
|
||||
|
||||
interface ViewGridProps extends TableViewProps<DocumentTableViewGrid> {
|
||||
interface ViewGridProps extends TableGridViewProps {
|
||||
tableClassName?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import type { DocumentBlockTable, DocumentTableDefinition } from '@gitbook/api';
|
||||
|
||||
import { createTableCellMergeLayout, getMergedCellWidth, getTableCellMerge } from './cellMerges';
|
||||
|
||||
const RECORD_ORDER = ['first', 'second', 'third'];
|
||||
const COLUMN_ORDER = ['a', 'b', 'c'];
|
||||
|
||||
function createBlock(
|
||||
cellMerges?: unknown[],
|
||||
options: {
|
||||
columns?: string[];
|
||||
definitions?: Record<string, DocumentTableDefinition>;
|
||||
recordOrder?: string[];
|
||||
viewType?: 'grid' | 'cards';
|
||||
} = {}
|
||||
) {
|
||||
const columns = options.columns ?? COLUMN_ORDER;
|
||||
const recordOrder = options.recordOrder ?? RECORD_ORDER;
|
||||
const definitions =
|
||||
options.definitions ??
|
||||
Object.fromEntries(columns.map((column) => [column, createDefinition('text', column)]));
|
||||
return {
|
||||
data: {
|
||||
view:
|
||||
options.viewType === 'cards'
|
||||
? { type: 'cards', columns }
|
||||
: { type: 'grid', columns },
|
||||
records: Object.fromEntries(
|
||||
recordOrder.map((recordId, index) => [
|
||||
recordId,
|
||||
{ orderIndex: `${index}`, values: {} },
|
||||
])
|
||||
),
|
||||
definition: definitions,
|
||||
...(cellMerges ? { cellMerges } : {}),
|
||||
},
|
||||
} as unknown as DocumentBlockTable;
|
||||
}
|
||||
|
||||
function createDefinition(type: DocumentTableDefinition['type'], id: string) {
|
||||
const base = { id, title: id };
|
||||
return type === 'text'
|
||||
? ({ ...base, type, textAlignment: 'left' } as DocumentTableDefinition)
|
||||
: ({ ...base, type } as DocumentTableDefinition);
|
||||
}
|
||||
|
||||
describe('createTableCellMergeLayout', () => {
|
||||
it('classifies horizontal and vertical Text and Number merges', () => {
|
||||
for (const type of ['text', 'number'] as const) {
|
||||
const layout = createTableCellMergeLayout(
|
||||
createBlock([horizontalMerge('first', 'a', 2), verticalMerge('second', 'c', 2)], {
|
||||
definitions: Object.fromEntries(
|
||||
COLUMN_ORDER.map((column) => [column, createDefinition(type, column)])
|
||||
),
|
||||
}),
|
||||
RECORD_ORDER
|
||||
);
|
||||
|
||||
expect(getTableCellMerge(layout, 'first', 'a')).toMatchObject({
|
||||
isAnchor: true,
|
||||
merge: { rowSpan: 1, colSpan: 2, columns: ['a', 'b'] },
|
||||
});
|
||||
expect(getTableCellMerge(layout, 'first', 'b')).toMatchObject({ isAnchor: false });
|
||||
expect(getTableCellMerge(layout, 'second', 'c')).toMatchObject({
|
||||
isAnchor: true,
|
||||
merge: { rowSpan: 2, colSpan: 1, records: ['second', 'third'] },
|
||||
});
|
||||
expect(getTableCellMerge(layout, 'third', 'c')).toMatchObject({ isAnchor: false });
|
||||
expect(layout.recordGroups).toEqual([['first'], ['second', 'third']]);
|
||||
expect(layout.hasVerticalMerges).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('treats missing metadata and Cards as unmerged layouts', () => {
|
||||
const missing = createTableCellMergeLayout(createBlock(), RECORD_ORDER);
|
||||
const cards = createTableCellMergeLayout(
|
||||
createBlock([horizontalMerge('first', 'a', 2)], {
|
||||
viewType: 'cards',
|
||||
}),
|
||||
RECORD_ORDER
|
||||
);
|
||||
|
||||
expect(missing.cells.size).toBe(0);
|
||||
expect(missing.recordGroups).toEqual([['first'], ['second'], ['third']]);
|
||||
expect(missing.hasVerticalMerges).toBe(false);
|
||||
expect(cards.cells.size).toBe(0);
|
||||
expect(cards.recordGroups).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['invalid shape', { anchor: 'first', rowSpan: 1, colSpan: 2 }],
|
||||
['single cell', { anchor: { record: 'first', column: 'a' }, rowSpan: 1, colSpan: 1 }],
|
||||
['unknown record', horizontalMerge('missing', 'a', 2)],
|
||||
['hidden column', horizontalMerge('first', 'hidden', 2)],
|
||||
['out-of-bounds span', horizontalMerge('first', 'c', 2)],
|
||||
['rectangle', { anchor: { record: 'first', column: 'a' }, rowSpan: 2, colSpan: 2 }],
|
||||
])('ignores malformed metadata: %s', (_name, merge) => {
|
||||
const block = createBlock([merge], {
|
||||
definitions: {
|
||||
a: createDefinition('text', 'a'),
|
||||
b: createDefinition('text', 'b'),
|
||||
c: createDefinition('text', 'c'),
|
||||
hidden: createDefinition('text', 'hidden'),
|
||||
},
|
||||
});
|
||||
const layout = createTableCellMergeLayout(block, RECORD_ORDER);
|
||||
|
||||
expect(layout.cells.size).toBe(0);
|
||||
expect(layout.hasVerticalMerges).toBe(false);
|
||||
});
|
||||
|
||||
it('drops every conflicting merge regardless of order while preserving unrelated merges', () => {
|
||||
const horizontal = horizontalMerge('first', 'a', 2);
|
||||
const vertical = verticalMerge('first', 'b', 2);
|
||||
const duplicate = horizontalMerge('first', 'a', 2);
|
||||
const unrelated = verticalMerge('second', 'c', 2);
|
||||
|
||||
for (const cellMerges of [
|
||||
[horizontal, vertical, duplicate, unrelated],
|
||||
[vertical, duplicate, horizontal, unrelated],
|
||||
]) {
|
||||
const layout = createTableCellMergeLayout(createBlock(cellMerges), RECORD_ORDER);
|
||||
|
||||
expect(getTableCellMerge(layout, 'first', 'a')).toBeUndefined();
|
||||
expect(getTableCellMerge(layout, 'first', 'b')).toBeUndefined();
|
||||
expect(getTableCellMerge(layout, 'second', 'b')).toBeUndefined();
|
||||
expect(getTableCellMerge(layout, 'second', 'c')).toMatchObject({
|
||||
isAnchor: true,
|
||||
merge: { records: ['second', 'third'], columns: ['c'] },
|
||||
});
|
||||
expect(getTableCellMerge(layout, 'third', 'c')).toMatchObject({ isAnchor: false });
|
||||
expect(layout.recordGroups).toEqual([['first'], ['second', 'third']]);
|
||||
}
|
||||
});
|
||||
|
||||
it('partitions disjoint vertical merges and singleton records in record order', () => {
|
||||
const recordOrder = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
||||
const layout = createTableCellMergeLayout(
|
||||
createBlock([verticalMerge('fourth', 'b', 2), verticalMerge('first', 'a', 2)], {
|
||||
recordOrder,
|
||||
}),
|
||||
recordOrder
|
||||
);
|
||||
|
||||
expect(layout.recordGroups).toEqual([
|
||||
['first', 'second'],
|
||||
['third'],
|
||||
['fourth', 'fifth'],
|
||||
['sixth'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('combines transitively connected vertical merges regardless of metadata order', () => {
|
||||
for (const cellMerges of [
|
||||
[verticalMerge('first', 'a', 2), verticalMerge('second', 'b', 2)],
|
||||
[verticalMerge('second', 'b', 2), verticalMerge('first', 'a', 2)],
|
||||
]) {
|
||||
const layout = createTableCellMergeLayout(createBlock(cellMerges), RECORD_ORDER);
|
||||
|
||||
expect(layout.recordGroups).toEqual([['first', 'second', 'third']]);
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores merges for unsupported or mixed field types', () => {
|
||||
const unsupportedDefinitions = {
|
||||
a: createDefinition('checkbox', 'a'),
|
||||
b: createDefinition('checkbox', 'b'),
|
||||
};
|
||||
const unsupportedHorizontal = createTableCellMergeLayout(
|
||||
createBlock([horizontalMerge('first', 'a', 2)], {
|
||||
columns: ['a', 'b'],
|
||||
definitions: unsupportedDefinitions,
|
||||
}),
|
||||
RECORD_ORDER
|
||||
);
|
||||
const unsupportedVertical = createTableCellMergeLayout(
|
||||
createBlock([verticalMerge('first', 'a', 2)], {
|
||||
columns: ['a', 'b'],
|
||||
definitions: unsupportedDefinitions,
|
||||
}),
|
||||
RECORD_ORDER
|
||||
);
|
||||
const mixed = createTableCellMergeLayout(
|
||||
createBlock([horizontalMerge('first', 'a', 2)], {
|
||||
columns: ['a', 'b'],
|
||||
definitions: {
|
||||
a: createDefinition('text', 'a'),
|
||||
b: createDefinition('number', 'b'),
|
||||
},
|
||||
}),
|
||||
RECORD_ORDER
|
||||
);
|
||||
|
||||
expect(unsupportedHorizontal.cells.size).toBe(0);
|
||||
expect(unsupportedVertical.cells.size).toBe(0);
|
||||
expect(unsupportedVertical.hasVerticalMerges).toBe(false);
|
||||
expect(mixed.cells.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
function horizontalMerge(record: string, column: string, colSpan: number) {
|
||||
return { anchor: { record, column }, rowSpan: 1, colSpan };
|
||||
}
|
||||
|
||||
function verticalMerge(record: string, column: string, rowSpan: number) {
|
||||
return { anchor: { record, column }, rowSpan, colSpan: 1 };
|
||||
}
|
||||
|
||||
describe('getMergedCellWidth', () => {
|
||||
it('adds fixed and automatic column widths in CSS', () => {
|
||||
expect(getMergedCellWidth(['120px', 'clamp(100px, calc(100% / 2), 100%)'])).toBe(
|
||||
'calc(120px + clamp(100px, calc(100% / 2), 100%))'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import type { DocumentBlockTable } from '@gitbook/api';
|
||||
|
||||
/**
|
||||
* Temporary compatibility type until the published `@gitbook/api` includes `cellMerges`.
|
||||
*/
|
||||
export interface TableCellMerge {
|
||||
anchor: {
|
||||
record: string;
|
||||
column: string;
|
||||
};
|
||||
rowSpan: number;
|
||||
colSpan: number;
|
||||
}
|
||||
|
||||
type TableDataWithCellMerges = DocumentBlockTable['data'] & {
|
||||
cellMerges?: TableCellMerge[];
|
||||
};
|
||||
|
||||
export interface ResolvedTableCellMerge {
|
||||
records: readonly string[];
|
||||
columns: readonly string[];
|
||||
rowSpan: number;
|
||||
colSpan: number;
|
||||
}
|
||||
|
||||
export interface TableCellMergeSlot {
|
||||
merge: ResolvedTableCellMerge;
|
||||
isAnchor: boolean;
|
||||
}
|
||||
|
||||
export interface TableCellMergeLayout {
|
||||
cells: ReadonlyMap<string, ReadonlyMap<string, TableCellMergeSlot>>;
|
||||
recordGroups: readonly (readonly string[])[];
|
||||
hasVerticalMerges: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve valid merge metadata once for a rendered grid.
|
||||
*
|
||||
* Invalid external metadata is ignored before any cell can be classified as covered, ensuring a
|
||||
* malformed merge always degrades to ordinary cells instead of hiding content.
|
||||
*/
|
||||
export function createTableCellMergeLayout(
|
||||
block: DocumentBlockTable,
|
||||
recordOrder: readonly string[]
|
||||
): TableCellMergeLayout {
|
||||
if (block.data.view.type !== 'grid') {
|
||||
return {
|
||||
cells: new Map(),
|
||||
recordGroups: [],
|
||||
hasVerticalMerges: false,
|
||||
};
|
||||
}
|
||||
|
||||
const columnOrder = block.data.view.columns;
|
||||
const candidates: { merge: ResolvedTableCellMerge; cellKeys: string[] }[] = [];
|
||||
const cells = new Map<string, Map<string, TableCellMergeSlot>>();
|
||||
const verticalRecordGroups: string[][] = [];
|
||||
|
||||
for (const candidate of getRawTableCellMerges(block)) {
|
||||
const merge = resolveTableCellMerge(candidate, block, recordOrder, columnOrder);
|
||||
if (!merge) continue;
|
||||
|
||||
const cellKeys = merge.records.flatMap((recordId) =>
|
||||
merge.columns.map((columnId) => getCellKey(recordId, columnId))
|
||||
);
|
||||
candidates.push({ merge, cellKeys });
|
||||
}
|
||||
|
||||
const cellOwnerCounts = new Map<string, number>();
|
||||
for (const candidate of candidates) {
|
||||
for (const cellKey of candidate.cellKeys) {
|
||||
cellOwnerCounts.set(cellKey, (cellOwnerCounts.get(cellKey) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.cellKeys.some((cellKey) => cellOwnerCounts.get(cellKey) !== 1)) continue;
|
||||
const { merge } = candidate;
|
||||
|
||||
for (const recordId of merge.records) {
|
||||
let row = cells.get(recordId);
|
||||
if (!row) {
|
||||
row = new Map();
|
||||
cells.set(recordId, row);
|
||||
}
|
||||
|
||||
for (const columnId of merge.columns) {
|
||||
row.set(columnId, {
|
||||
merge,
|
||||
isAnchor: recordId === merge.records[0] && columnId === merge.columns[0],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (merge.rowSpan > 1) {
|
||||
verticalRecordGroups.push([...merge.records]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
cells,
|
||||
recordGroups: groupConnectedRecords(recordOrder, verticalRecordGroups),
|
||||
hasVerticalMerges: verticalRecordGroups.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Return the resolved merge classification for a logical table cell. */
|
||||
export function getTableCellMerge(
|
||||
layout: TableCellMergeLayout,
|
||||
recordId: string,
|
||||
columnId: string
|
||||
): TableCellMergeSlot | undefined {
|
||||
return layout.cells.get(recordId)?.get(columnId);
|
||||
}
|
||||
|
||||
/** Combine the independent column widths used by a horizontal merged cell. */
|
||||
export function getMergedCellWidth(widths: string[]): string {
|
||||
return widths.length === 1 && widths[0] ? widths[0] : `calc(${widths.join(' + ')})`;
|
||||
}
|
||||
|
||||
function getRawTableCellMerges(block: DocumentBlockTable): unknown[] {
|
||||
const data = block.data as TableDataWithCellMerges;
|
||||
return Array.isArray(data.cellMerges) ? data.cellMerges : [];
|
||||
}
|
||||
|
||||
function resolveTableCellMerge(
|
||||
candidate: unknown,
|
||||
block: DocumentBlockTable,
|
||||
recordOrder: readonly string[],
|
||||
columnOrder: readonly string[]
|
||||
): ResolvedTableCellMerge | null {
|
||||
if (!candidate || typeof candidate !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const merge = candidate as {
|
||||
anchor?: { record?: unknown; column?: unknown };
|
||||
rowSpan?: unknown;
|
||||
colSpan?: unknown;
|
||||
};
|
||||
if (
|
||||
typeof merge.anchor?.record !== 'string' ||
|
||||
typeof merge.anchor.column !== 'string' ||
|
||||
typeof merge.rowSpan !== 'number' ||
|
||||
!Number.isInteger(merge.rowSpan) ||
|
||||
merge.rowSpan < 1 ||
|
||||
typeof merge.colSpan !== 'number' ||
|
||||
!Number.isInteger(merge.colSpan) ||
|
||||
merge.colSpan < 1 ||
|
||||
!(
|
||||
(merge.rowSpan === 1 && merge.colSpan >= 2) ||
|
||||
(merge.rowSpan >= 2 && merge.colSpan === 1)
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const recordStart = recordOrder.indexOf(merge.anchor.record);
|
||||
const columnStart = columnOrder.indexOf(merge.anchor.column);
|
||||
if (recordStart < 0 || columnStart < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const records = recordOrder.slice(recordStart, recordStart + merge.rowSpan);
|
||||
const columns = columnOrder.slice(columnStart, columnStart + merge.colSpan);
|
||||
const recordsValid =
|
||||
records.length === merge.rowSpan &&
|
||||
records.every((recordId) => Boolean(block.data.records[recordId]));
|
||||
const definitions = columns.map((columnId) => block.data.definition[columnId]);
|
||||
const columnsValid =
|
||||
columns.length === merge.colSpan &&
|
||||
definitions.every(
|
||||
(definition) => definition?.type === 'text' || definition?.type === 'number'
|
||||
) &&
|
||||
definitions.every((definition) => definition?.type === definitions[0]?.type);
|
||||
if (!recordsValid || !columnsValid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
records: [...records],
|
||||
columns: [...columns],
|
||||
rowSpan: merge.rowSpan,
|
||||
colSpan: merge.colSpan,
|
||||
};
|
||||
}
|
||||
|
||||
function getCellKey(recordId: string, columnId: string): string {
|
||||
return `${recordId.length}:${recordId}${columnId}`;
|
||||
}
|
||||
|
||||
/** Partition records into ordered groups connected by one or more vertical merges. */
|
||||
function groupConnectedRecords(
|
||||
recordOrder: readonly string[],
|
||||
connectedRecordGroups: readonly (readonly string[])[]
|
||||
): string[][] {
|
||||
const parents = new Map(recordOrder.map((recordId) => [recordId, recordId]));
|
||||
|
||||
const findRoot = (recordId: string): string => {
|
||||
const parent = parents.get(recordId);
|
||||
if (!parent || parent === recordId) {
|
||||
return recordId;
|
||||
}
|
||||
|
||||
const root = findRoot(parent);
|
||||
parents.set(recordId, root);
|
||||
return root;
|
||||
};
|
||||
|
||||
for (const group of connectedRecordGroups) {
|
||||
const firstRecordId = group[0];
|
||||
if (!firstRecordId) continue;
|
||||
|
||||
for (const recordId of group.slice(1)) {
|
||||
parents.set(findRoot(recordId), findRoot(firstRecordId));
|
||||
}
|
||||
}
|
||||
|
||||
const groupedRecords = new Map<string, string[]>();
|
||||
for (const recordId of recordOrder) {
|
||||
const root = findRoot(recordId);
|
||||
const group = groupedRecords.get(root);
|
||||
if (group) {
|
||||
group.push(recordId);
|
||||
} else {
|
||||
groupedRecords.set(root, [recordId]);
|
||||
}
|
||||
}
|
||||
|
||||
return [...groupedRecords.values()];
|
||||
}
|
||||
@@ -1,10 +1,34 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { type SelectedOptions, matchesText, recordMatches } from './searchMatch';
|
||||
import {
|
||||
type SelectedOptions,
|
||||
type TableSearchRecordData,
|
||||
getVisibleTableRecordIds,
|
||||
matchesText,
|
||||
recordMatches,
|
||||
} from './searchMatch';
|
||||
|
||||
const NO_OPTIONS: SelectedOptions = {};
|
||||
const NO_CHECKBOXES: ReadonlySet<string> = new Set();
|
||||
|
||||
function visibleIds(
|
||||
records: TableSearchRecordData[],
|
||||
filters: {
|
||||
query?: string;
|
||||
selectedOptions?: SelectedOptions;
|
||||
checkedColumns?: ReadonlySet<string>;
|
||||
},
|
||||
recordGroups: string[][] = []
|
||||
) {
|
||||
return getVisibleTableRecordIds({
|
||||
records,
|
||||
recordGroups,
|
||||
query: filters.query ?? '',
|
||||
selectedOptions: filters.selectedOptions ?? NO_OPTIONS,
|
||||
checkedColumns: filters.checkedColumns ?? NO_CHECKBOXES,
|
||||
});
|
||||
}
|
||||
|
||||
function match(
|
||||
record: {
|
||||
searchText?: string;
|
||||
@@ -149,3 +173,75 @@ describe('recordMatches', () => {
|
||||
expect(match({ ...record, checkboxValues: { featured: false } }, filters)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getVisibleTableRecordIds', () => {
|
||||
const records: TableSearchRecordData[] = [
|
||||
{
|
||||
id: 'first',
|
||||
searchText: 'Anchor value',
|
||||
selectValues: { status: ['active'] },
|
||||
checkboxValues: { featured: false },
|
||||
},
|
||||
{
|
||||
id: 'second',
|
||||
searchText: 'Covered value',
|
||||
selectValues: { status: ['archived'] },
|
||||
checkboxValues: { featured: true },
|
||||
},
|
||||
{
|
||||
id: 'third',
|
||||
searchText: 'Connected value',
|
||||
selectValues: { status: ['pending'] },
|
||||
checkboxValues: { featured: false },
|
||||
},
|
||||
{
|
||||
id: 'unrelated',
|
||||
searchText: 'Unrelated value',
|
||||
selectValues: { status: ['archived'] },
|
||||
checkboxValues: { featured: false },
|
||||
},
|
||||
];
|
||||
const verticalGroup = [['first', 'second']];
|
||||
|
||||
it('returns null when no filter is active', () => {
|
||||
expect(visibleIds(records, {}, verticalGroup)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a complete vertical group when text matches its anchor', () => {
|
||||
expect(visibleIds(records, { query: 'anchor' }, verticalGroup)).toEqual(
|
||||
new Set(['first', 'second'])
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps a complete vertical group when select or checkbox filters match a grouped row', () => {
|
||||
expect(
|
||||
visibleIds(records, { selectedOptions: { status: new Set(['active']) } }, verticalGroup)
|
||||
).toEqual(new Set(['first', 'second']));
|
||||
expect(
|
||||
visibleIds(records, { checkedColumns: new Set(['featured']) }, verticalGroup)
|
||||
).toEqual(new Set(['second', 'first']));
|
||||
});
|
||||
|
||||
it('excludes completely unmatched and disconnected groups', () => {
|
||||
expect(visibleIds(records, { query: 'unrelated' }, verticalGroup)).toEqual(
|
||||
new Set(['unrelated'])
|
||||
);
|
||||
});
|
||||
|
||||
it('expands transitively connected groups in reversed metadata order without mutation', () => {
|
||||
const groups = [
|
||||
['second', 'third'],
|
||||
['first', 'second'],
|
||||
];
|
||||
const originalGroups = groups.map((group) => [...group]);
|
||||
|
||||
expect(visibleIds(records, { query: 'anchor' }, groups)).toEqual(
|
||||
new Set(['first', 'second', 'third'])
|
||||
);
|
||||
expect(groups).toEqual(originalGroups);
|
||||
});
|
||||
|
||||
it('leaves cards independently filtered when no merge groups are provided', () => {
|
||||
expect(visibleIds(records, { query: 'anchor' })).toEqual(new Set(['first']));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,72 @@
|
||||
/** Selected option values per select column, keyed by column id. */
|
||||
export type SelectedOptions = Readonly<Record<string, ReadonlySet<string>>>;
|
||||
|
||||
/** Per-record data used by the client-side table search. */
|
||||
export interface TableSearchRecordData {
|
||||
id: string;
|
||||
searchText: string;
|
||||
selectValues?: Record<string, string[]>;
|
||||
checkboxValues?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match records and expand matching vertical merge groups to a fixed point.
|
||||
*/
|
||||
export function getVisibleTableRecordIds({
|
||||
records,
|
||||
recordGroups = [],
|
||||
query,
|
||||
selectedOptions,
|
||||
checkedColumns,
|
||||
}: {
|
||||
records: readonly TableSearchRecordData[];
|
||||
recordGroups?: readonly (readonly string[])[];
|
||||
query: string;
|
||||
selectedOptions: SelectedOptions;
|
||||
checkedColumns: ReadonlySet<string>;
|
||||
}): ReadonlySet<string> | null {
|
||||
const hasActiveFilters =
|
||||
query.trim() !== '' || Object.keys(selectedOptions).length > 0 || checkedColumns.size > 0;
|
||||
if (!hasActiveFilters) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const visibleIds = new Set<string>();
|
||||
for (const record of records) {
|
||||
if (
|
||||
recordMatches(
|
||||
record.searchText,
|
||||
record.selectValues,
|
||||
record.checkboxValues,
|
||||
query,
|
||||
selectedOptions,
|
||||
checkedColumns
|
||||
)
|
||||
) {
|
||||
visibleIds.add(record.id);
|
||||
}
|
||||
}
|
||||
|
||||
let expanded = true;
|
||||
while (expanded) {
|
||||
expanded = false;
|
||||
for (const group of recordGroups) {
|
||||
if (!group.some((id) => visibleIds.has(id))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const id of group) {
|
||||
if (!visibleIds.has(id)) {
|
||||
visibleIds.add(id);
|
||||
expanded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return visibleIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a record passes the current filters.
|
||||
*
|
||||
|
||||
@@ -5,7 +5,12 @@ import { validateIconName } from '@gitbook/icons/icons';
|
||||
import type { BlockProps } from '../Block';
|
||||
import { Blocks } from '../Blocks';
|
||||
import { DynamicTabs } from './DynamicTabs';
|
||||
import { generateSelectCSS, selectSetClassName, slugifySelectValue } from '@/lib/select';
|
||||
import {
|
||||
generateSelectCSS,
|
||||
resolveSelectSlug,
|
||||
selectSetClassName,
|
||||
slugifySelectValue,
|
||||
} from '@/lib/select';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export function Tabs(props: BlockProps<DocumentBlockTabs>) {
|
||||
@@ -26,6 +31,7 @@ export function Tabs(props: BlockProps<DocumentBlockTabs>) {
|
||||
return {
|
||||
id: tab.meta?.id ?? tab.key,
|
||||
title: tab.data.title ?? '',
|
||||
slug: tab.data.slug,
|
||||
icon,
|
||||
body: (
|
||||
<Blocks
|
||||
@@ -94,19 +100,20 @@ function SelectGroupStyle({ slugs }: { slugs: string[] }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a `select` slug for each tab from its title. Untitled tabs fall back to their (stable) id
|
||||
* so they stay selectable.
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
function withSelectSlugs<T extends { id: string; title: string }>(
|
||||
function withSelectSlugs<T extends { id: string; title: string; slug?: string }>(
|
||||
items: T[]
|
||||
): (T & { slug: string })[] {
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
slug: slugifySelectValue(item.title) || slugifySelectValue(item.id) || item.id,
|
||||
slug: resolveSelectSlug(item) || slugifySelectValue(item.id) || item.id,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import QuickLRU from 'quick-lru';
|
||||
import React from 'react';
|
||||
import { createStore, useStore } from 'zustand';
|
||||
|
||||
import type { GitSyncState } from '@gitbook/api';
|
||||
import { type GitSyncState, SiteInsightsMarkdownSource } from '@gitbook/api';
|
||||
import { Icon, type IconName, IconStyle } from '@gitbook/icons';
|
||||
|
||||
import { useAIChatController, useAIChatState } from '@/components/AI';
|
||||
@@ -98,9 +98,14 @@ const createCopiedStateStore = () => {
|
||||
set({ copied: true });
|
||||
|
||||
timeoutRef = setTimeout(() => {
|
||||
set({ copied: false });
|
||||
onSuccess?.();
|
||||
timeoutRef = null;
|
||||
|
||||
// Delay resetting the label past the dropdown's closing animation (`scaleOut`,
|
||||
// 200ms) so the "Copied" label doesn't flip back while still visible mid-fade.
|
||||
timeoutRef = setTimeout(() => {
|
||||
set({ copied: false });
|
||||
timeoutRef = null;
|
||||
}, 200);
|
||||
}, 1500);
|
||||
},
|
||||
}));
|
||||
@@ -120,6 +125,10 @@ function useCopiedStore(stateKey: string) {
|
||||
return useStore(getOrCreateCopiedStoreByKey(stateKey));
|
||||
}
|
||||
|
||||
function getReaderMarkdownURL(markdownPageURL: string) {
|
||||
return `${markdownPageURL}?displayAgentInstructions=false&markdownSource=${SiteInsightsMarkdownSource.PageAction}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache for the markdown version of the page.
|
||||
*/
|
||||
@@ -144,7 +153,7 @@ export function ActionCopyMarkdown(props: {
|
||||
const fetchMarkdown = async () => {
|
||||
setLoading(true);
|
||||
|
||||
const humanURL = `${markdownPageURL}?displayAgentInstructions=false`;
|
||||
const humanURL = getReaderMarkdownURL(markdownPageURL);
|
||||
const result = await fetch(humanURL).then((res) => res.text());
|
||||
markdownCache.set(markdownPageURL, result);
|
||||
|
||||
@@ -153,13 +162,7 @@ export function ActionCopyMarkdown(props: {
|
||||
return result;
|
||||
};
|
||||
|
||||
const onClick = async (e: React.MouseEvent) => {
|
||||
// Prevent default behavior for non-default actions to avoid closing the dropdown.
|
||||
// This allows showing transient UI (e.g., a "copied" state) inside the menu item.
|
||||
if (!isDefaultAction) {
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
const onClick = async () => {
|
||||
copy(markdownCache.get(markdownPageURL) || (await fetchMarkdown()), {
|
||||
onSuccess: () => {
|
||||
// We close the dropdown menu if the action is a dropdown menu item and not the default action.
|
||||
@@ -179,6 +182,7 @@ export function ActionCopyMarkdown(props: {
|
||||
description={tString(language, 'copy_page_markdown')}
|
||||
onClick={onClick}
|
||||
loading={loading}
|
||||
closeOnClick={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -196,7 +200,7 @@ export function ActionViewAsMarkdown(props: { markdownPageURL: string; type: Pag
|
||||
icon="markdown"
|
||||
label={tString(language, 'view_page_markdown')}
|
||||
description={tString(language, 'view_page_plaintext')}
|
||||
href={`${markdownPageURL}?displayAgentInstructions=false`}
|
||||
href={getReaderMarkdownURL(markdownPageURL)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -421,9 +425,7 @@ export function CopyToClipboard(props: {
|
||||
icon={copied ? 'check' : icon}
|
||||
label={copied ? tString(language, 'code_copied') : label}
|
||||
description={description}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
|
||||
onClick={() => {
|
||||
copy(data, {
|
||||
onSuccess: () => {
|
||||
if (type === 'dropdown-menu-item') {
|
||||
@@ -432,6 +434,7 @@ export function CopyToClipboard(props: {
|
||||
},
|
||||
});
|
||||
}}
|
||||
closeOnClick={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -453,6 +456,7 @@ function PageActionWrapper(props: {
|
||||
target?: React.HTMLAttributeAnchorTarget;
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
closeOnClick?: boolean;
|
||||
}) {
|
||||
const {
|
||||
type,
|
||||
@@ -465,6 +469,7 @@ function PageActionWrapper(props: {
|
||||
description,
|
||||
disabled,
|
||||
loading,
|
||||
closeOnClick,
|
||||
} = props;
|
||||
|
||||
if (type === 'button') {
|
||||
@@ -498,6 +503,7 @@ function PageActionWrapper(props: {
|
||||
target={target}
|
||||
onClick={onClick}
|
||||
disabled={disabled || loading}
|
||||
closeOnClick={closeOnClick}
|
||||
>
|
||||
<div className="flex size-5 items-center justify-center text-tint">
|
||||
{loading ? (
|
||||
|
||||
@@ -16,18 +16,10 @@ 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,
|
||||
});
|
||||
@@ -144,54 +136,7 @@ export function SearchContainer({
|
||||
? Boolean(state?.open || state?.query || wasSearchOpened)
|
||||
: Boolean(state?.query || withAI);
|
||||
|
||||
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]);
|
||||
useSearchPopupFocusTrap({ close, searchInputRef, searchPopup, usesSideSheet });
|
||||
|
||||
const scopeControlNode =
|
||||
searchProps.withVariants || searchProps.withSections ? (
|
||||
|
||||
@@ -5,6 +5,7 @@ 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';
|
||||
@@ -198,17 +199,36 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
const itemKey = getResultKey(item);
|
||||
const shouldAnimateItem =
|
||||
shouldAnimateResults || !seenResultKeys.current.has(itemKey);
|
||||
const handleResultSelect = () => {
|
||||
const handleResultSelect = (
|
||||
event: React.MouseEvent<HTMLAnchorElement>
|
||||
) => {
|
||||
const isPageResult =
|
||||
item.type === 'local-page' ||
|
||||
item.type === 'page' ||
|
||||
item.type === 'record';
|
||||
|
||||
if (
|
||||
query &&
|
||||
siteSpaceId &&
|
||||
(item.type === 'local-page' ||
|
||||
item.type === 'page' ||
|
||||
item.type === 'record')
|
||||
isPageResult &&
|
||||
!event.currentTarget.hash &&
|
||||
event.currentTarget.pathname === window.location.pathname
|
||||
) {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
if (query && siteSpaceId && isPageResult) {
|
||||
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 = {
|
||||
@@ -376,3 +396,19 @@ 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)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
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,18 +5,13 @@ import { useCallback, useSyncExternalStore } from 'react';
|
||||
import { selectStore } from '@/lib/select';
|
||||
|
||||
/**
|
||||
* 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}.
|
||||
* 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.
|
||||
*/
|
||||
export function useSelect() {
|
||||
const slugs = useSyncExternalStore(
|
||||
selectStore.subscribe,
|
||||
selectStore.getState,
|
||||
selectStore.getState
|
||||
).slugs;
|
||||
|
||||
return {
|
||||
slugs,
|
||||
activate: selectStore.activate,
|
||||
deactivate: selectStore.deactivate,
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import Script from 'next/script';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
import { CustomizationDefaultThemeMode } from '@gitbook/api';
|
||||
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
|
||||
|
||||
import { AIContextProvider } from '../AI';
|
||||
import { RocketLoaderDetector } from './RocketLoaderDetector';
|
||||
@@ -12,6 +12,7 @@ import { AdminToolbar } from '@/components/AdminToolbar';
|
||||
import { CookiesToast } from '@/components/Cookies';
|
||||
import { LoadIntegrations } from '@/components/Integrations';
|
||||
import { SpaceLayout } from '@/components/SpaceLayout';
|
||||
import { WebMCP } from '@/components/WebMCP/WebMCP';
|
||||
import type { VisitorAuthClaims } from '@/lib/adaptive';
|
||||
import { buildVersion } from '@/lib/build';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
@@ -117,6 +118,9 @@ export async function SiteLayout(props: {
|
||||
</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" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import type { PageMetaLinks } from './SitePage';
|
||||
@@ -33,7 +33,6 @@ 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();
|
||||
|
||||
@@ -41,9 +40,14 @@ function useStripFallbackQueryParam() {
|
||||
if (searchParams?.has('fallback')) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete('fallback');
|
||||
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
|
||||
const query = params.toString();
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
`${pathname}${query ? `?${query}` : ''}${window.location.hash}`
|
||||
);
|
||||
}
|
||||
}, [router, pathname, searchParams]);
|
||||
}, [pathname, searchParams]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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,6 +1,7 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { permanentRedirect, redirect } from 'next/navigation';
|
||||
|
||||
import {
|
||||
CustomizationPageActionType,
|
||||
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
} from '@gitbook/api';
|
||||
@@ -26,7 +27,34 @@ export type PageParams = PagePathParams | PageIdParams;
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
|
||||
const pageTarget = await resolvePage(context, params);
|
||||
let pageTarget = await resolvePage(context, params);
|
||||
|
||||
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
|
||||
if (
|
||||
pageTarget &&
|
||||
!pageTarget.page.git &&
|
||||
context.space.gitSync?.url &&
|
||||
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
|
||||
) {
|
||||
const response = await context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
path: pageTarget.page.path,
|
||||
metadata: true,
|
||||
cachedMetadata: true,
|
||||
});
|
||||
const pageWithMetadata = response.data;
|
||||
|
||||
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
|
||||
pageTarget = {
|
||||
...pageTarget,
|
||||
page: {
|
||||
...pageTarget.page,
|
||||
git: pageWithMetadata.git,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
context: {
|
||||
@@ -89,7 +117,21 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
|
||||
})
|
||||
));
|
||||
if (resolvedSiteRedirect) {
|
||||
return redirect(linker.toLinkForContent(resolvedSiteRedirect.target));
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,15 +58,15 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
? context.linker.toPathInSite('~gitbook/auth/login')
|
||||
: null;
|
||||
|
||||
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);
|
||||
// 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 getVisitorClaimsUrl = context.linker.toAbsoluteURL(
|
||||
context.linker.toPathInSite('/~gitbook/visitor')
|
||||
);
|
||||
const getVisitorClaimsUrl = context.linker.toPathInSite('/~gitbook/visitor');
|
||||
|
||||
return (
|
||||
<SpaceLayoutContextProvider
|
||||
@@ -92,7 +92,7 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
|
||||
appURL={GITBOOK_APP_URL}
|
||||
visitorCookieTrackingEnabled={customization.insights?.trackingCookie}
|
||||
>
|
||||
<InsightsProvider enabled={withTracking} eventUrl={eventUrl.toString()}>
|
||||
<InsightsProvider enabled={withTracking} eventUrl={eventUrl}>
|
||||
<AIChatProvider
|
||||
renderMessageOptions={aiChatRenderMessageOptions}
|
||||
withPageFeedback={customization.feedback.enabled}
|
||||
|
||||
@@ -8,12 +8,6 @@ import { useEffect } from 'react';
|
||||
export function TableOfContentsScript() {
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
// Writing the <html> style attribute re-styles the whole document, so skip unchanged values.
|
||||
const setVar = (name: string, value: string) => {
|
||||
if (root.style.getPropertyValue(name) !== value) {
|
||||
root.style.setProperty(name, value);
|
||||
}
|
||||
};
|
||||
|
||||
// Calculate and set TOC dimensions
|
||||
const updateTocLayout = () => {
|
||||
@@ -48,8 +42,8 @@ export function TableOfContentsScript() {
|
||||
}
|
||||
|
||||
// Update height
|
||||
setVar('--toc-height', `${Math.max(height, 0)}px`);
|
||||
setVar('--toc-top-offset', `${Math.max(offset, 0)}px`);
|
||||
root.style.setProperty('--toc-height', `${Math.max(height, 0)}px`);
|
||||
root.style.setProperty('--toc-top-offset', `${Math.max(offset, 0)}px`);
|
||||
|
||||
// Subtract visible pageCover (if any)
|
||||
if (
|
||||
@@ -70,8 +64,8 @@ export function TableOfContentsScript() {
|
||||
}
|
||||
}
|
||||
|
||||
setVar('--outline-height', `${Math.max(height, 0)}px`);
|
||||
setVar('--outline-top-offset', `${Math.max(offset, 0)}px`);
|
||||
root.style.setProperty('--outline-height', `${Math.max(height, 0)}px`);
|
||||
root.style.setProperty('--outline-top-offset', `${Math.max(offset, 0)}px`);
|
||||
};
|
||||
|
||||
// Initial update
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
'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;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 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)
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
'use client';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
import { resolveOverflowingItems } from './listOverflow';
|
||||
|
||||
interface OverflowState {
|
||||
/**
|
||||
* Ref for the container element.
|
||||
@@ -24,12 +26,23 @@ 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.
|
||||
* 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.
|
||||
*/
|
||||
export function useListOverflow(): OverflowState {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [overflowing, setOverflowing] = useState<Set<string>>(new Set());
|
||||
const [isMeasuring, setIsMeasuring] = useState(false);
|
||||
// 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 itemRefs = useRef(new Map<string, HTMLElement>());
|
||||
const rafRef = useRef(0);
|
||||
|
||||
@@ -43,19 +56,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;
|
||||
}
|
||||
|
||||
setIsMeasuring(true);
|
||||
requestMeasure();
|
||||
|
||||
const ro = new ResizeObserver(() => {
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
setIsMeasuring(true);
|
||||
});
|
||||
rafRef.current = requestAnimationFrame(requestMeasure);
|
||||
});
|
||||
|
||||
ro.observe(containerRef.current);
|
||||
@@ -64,7 +77,7 @@ export function useListOverflow(): OverflowState {
|
||||
ro.disconnect();
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
};
|
||||
}, []);
|
||||
}, [requestMeasure]);
|
||||
|
||||
// Measure which items are overflowing
|
||||
useLayoutEffect(() => {
|
||||
@@ -72,29 +85,32 @@ export function useListOverflow(): OverflowState {
|
||||
return;
|
||||
}
|
||||
|
||||
const containerRect = containerRef.current.getBoundingClientRect();
|
||||
const newOverflowing = new Set<string>();
|
||||
const newOverflowing = resolveOverflowingItems(
|
||||
containerRef.current.getBoundingClientRect(),
|
||||
Array.from(itemRefs.current, ([id, element]) => ({
|
||||
id,
|
||||
rect: element.getBoundingClientRect(),
|
||||
}))
|
||||
);
|
||||
|
||||
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)) {
|
||||
// `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) {
|
||||
return newOverflowing;
|
||||
}
|
||||
}
|
||||
return previous;
|
||||
});
|
||||
setIsMeasuring(false);
|
||||
}, [isMeasuring]);
|
||||
for (const id of previous) {
|
||||
if (!newOverflowing.has(id)) {
|
||||
return newOverflowing;
|
||||
}
|
||||
}
|
||||
return previous;
|
||||
});
|
||||
}
|
||||
|
||||
setMeasureCompleted(measureRequest);
|
||||
}, [isMeasuring, measureRequest]);
|
||||
|
||||
return { containerRef, itemRef, overflowing, isMeasuring };
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useEffect, useLayoutEffect, useRef } from 'react';
|
||||
import { useEffect, useLayoutEffect } from 'react';
|
||||
|
||||
import { useIsNavigating } from '../hooks';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -15,14 +15,8 @@ export const NavigationLoader = () => {
|
||||
}, []);
|
||||
|
||||
// On route changes, add a transient class for the first paint of the new page.
|
||||
// Skipped on the initial mount: toggling a class on <html> re-styles the whole document.
|
||||
const isInitialMount = useRef(true);
|
||||
useLayoutEffect(() => {
|
||||
void pathname;
|
||||
if (isInitialMount.current) {
|
||||
isInitialMount.current = false;
|
||||
return;
|
||||
}
|
||||
const root = document.documentElement;
|
||||
root.classList.add('route-change');
|
||||
let raf2 = 0;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
||||
|
||||
import { scrollByItemsInContainer } from './ScrollContainer';
|
||||
|
||||
type MockRect = {
|
||||
left: number;
|
||||
right: number;
|
||||
top: number;
|
||||
bottom: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
class MockElement {
|
||||
constructor(private readonly rect: MockRect) {}
|
||||
|
||||
getBoundingClientRect() {
|
||||
return this.rect;
|
||||
}
|
||||
}
|
||||
|
||||
const originalHTMLElement = globalThis.HTMLElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
configurable: true,
|
||||
value: MockElement,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Object.defineProperty(globalThis, 'HTMLElement', {
|
||||
configurable: true,
|
||||
value: originalHTMLElement,
|
||||
});
|
||||
});
|
||||
|
||||
function rect(left: number, right: number): MockRect {
|
||||
return { left, right, top: 0, bottom: 100, width: right - left, height: 100 };
|
||||
}
|
||||
|
||||
function makeContainer(
|
||||
childRects: MockRect[],
|
||||
options: { scrollLeft?: number; scrollWidth?: number } = {}
|
||||
) {
|
||||
const scrollCalls: Record<string, unknown>[] = [];
|
||||
const container = Object.assign(new MockElement(rect(0, 300)), {
|
||||
children: childRects.map((childRect) => new MockElement(childRect)),
|
||||
clientHeight: 100,
|
||||
clientWidth: 300,
|
||||
scrollHeight: 100,
|
||||
scrollLeft: options.scrollLeft ?? 0,
|
||||
scrollTop: 0,
|
||||
scrollWidth: options.scrollWidth ?? 1000,
|
||||
scrollTo: (options: Record<string, unknown>) => scrollCalls.push(options),
|
||||
});
|
||||
|
||||
return { container: container as unknown as HTMLElement, scrollCalls };
|
||||
}
|
||||
|
||||
describe('scrollByItemsInContainer', () => {
|
||||
it('advances by fully visible items and excludes a partial preview', () => {
|
||||
const { container, scrollCalls } = makeContainer([
|
||||
rect(0, 100),
|
||||
rect(110, 210),
|
||||
rect(220, 320),
|
||||
rect(330, 430),
|
||||
]);
|
||||
|
||||
scrollByItemsInContainer(container, 'horizontal', 'forward');
|
||||
|
||||
expect(scrollCalls).toEqual([{ top: undefined, left: 220, behavior: 'smooth' }]);
|
||||
});
|
||||
|
||||
it('moves backward by the visible page size', () => {
|
||||
const { container, scrollCalls } = makeContainer(
|
||||
[rect(-220, -120), rect(-110, -10), rect(0, 100), rect(110, 210), rect(220, 320)],
|
||||
{ scrollLeft: 220 }
|
||||
);
|
||||
|
||||
scrollByItemsInContainer(container, 'horizontal', 'backward');
|
||||
|
||||
expect(scrollCalls).toEqual([{ top: undefined, left: 0, behavior: 'smooth' }]);
|
||||
});
|
||||
|
||||
it('clamps at the first and last scroll positions', () => {
|
||||
const firstPage = makeContainer([rect(0, 100), rect(110, 210), rect(220, 320)]);
|
||||
scrollByItemsInContainer(firstPage.container, 'horizontal', 'backward');
|
||||
|
||||
const lastPage = makeContainer(
|
||||
[rect(-240, -140), rect(-130, -30), rect(-20, 80), rect(90, 190), rect(200, 300)],
|
||||
{ scrollLeft: 240, scrollWidth: 540 }
|
||||
);
|
||||
scrollByItemsInContainer(lastPage.container, 'horizontal', 'forward');
|
||||
|
||||
expect(firstPage.scrollCalls).toEqual([{ top: undefined, left: 0, behavior: 'smooth' }]);
|
||||
expect(lastPage.scrollCalls).toEqual([{ top: undefined, left: 240, behavior: 'smooth' }]);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user