mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-15 15:15:55 +00:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ec64dad58 | |||
| 326d674254 | |||
| a6a78ce5ac | |||
| 56cb2f4c9a | |||
| f92e90603f | |||
| 14172791e9 | |||
| e4e2f524d4 | |||
| fc7b16f6a7 | |||
| 6ba3ae74d5 | |||
| c71d1598d8 | |||
| 5950657b0e | |||
| 0e1a48cd06 | |||
| 98245e5f20 | |||
| 0b6ddca981 | |||
| ea1468c892 | |||
| e8e64bf510 | |||
| aaf8daf0d7 | |||
| 8af1abc4e1 | |||
| 48ab59feb3 | |||
| f64d5073d4 | |||
| 53b9f10ac8 | |||
| 75606e4df7 | |||
| 0643b7f351 | |||
| 5b3b4e0614 |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
"@babel/preset-react"
|
||||
],
|
||||
"ignore": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"public"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
1.1.40
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix expandable block anchore resolution
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Adapt code to pull token from customer backend generated custom cookies
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix an issue with the cookie banner buttons being non responsive
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@gitbook/react-openapi': minor
|
||||
---
|
||||
|
||||
Add an optional client context to get a callback called when the Scalar client is opened for a block.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Update the site header with new styling, a new search button, and refactored layout
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add support for tint color
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@gitbook/cache-do': patch
|
||||
---
|
||||
|
||||
Disable cloudflare observability in production
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Update styling of search+ask modal
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix a regression in variant drop-down caused by missing z-index.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add breadcrumbs above page title
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add scroll margin to the top when there are sections
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Improve contrast of search box placeholder
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Smoother tab transition for sections
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
GitBook Open now supports Ask AI in sites. When asking a question to Ask AI, GitBook will use context from across your site sections and variants to provide the best answer.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix an issue where the active site section indicator appeared above any dropdowns.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Don't adjust fallback font for mono font.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Optimize performances by using new API endpoint for fetching site data.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track events for site insights using the new dedicated API.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix margin and image resolution of header logo
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Improve colour contrast of list item decoration
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Bump @scalar/api-client-react version
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
'@gitbook/react-contentkit': minor
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Send redirectOnError param to getPublishedContent when token is pulled from cookie
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Support Integers in Response example
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track clicks on links (header, footer, content) for site insights.
|
||||
@@ -2,4 +2,4 @@
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Restyle hint blocks
|
||||
Fix emojis display
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix security issue with image resizing that could be used for phishing
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Prevent codemirror from loading multiple versions in scalar
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
bumped the scalar api client dependency
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix variant selector contrast for non-default themes
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Bumped scalar api client pacakge
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix an issue where the space dropdown was shown under the site sections in Safari.
|
||||
@@ -2,4 +2,4 @@
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Fixed scalar api client routing
|
||||
Updated scalar depdenency
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix - whitespace added to site section tabs with icons.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix an issue where Ask AI was erroring due to an object being passed as a param.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Increase token max length to fix code not highlighted
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add icons to sections
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix bullet list display on full size blocks
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
style: adds missing scalar css variables
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track an event into site insights when visitor is opening the Scalar API client.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix an issue where the space dropdown could appear behind the header.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix the styling of site section tabs on smaller screens.
|
||||
@@ -0,0 +1,18 @@
|
||||
name: 'Setup Bun'
|
||||
description: 'Install Bun and cache dependencies'
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
# We cache dependencies even if Bun is fast to avoid downloading fontawesome too many times
|
||||
# and impacting bandwidth there.
|
||||
- name: Cache bun
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: '.bun-version'
|
||||
+19
-35
@@ -5,7 +5,7 @@ on:
|
||||
branches:
|
||||
- main
|
||||
env:
|
||||
NPMRC_FONT_AWESOME_TOKEN: ${{ secrets.NPMRC_FONT_AWESOME_TOKEN }}
|
||||
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy to Cloudflare Pages
|
||||
@@ -22,10 +22,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -102,10 +100,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Setup Playwright
|
||||
@@ -128,10 +124,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -147,10 +141,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -162,10 +154,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -177,10 +167,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -191,16 +179,14 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build (Open Source)
|
||||
env:
|
||||
NPMRC_FONT_AWESOME_TOKEN: ''
|
||||
NPM_TOKEN_READONLY: ''
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
run: bun install
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||
- run: bun run build
|
||||
@@ -210,10 +196,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
|
||||
@@ -17,10 +17,8 @@ jobs:
|
||||
with:
|
||||
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
|
||||
fetch-depth: 0
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -34,7 +32,7 @@ jobs:
|
||||
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
|
||||
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
|
||||
GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
release-preview:
|
||||
@@ -45,10 +43,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v3
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Setup Bun
|
||||
uses: ./.github/composite/setup-bun
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
[install.scopes]
|
||||
"awesome.me" = { token = "$NPMRC_FONT_AWESOME_TOKEN", url = "https://npm.fontawesome.com/" }
|
||||
"gitbook" = { token = "$NPM_TOKEN_READONLY", url = "https://registry.npmjs.org" }
|
||||
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||
+43
-33
@@ -1,35 +1,45 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.1.0",
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.7",
|
||||
"prettier": "^3.0.3",
|
||||
"turbo": "^2.1.2"
|
||||
},
|
||||
"packageManager": "bun@1.1.18",
|
||||
"patchedDependencies": {
|
||||
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
|
||||
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
|
||||
},
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "turbo run dev",
|
||||
"build": "turbo run build",
|
||||
"build:cloudflare": "turbo run build:cloudflare",
|
||||
"lint": "turbo run lint",
|
||||
"lint:fix": "turbo run lint -- --fix",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"format": "prettier ./ --ignore-unknown --write",
|
||||
"format:check": "prettier ./ --ignore-unknown --list-different",
|
||||
"unit": "turbo run unit",
|
||||
"e2e": "turbo run e2e",
|
||||
"changeset": "changeset",
|
||||
"release": "turbo run release && changeset publish",
|
||||
"release:preview": "turbo run release:preview",
|
||||
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
|
||||
"clean": "turbo run clean"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
]
|
||||
"name": "gitbook",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.7",
|
||||
"prettier": "^3.0.3",
|
||||
"turbo": "^2.1.2"
|
||||
},
|
||||
"packageManager": "bun@1.1.18",
|
||||
"patchedDependencies": {
|
||||
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
|
||||
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
|
||||
},
|
||||
"overrides": {
|
||||
"@codemirror/state": "6.4.1"
|
||||
},
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "turbo run dev",
|
||||
"build": "turbo run build",
|
||||
"build:cloudflare": "turbo run build:cloudflare",
|
||||
"lint": "turbo run lint",
|
||||
"lint:fix": "turbo run lint -- --fix",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"format": "prettier ./ --ignore-unknown --write",
|
||||
"format:check": "prettier ./ --ignore-unknown --list-different",
|
||||
"unit": "turbo run unit",
|
||||
"e2e": "turbo run e2e",
|
||||
"changeset": "changeset",
|
||||
"release": "turbo run release && changeset publish",
|
||||
"release:preview": "turbo run release:preview",
|
||||
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
|
||||
"clean": "turbo run clean"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@babel/cli": "^7.26.4",
|
||||
"@babel/preset-env": "^7.26.0",
|
||||
"@babel/preset-react": "^7.26.3",
|
||||
"tsconfig-paths": "^4.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# @gitbook/cache-do
|
||||
|
||||
## 0.1.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- b7a5106: Disable cloudflare observability in production
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"default": "./dist/api.js"
|
||||
}
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.0.0-beta2",
|
||||
"lru_map": "^0.4.1"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,45 @@
|
||||
# gitbook
|
||||
|
||||
## 0.5.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57cdd25: GitBook Open now supports Ask AI in sites. When asking a question to Ask AI, GitBook will use context from across your site sections and variants to provide the best answer.
|
||||
- ca134c8: Fix an issue where the active site section indicator appeared above any dropdowns.
|
||||
- d48926e: Fix an issue where the space dropdown was shown under the site sections in Safari.
|
||||
- 9fe8142: Fix an issue where Ask AI was erroring due to an object being passed as a param.
|
||||
- d843e5e: Fix an issue where the space dropdown could appear behind the header.
|
||||
- a2e5647: Fix the styling of site section tabs on smaller screens.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 076dc48: Fix expandable block anchore resolution
|
||||
- d9bb9f9: Fix an issue with the cookie banner buttons being non responsive
|
||||
- 23584c9: Update the site header with new styling, a new search button, and refactored layout
|
||||
- 664debc: Add support for tint color
|
||||
- 4d56f11: Update styling of search+ask modal
|
||||
- 061c0c1: Fix a regression in variant drop-down caused by missing z-index.
|
||||
- 2f76712: Add breadcrumbs above page title
|
||||
- 07cf835: Add scroll margin to the top when there are sections
|
||||
- 5d72b35: Smoother tab transition for sections
|
||||
- 7c71363: Don't adjust fallback font for mono font.
|
||||
- 7675c2c: Optimize performances by using new API endpoint for fetching site data.
|
||||
- 87eea73: Fix margin and image resolution of header logo
|
||||
- aa2ed0f: Restyle hint blocks
|
||||
- ffd3937: Fix security issue with image resizing that could be used for phishing
|
||||
- 2ce59d7: Fix - whitespace added to site section tabs with icons.
|
||||
- c73e07d: Increase token max length to fix code not highlighted
|
||||
- 3b3d6e2: Add icons to sections
|
||||
- 1ed18c0: style: adds missing scalar css variables
|
||||
- Updated dependencies [b7a5106]
|
||||
- Updated dependencies [4771c78]
|
||||
- Updated dependencies [ff50ac2]
|
||||
- Updated dependencies [867481c]
|
||||
- Updated dependencies [7ba67fd]
|
||||
- Updated dependencies [a78c1ec]
|
||||
- @gitbook/cache-do@0.1.1
|
||||
- @gitbook/react-openapi@0.7.1
|
||||
|
||||
## 0.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -6,20 +6,29 @@ import {
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationIconsStyle,
|
||||
CustomizationLocale,
|
||||
CustomizationSidebarBackgroundStyle,
|
||||
CustomizationSidebarListStyle,
|
||||
CustomizationThemeMode,
|
||||
SiteCustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import { test, expect, Page, BrowserContext } from '@playwright/test';
|
||||
import deepMerge from 'deepmerge';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import rison from 'rison';
|
||||
import { DeepPartial } from 'ts-essentials';
|
||||
|
||||
import {
|
||||
getVisitorAuthCookieName,
|
||||
getVisitorAuthCookieValue,
|
||||
VISITOR_TOKEN_COOKIE,
|
||||
} from '@/lib/visitor-token';
|
||||
|
||||
import { getContentTestURL } from '../tests/utils';
|
||||
|
||||
interface Test {
|
||||
name: string;
|
||||
url: string; // URL to visit for testing
|
||||
cookies?: Parameters<BrowserContext['addCookies']>[0];
|
||||
run?: (page: Page) => Promise<unknown>; // The test to run
|
||||
fullPage?: boolean; // Whether the test should be fullscreened during testing
|
||||
screenshot?: false; // Should a screenshot be stored
|
||||
@@ -867,6 +876,60 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
|
||||
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'Redirect to fallback on invalid token pulled from cookie',
|
||||
url: '',
|
||||
screenshot: false,
|
||||
cookies: (() => {
|
||||
const basePath = '/va-site-redirects-fallback/';
|
||||
const invalidToken = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
'invalidKey',
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: getVisitorAuthCookieName(basePath),
|
||||
value: getVisitorAuthCookieValue(basePath, invalidToken),
|
||||
httpOnly: true,
|
||||
},
|
||||
];
|
||||
})(),
|
||||
run: async (page) => {
|
||||
await expect(page).toHaveURL(/https:\/\/www.google.com/);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Show error message when invalid token is passed to url',
|
||||
screenshot: false,
|
||||
url: (() => {
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
'invalidKey',
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
await expect(page.locator('pre')).toContainText(
|
||||
'Error while validating the JWT token. Reason: The token signature is invalid.',
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Languages',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
@@ -1022,6 +1085,149 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Adaptive Content - Public',
|
||||
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'No custom cookie',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const welcomePage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Welcome Page' });
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha User' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta User' });
|
||||
|
||||
await expect(welcomePage).toBeVisible();
|
||||
await expect(alphaUserPage).toHaveCount(0);
|
||||
await expect(betaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Custom cookie with isAlphaUser claim',
|
||||
cookies: (() => {
|
||||
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: VISITOR_TOKEN_COOKIE,
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
},
|
||||
];
|
||||
})(),
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const welcomePage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Welcome Page' });
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha User' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta User' });
|
||||
|
||||
await expect(welcomePage).toBeVisible();
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
await expect(betaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Custom cookie with isBetaUser claim',
|
||||
cookies: (() => {
|
||||
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: VISITOR_TOKEN_COOKIE,
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
},
|
||||
];
|
||||
})(),
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const welcomePage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Welcome Page' });
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha User' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta User' });
|
||||
|
||||
await expect(welcomePage).toBeVisible();
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
await expect(alphaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Custom cookie with isAlphaUser & isBetaUser claims',
|
||||
cookies: (() => {
|
||||
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: VISITOR_TOKEN_COOKIE,
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
},
|
||||
];
|
||||
})(),
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const welcomePage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Welcome Page' });
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha User' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta User' });
|
||||
|
||||
await expect(welcomePage).toBeVisible();
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Tables',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
@@ -1112,9 +1318,18 @@ for (const testCase of testCases) {
|
||||
test.describe(testCase.name, () => {
|
||||
for (const testEntry of testCase.tests) {
|
||||
const testFn = testEntry.only ? test.only : test;
|
||||
testFn(testEntry.name, async ({ page, baseURL }) => {
|
||||
testFn(testEntry.name, async ({ page, baseURL, context }) => {
|
||||
const contentUrl = new URL(testEntry.url, testCase.baseUrl);
|
||||
const url = getContentTestURL(contentUrl.toString(), baseURL);
|
||||
if (testEntry.cookies) {
|
||||
await context.addCookies(
|
||||
testEntry.cookies.map((cookie) => ({
|
||||
...cookie,
|
||||
domain: new URL(url).host,
|
||||
path: '/',
|
||||
})),
|
||||
);
|
||||
}
|
||||
await page.goto(url);
|
||||
if (testEntry.run) {
|
||||
await testEntry.run(page);
|
||||
@@ -1152,6 +1367,10 @@ function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): s
|
||||
font: CustomizationFont.Inter,
|
||||
background: CustomizationBackground.Plain,
|
||||
icons: CustomizationIconsStyle.Regular,
|
||||
sidebar: {
|
||||
background: CustomizationSidebarBackgroundStyle.Default,
|
||||
list: CustomizationSidebarListStyle.Default,
|
||||
},
|
||||
},
|
||||
internationalization: {
|
||||
locale: CustomizationLocale.En,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "env-cmd --silent -f ../../.env.local next dev",
|
||||
@@ -16,7 +16,7 @@
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gitbook/api": "^0.81.0",
|
||||
"@gitbook/api": "^0.85.0",
|
||||
"@gitbook/cache-do": "workspace:*",
|
||||
"@gitbook/emoji-codepoints": "workspace:*",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
@@ -43,7 +43,7 @@
|
||||
"memoizee": "^0.4.15",
|
||||
"next": "14.2.15",
|
||||
"next-themes": "^0.2.1",
|
||||
"nuqs": "^1.17.4",
|
||||
"nuqs": "^2.2.3",
|
||||
"object-hash": "^3.0.0",
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.0",
|
||||
@@ -64,7 +64,8 @@
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"tailwind-shades": "^1.1.2",
|
||||
"unified": "^11.0.4",
|
||||
"url-join": "^5.0.0"
|
||||
"url-join": "^5.0.0",
|
||||
"usehooks-ts": "^3.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^2.0.0",
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { TrackPageViewEvent } from '@/components/Insights';
|
||||
import { getSpaceLanguage, t } from '@/intl/server';
|
||||
import { getSiteData } from '@/lib/api';
|
||||
import { getSiteData, getSpaceContentData } from '@/lib/api';
|
||||
import { getSiteContentPointer } from '@/lib/pointer';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export default async function NotFound() {
|
||||
const pointer = getSiteContentPointer();
|
||||
const { customization } = await getSiteData(pointer);
|
||||
const [{ space }, { customization }] = await Promise.all([
|
||||
getSpaceContentData(pointer, pointer.siteShareKey),
|
||||
getSiteData(pointer),
|
||||
]);
|
||||
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
@@ -19,6 +23,9 @@ export default async function NotFound() {
|
||||
</h2>
|
||||
<p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p>
|
||||
</div>
|
||||
|
||||
{/* Track the page not found as a page view */}
|
||||
<TrackPageViewEvent pageId={null} revisionId={space.revision} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
|
||||
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
|
||||
import { ContentRefContext } from '@/lib/references';
|
||||
import { isSpaceIndexable, isPageIndexable } from '@/lib/seo';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getContentTitle } from '@/lib/utils';
|
||||
|
||||
import { PageClientLayout } from './PageClientLayout';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CustomizationThemeMode } from '@gitbook/api';
|
||||
import { Metadata, Viewport } from 'next';
|
||||
import { headers } from 'next/headers';
|
||||
import { NuqsAdapter } from 'nuqs/adapters/next/app';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
@@ -55,46 +56,48 @@ export default async function ContentLayout(props: { children: React.ReactNode }
|
||||
});
|
||||
|
||||
return (
|
||||
<ClientContexts
|
||||
nonce={nonce}
|
||||
forcedTheme={
|
||||
getQueryStringTheme() ??
|
||||
(customization.themes.toggeable ? undefined : customization.themes.default)
|
||||
}
|
||||
>
|
||||
<SpaceLayout
|
||||
space={space}
|
||||
contentTarget={contentTarget}
|
||||
site={site}
|
||||
spaces={spaces}
|
||||
sections={sections}
|
||||
customization={customization}
|
||||
pages={pages}
|
||||
ancestors={ancestors}
|
||||
content={content}
|
||||
<NuqsAdapter>
|
||||
<ClientContexts
|
||||
nonce={nonce}
|
||||
forcedTheme={
|
||||
getQueryStringTheme() ??
|
||||
(customization.themes.toggeable ? undefined : customization.themes.default)
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</SpaceLayout>
|
||||
<SpaceLayout
|
||||
space={space}
|
||||
contentTarget={contentTarget}
|
||||
site={site}
|
||||
spaces={spaces}
|
||||
sections={sections}
|
||||
customization={customization}
|
||||
pages={pages}
|
||||
ancestors={ancestors}
|
||||
content={content}
|
||||
>
|
||||
{children}
|
||||
</SpaceLayout>
|
||||
|
||||
{scripts.length > 0 ? (
|
||||
<>
|
||||
<LoadIntegrations />
|
||||
{scripts.map(({ script }) => (
|
||||
<script key={script} async src={script} nonce={nonce} />
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
{scripts.length > 0 ? (
|
||||
<>
|
||||
<LoadIntegrations />
|
||||
{scripts.map(({ script }) => (
|
||||
<script key={script} async src={script} nonce={nonce} />
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
|
||||
<React.Suspense fallback={null}>
|
||||
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
|
||||
<React.Suspense fallback={null}>
|
||||
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
|
||||
<RocketLoaderDetector nonce={nonce} />
|
||||
<RocketLoaderDetector nonce={nonce} />
|
||||
|
||||
<AdminToolbar space={space} content={content} />
|
||||
</ClientContexts>
|
||||
<AdminToolbar space={space} content={content} />
|
||||
</ClientContexts>
|
||||
</NuqsAdapter>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,23 +11,24 @@ import { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import * as React from 'react';
|
||||
|
||||
import { DocumentView } from '@/components/DocumentView';
|
||||
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
|
||||
import { PolymorphicComponentProp } from '@/components/utils/types';
|
||||
import { getSpaceLanguage } from '@/intl/server';
|
||||
import { tString } from '@/intl/translate';
|
||||
import { DocumentView } from '../../../../components/DocumentView';
|
||||
import { TrademarkLink } from '../../../../components/TableOfContents/Trademark';
|
||||
import { PolymorphicComponentProp } from '../../../../components/utils/types';
|
||||
import { getSpaceLanguage } from '../../../../intl/server';
|
||||
import { tString } from '../../../../intl/translate';
|
||||
import {
|
||||
getDocument,
|
||||
getSpace,
|
||||
getSpaceCustomization,
|
||||
getSpaceContentData,
|
||||
getSiteData,
|
||||
} from '@/lib/api';
|
||||
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links';
|
||||
import { resolvePageId } from '@/lib/pages';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
|
||||
} from '../../../../lib/api';
|
||||
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '../../../../lib/links';
|
||||
import { resolvePageId } from '../../../../lib/pages';
|
||||
import { ContentRefContext, resolveContentRef } from '../../../../lib/references';
|
||||
import { tcls } from '../../../../lib/tailwind';
|
||||
import { SiteContentPointer, SpaceContentPointer } from '../../../../lib/api';
|
||||
import { PDFSearchParams, getPDFSearchParams } from '../../../../lib/urls';
|
||||
|
||||
import './pdf.css';
|
||||
import { PageControlButtons } from './PageControlButtons';
|
||||
@@ -55,7 +56,9 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
* Render a space as a standalone HTML page that can be printed as a PDF.
|
||||
*/
|
||||
export default async function PDFHTMLOutput(props: { searchParams: { [key: string]: string } }) {
|
||||
const pointer = getSiteOrSpacePointerForPDF();
|
||||
const pointer = {"siteId": "site_dIY9z", "spaceId": "-MdwVZ6HOZriajCf5nXH", "siteSpaceId": "sitesp_mX2p5", "organizationId": "-M4tdxG8qotLgGZnLpFR"} as SiteContentPointer | SpaceContentPointer;
|
||||
|
||||
console.log('vib pointer', JSON.stringify(pointer));
|
||||
|
||||
const searchParams = new URLSearchParams(props.searchParams);
|
||||
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
const { renderToPipeableStream } = require('react-dom/server');
|
||||
const PDFHTMLOutput = require('./page');
|
||||
//import { renderToPipeableStream, renderToStaticNodeStream } from 'react-dom/server';
|
||||
//import PDFHTMLOutput from './page';
|
||||
//import fs from 'fs';
|
||||
//import React from 'react';
|
||||
const fs = require('fs');
|
||||
const React = require('react');
|
||||
|
||||
|
||||
// Create a writable stream to save the HTML to a file
|
||||
const writeStream = fs.createWriteStream('output.html');
|
||||
|
||||
// Start the server-side rendering with renderToPipeableStream
|
||||
const { pipe } = renderToPipeableStream(React.createElement(PDFHTMLOutput, {searchParams : {'a': 'b'}}) as any);
|
||||
|
||||
// Pipe the render stream to the writable file stream
|
||||
pipe(writeStream);
|
||||
|
||||
// Optionally, you can handle errors and closure
|
||||
writeStream.on('finish', () => {
|
||||
console.log('HTML has been written to output.html');
|
||||
});
|
||||
|
||||
writeStream.on('error', (err: any) => {
|
||||
console.error('Error writinsg to file:', err);
|
||||
});
|
||||
@@ -6,9 +6,10 @@ import * as React from 'react';
|
||||
import { Button } from '@/components/primitives';
|
||||
import { useLanguage } from '@/intl/client';
|
||||
import { t, tString } from '@/intl/translate';
|
||||
import { isCookiesTrackingDisabled, setCookiesTracking } from '@/lib/analytics';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { isCookiesTrackingDisabled, setCookiesTracking } from '../Insights';
|
||||
|
||||
/**
|
||||
* Toast to accept or reject the use of cookies.
|
||||
*/
|
||||
|
||||
@@ -34,6 +34,10 @@ export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>
|
||||
href={resolved.href}
|
||||
title={resolved.text}
|
||||
style={style}
|
||||
insights={{
|
||||
target: block.data.ref,
|
||||
position: 'content',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -283,9 +283,9 @@ function CodeHighlightToken(props: {
|
||||
return <>{token.content}</>;
|
||||
}
|
||||
|
||||
if (!token.token.color) {
|
||||
return <>{token.token.content}</>;
|
||||
}
|
||||
// if (!token.token.color) {
|
||||
// return <>{token.token.content}</>;
|
||||
// }
|
||||
|
||||
return <span style={{ color: token.token.color }}>{token.token.content}</span>;
|
||||
// return <span style={{ color: token.token.color }}>{token.token.content}</span>;
|
||||
}
|
||||
|
||||
@@ -1,105 +1,110 @@
|
||||
import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api';
|
||||
import {
|
||||
createdBundledHighlighter,
|
||||
ThemedToken,
|
||||
createCssVariablesTheme,
|
||||
HighlighterGeneric,
|
||||
} from 'shiki/core';
|
||||
import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma';
|
||||
import { bundledLanguages } from 'shiki/langs';
|
||||
// @ts-ignore - onigWasm is a Wasm module
|
||||
import onigWasm from 'shiki/onig.wasm?module';
|
||||
// // @ts-ignore - onigWasm is a Wasm module
|
||||
// import {
|
||||
// createdBundledHighlighter,
|
||||
// ThemedToken,
|
||||
// createCssVariablesTheme,
|
||||
// HighlighterGeneric,
|
||||
// } from 'shiki/core';
|
||||
// // @ts-ignore - onigWasm is a Wasm module
|
||||
// import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma';
|
||||
// // @ts-ignore - onigWasm is a Wasm module
|
||||
// import { bundledLanguages } from 'shiki/langs';
|
||||
// // @ts-ignore - onigWasm is a Wasm module
|
||||
// import onigWasm from 'shiki/onig.wasm?module';
|
||||
|
||||
import { asyncMutexFunction, singleton } from '@/lib/async';
|
||||
// import { asyncMutexFunction, singleton } from '@/lib/async';
|
||||
import { getNodeText } from '@/lib/document';
|
||||
import { trace } from '@/lib/tracing';
|
||||
// import { trace } from '@/lib/tracing';
|
||||
|
||||
export type HighlightLine = {
|
||||
highlighted: boolean;
|
||||
tokens: HighlightToken[];
|
||||
};
|
||||
|
||||
export type HighlightToken =
|
||||
| { type: 'plain'; content: string }
|
||||
| { type: 'shiki'; token: ThemedToken }
|
||||
| { type: 'inline'; inline: DocumentInlineAnnotation; children: HighlightToken[] };
|
||||
export type HighlightToken =
|
||||
| { type: 'plain'; content: string }
|
||||
| { type: 'inline'; inline: DocumentInlineAnnotation; children: HighlightToken[] };
|
||||
|
||||
type InlineIndexed = { inline: any; start: number; end: number };
|
||||
// | { type: 'shiki'; token: ThemedToken }
|
||||
|
||||
type PositionedToken = ThemedToken & { start: number; end: number };
|
||||
// type InlineIndexed = { inline: any; start: number; end: number };
|
||||
|
||||
/**
|
||||
* Highlight a code block while preserving inline elements.
|
||||
*/
|
||||
// type PositionedToken = ThemedToken & { start: number; end: number };
|
||||
|
||||
// /**
|
||||
// * Highlight a code block while preserving inline elements.
|
||||
// */
|
||||
export async function highlight(block: DocumentBlockCode): Promise<HighlightLine[]> {
|
||||
const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
|
||||
if (!langName) {
|
||||
// Language not found, fallback to plain highlighting
|
||||
return plainHighlighting(block);
|
||||
}
|
||||
return plainHighlighting(block);
|
||||
// const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
|
||||
// if (!langName) {
|
||||
// // Language not found, fallback to plain highlighting
|
||||
// return plainHighlighting(block);
|
||||
// }
|
||||
|
||||
const inlines: InlineIndexed[] = [];
|
||||
const code = getPlainCodeBlock(block, inlines);
|
||||
// const inlines: InlineIndexed[] = [];
|
||||
// const code = getPlainCodeBlock(block, inlines);
|
||||
|
||||
inlines.sort((a, b) => {
|
||||
return a.start - b.start;
|
||||
});
|
||||
// inlines.sort((a, b) => {
|
||||
// return a.start - b.start;
|
||||
// });
|
||||
|
||||
const highlighter = await loadHighlighter();
|
||||
await loadHighlighterLanguage(highlighter, langName);
|
||||
// const highlighter = await loadHighlighter();
|
||||
// await loadHighlighterLanguage(highlighter, langName);
|
||||
|
||||
const lines = highlighter.codeToTokensBase(code, {
|
||||
lang: langName,
|
||||
tokenizeMaxLineLength: 400,
|
||||
});
|
||||
// const lines = highlighter.codeToTokensBase(code, {
|
||||
// lang: langName,
|
||||
// tokenizeMaxLineLength: 400,
|
||||
// });
|
||||
|
||||
let currentIndex = 0;
|
||||
return lines.map((tokens, index) => {
|
||||
const lineBlock = block.nodes[index];
|
||||
const result: HighlightToken[] = [];
|
||||
// let currentIndex = 0;
|
||||
// return lines.map((tokens, index) => {
|
||||
// const lineBlock = block.nodes[index];
|
||||
// const result: HighlightToken[] = [];
|
||||
|
||||
const eatToken = (): PositionedToken | null => {
|
||||
const token = tokens.shift();
|
||||
if (token) {
|
||||
currentIndex += token.content.length;
|
||||
}
|
||||
return token
|
||||
? { ...token, start: currentIndex - token.content.length, end: currentIndex }
|
||||
: null;
|
||||
};
|
||||
// const eatToken = (): PositionedToken | null => {
|
||||
// const token = tokens.shift();
|
||||
// if (token) {
|
||||
// currentIndex += token.content.length;
|
||||
// }
|
||||
// return token
|
||||
// ? { ...token, start: currentIndex - token.content.length, end: currentIndex }
|
||||
// : null;
|
||||
// };
|
||||
|
||||
while (tokens.length > 0) {
|
||||
result.push(...matchTokenAndInlines(eatToken, inlines));
|
||||
}
|
||||
// while (tokens.length > 0) {
|
||||
// result.push(...matchTokenAndInlines(eatToken, inlines));
|
||||
// }
|
||||
|
||||
currentIndex += 1; // for the \n
|
||||
// currentIndex += 1; // for the \n
|
||||
|
||||
return {
|
||||
highlighted: !!lineBlock.data.highlighted,
|
||||
tokens: result,
|
||||
};
|
||||
});
|
||||
// return {
|
||||
// highlighted: !!lineBlock.data.highlighted,
|
||||
// tokens: result,
|
||||
// };
|
||||
// });
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a language name.
|
||||
*/
|
||||
function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null {
|
||||
// @ts-ignore
|
||||
const lang = bundledLanguages[syntax];
|
||||
if (!lang) {
|
||||
return null;
|
||||
}
|
||||
// /**
|
||||
// * Validate a language name.
|
||||
// */
|
||||
// function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null {
|
||||
// // @ts-ignore
|
||||
// const lang = bundledLanguages[syntax];
|
||||
// if (!lang) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// @ts-ignore
|
||||
return syntax;
|
||||
}
|
||||
// // @ts-ignore
|
||||
// return syntax;
|
||||
// }
|
||||
|
||||
/**
|
||||
* Parse a code block without highlighting it.
|
||||
*/
|
||||
// /**
|
||||
// * Parse a code block without highlighting it.
|
||||
// */
|
||||
export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
||||
return block.nodes.map((lineBlock) => {
|
||||
return block.nodes.map((lineBlock: any) => {
|
||||
const tokens: HighlightToken[] = [];
|
||||
|
||||
for (const node of lineBlock.nodes) {
|
||||
@@ -108,17 +113,6 @@ export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
||||
type: 'plain',
|
||||
content: getNodeText(node),
|
||||
});
|
||||
} else {
|
||||
tokens.push({
|
||||
type: 'inline',
|
||||
inline: node,
|
||||
children: [
|
||||
{
|
||||
type: 'plain',
|
||||
content: getNodeText(node),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,214 +123,214 @@ export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
||||
});
|
||||
}
|
||||
|
||||
function matchTokenAndInlines(
|
||||
eat: () => PositionedToken | null,
|
||||
allInlines: InlineIndexed[],
|
||||
): HighlightToken[] {
|
||||
const initialToken = eat();
|
||||
if (!initialToken) {
|
||||
return [];
|
||||
}
|
||||
// function matchTokenAndInlines(
|
||||
// eat: () => PositionedToken | null,
|
||||
// allInlines: InlineIndexed[],
|
||||
// ): HighlightToken[] {
|
||||
// const initialToken = eat();
|
||||
// if (!initialToken) {
|
||||
// return [];
|
||||
// }
|
||||
|
||||
const inlines = allInlines.filter(
|
||||
(inline) => inline.start >= initialToken.start && inline.start < initialToken.end,
|
||||
);
|
||||
let token = initialToken;
|
||||
const result: HighlightToken[] = [];
|
||||
// const inlines = allInlines.filter(
|
||||
// (inline) => inline.start >= initialToken.start && inline.start < initialToken.end,
|
||||
// );
|
||||
// let token = initialToken;
|
||||
// const result: HighlightToken[] = [];
|
||||
|
||||
const matchAgainstInline = () => {
|
||||
const inline = inlines.shift();
|
||||
if (!inline) {
|
||||
result.push({
|
||||
type: 'shiki',
|
||||
token,
|
||||
});
|
||||
// const matchAgainstInline = () => {
|
||||
// const inline = inlines.shift();
|
||||
// if (!inline) {
|
||||
// result.push({
|
||||
// type: 'shiki',
|
||||
// token,
|
||||
// });
|
||||
|
||||
return;
|
||||
}
|
||||
// return;
|
||||
// }
|
||||
|
||||
const [before, afterBefore] = splitPositionedTokenAt(token, inline.start);
|
||||
if (before) {
|
||||
result.push({
|
||||
type: 'shiki',
|
||||
token: before,
|
||||
});
|
||||
}
|
||||
if (!afterBefore) {
|
||||
throw new Error(`expect afterBefore to not be empty`);
|
||||
}
|
||||
// const [before, afterBefore] = splitPositionedTokenAt(token, inline.start);
|
||||
// if (before) {
|
||||
// result.push({
|
||||
// type: 'shiki',
|
||||
// token: before,
|
||||
// });
|
||||
// }
|
||||
// if (!afterBefore) {
|
||||
// throw new Error(`expect afterBefore to not be empty`);
|
||||
// }
|
||||
|
||||
token = afterBefore;
|
||||
const children: HighlightToken[] = [];
|
||||
// token = afterBefore;
|
||||
// const children: HighlightToken[] = [];
|
||||
|
||||
// If shiki token finished before the end of the annotation or the annotation contains multiple tokens
|
||||
while (token.end < inline.end) {
|
||||
children.push({
|
||||
type: 'shiki',
|
||||
token: token,
|
||||
});
|
||||
// // If shiki token finished before the end of the annotation or the annotation contains multiple tokens
|
||||
// while (token.end < inline.end) {
|
||||
// children.push({
|
||||
// type: 'shiki',
|
||||
// token: token,
|
||||
// });
|
||||
|
||||
const next = eat();
|
||||
if (!next) {
|
||||
throw new Error(`expect token to not be empty`);
|
||||
}
|
||||
token = next;
|
||||
}
|
||||
// const next = eat();
|
||||
// if (!next) {
|
||||
// throw new Error(`expect token to not be empty`);
|
||||
// }
|
||||
// token = next;
|
||||
// }
|
||||
|
||||
const [inside, after] = splitPositionedTokenAt(token, inline.end);
|
||||
if (!inside) {
|
||||
throw new Error(`expect inside to not be empty`);
|
||||
}
|
||||
// const [inside, after] = splitPositionedTokenAt(token, inline.end);
|
||||
// if (!inside) {
|
||||
// throw new Error(`expect inside to not be empty`);
|
||||
// }
|
||||
|
||||
children.push({
|
||||
type: 'shiki',
|
||||
token: inside,
|
||||
});
|
||||
// children.push({
|
||||
// type: 'shiki',
|
||||
// token: inside,
|
||||
// });
|
||||
|
||||
result.push({
|
||||
type: 'inline',
|
||||
inline: inline.inline,
|
||||
children,
|
||||
});
|
||||
// result.push({
|
||||
// type: 'inline',
|
||||
// inline: inline.inline,
|
||||
// children,
|
||||
// });
|
||||
|
||||
if (after) {
|
||||
token = after;
|
||||
matchAgainstInline();
|
||||
}
|
||||
};
|
||||
// if (after) {
|
||||
// token = after;
|
||||
// matchAgainstInline();
|
||||
// }
|
||||
// };
|
||||
|
||||
matchAgainstInline();
|
||||
return result;
|
||||
}
|
||||
// matchAgainstInline();
|
||||
// return result;
|
||||
// }
|
||||
|
||||
function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string {
|
||||
let content = '';
|
||||
// function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string {
|
||||
// let content = '';
|
||||
|
||||
code.nodes.forEach((node, index) => {
|
||||
const lineContent = getPlainCodeBlockLine(node, inlines, content.length);
|
||||
content += lineContent;
|
||||
// code.nodes.forEach((node, index) => {
|
||||
// const lineContent = getPlainCodeBlockLine(node, inlines, content.length);
|
||||
// content += lineContent;
|
||||
|
||||
if (index < code.nodes.length - 1) {
|
||||
content += '\n';
|
||||
}
|
||||
});
|
||||
// if (index < code.nodes.length - 1) {
|
||||
// content += '\n';
|
||||
// }
|
||||
// });
|
||||
|
||||
return content;
|
||||
}
|
||||
// return content;
|
||||
// }
|
||||
|
||||
function getPlainCodeBlockLine(
|
||||
parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
|
||||
inlines: InlineIndexed[],
|
||||
index: number,
|
||||
): string {
|
||||
let content = '';
|
||||
// function getPlainCodeBlockLine(
|
||||
// parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
|
||||
// inlines: InlineIndexed[],
|
||||
// index: number,
|
||||
// ): string {
|
||||
// let content = '';
|
||||
|
||||
for (const node of parent.nodes) {
|
||||
if (node.object === 'text') {
|
||||
content += cleanupLine(node.leaves.map((leaf) => leaf.text).join(''));
|
||||
} else {
|
||||
const start = index + content.length;
|
||||
content += getPlainCodeBlockLine(node, inlines, index + content.length);
|
||||
const end = index + content.length;
|
||||
// for (const node of parent.nodes) {
|
||||
// if (node.object === 'text') {
|
||||
// content += cleanupLine(node.leaves.map((leaf) => leaf.text).join(''));
|
||||
// } else {
|
||||
// const start = index + content.length;
|
||||
// content += getPlainCodeBlockLine(node, inlines, index + content.length);
|
||||
// const end = index + content.length;
|
||||
|
||||
inlines.push({
|
||||
inline: node,
|
||||
start,
|
||||
end,
|
||||
});
|
||||
}
|
||||
}
|
||||
// inlines.push({
|
||||
// inline: node,
|
||||
// start,
|
||||
// end,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
return content;
|
||||
}
|
||||
// return content;
|
||||
// }
|
||||
|
||||
function slicePositionedToken(
|
||||
token: PositionedToken,
|
||||
relativeStart: number,
|
||||
relativeLength: number,
|
||||
): PositionedToken {
|
||||
return {
|
||||
...token,
|
||||
start: token.start + relativeStart,
|
||||
end: token.start + relativeStart + relativeLength,
|
||||
content: token.content.slice(relativeStart, relativeStart + relativeLength),
|
||||
};
|
||||
}
|
||||
// function slicePositionedToken(
|
||||
// token: PositionedToken,
|
||||
// relativeStart: number,
|
||||
// relativeLength: number,
|
||||
// ): PositionedToken {
|
||||
// return {
|
||||
// ...token,
|
||||
// start: token.start + relativeStart,
|
||||
// end: token.start + relativeStart + relativeLength,
|
||||
// content: token.content.slice(relativeStart, relativeStart + relativeLength),
|
||||
// };
|
||||
// }
|
||||
|
||||
function splitPositionedTokenAt(
|
||||
token: PositionedToken,
|
||||
absoluteIndex: number,
|
||||
): [PositionedToken | null, PositionedToken | null] {
|
||||
if (absoluteIndex < token.start || absoluteIndex > token.end) {
|
||||
throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
|
||||
}
|
||||
// function splitPositionedTokenAt(
|
||||
// token: PositionedToken,
|
||||
// absoluteIndex: number,
|
||||
// ): [PositionedToken | null, PositionedToken | null] {
|
||||
// if (absoluteIndex < token.start || absoluteIndex > token.end) {
|
||||
// throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
|
||||
// }
|
||||
|
||||
const before = slicePositionedToken(token, 0, absoluteIndex - token.start);
|
||||
const after = slicePositionedToken(
|
||||
token,
|
||||
absoluteIndex - token.start,
|
||||
token.end - absoluteIndex,
|
||||
);
|
||||
// const before = slicePositionedToken(token, 0, absoluteIndex - token.start);
|
||||
// const after = slicePositionedToken(
|
||||
// token,
|
||||
// absoluteIndex - token.start,
|
||||
// token.end - absoluteIndex,
|
||||
// );
|
||||
|
||||
return [
|
||||
isEmptyPositionedToken(before) ? null : before,
|
||||
isEmptyPositionedToken(after) ? null : after,
|
||||
];
|
||||
}
|
||||
// return [
|
||||
// isEmptyPositionedToken(before) ? null : before,
|
||||
// isEmptyPositionedToken(after) ? null : after,
|
||||
// ];
|
||||
// }
|
||||
|
||||
function isEmptyPositionedToken(token: PositionedToken): boolean {
|
||||
return token.start === token.end;
|
||||
}
|
||||
// function isEmptyPositionedToken(token: PositionedToken): boolean {
|
||||
// return token.start === token.end;
|
||||
// }
|
||||
|
||||
/**
|
||||
* Currently it's possible for some lines to contain \r characters, we need to remove them
|
||||
* as they are considered as new lines by shikijs.
|
||||
*/
|
||||
function cleanupLine(line: string): string {
|
||||
return line.replace(/\r/g, '');
|
||||
}
|
||||
// /**
|
||||
// * Currently it's possible for some lines to contain \r characters, we need to remove them
|
||||
// * as they are considered as new lines by shikijs.
|
||||
// */
|
||||
// function cleanupLine(line: string): string {
|
||||
// return line.replace(/\r/g, '');
|
||||
// }
|
||||
|
||||
const createHighlighter = createdBundledHighlighter<any, any>({
|
||||
langs: bundledLanguages,
|
||||
themes: {},
|
||||
engine: () => createOnigurumaEngine(import('shiki/wasm')),
|
||||
});
|
||||
// const createHighlighter = createdBundledHighlighter<any, any>({
|
||||
// langs: bundledLanguages,
|
||||
// themes: {},
|
||||
// engine: () => createOnigurumaEngine(import('shiki/wasm')),
|
||||
// });
|
||||
|
||||
/**
|
||||
* Load the highlighter, only once, and reuse it.
|
||||
* It makes sure to handle concurrent calls.
|
||||
*/
|
||||
const loadHighlighter = singleton(async () => {
|
||||
return await trace('highlighting.loadHighlighter', async () => {
|
||||
if (typeof onigWasm !== 'string') {
|
||||
// When running bun test, the import is a string, we ignore it and let the module
|
||||
// loads it on its own.
|
||||
//
|
||||
// Otherwise for Vercel/Cloudflare, we need to load it ourselves.
|
||||
await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj));
|
||||
}
|
||||
// /**
|
||||
// * Load the highlighter, only once, and reuse it.
|
||||
// * It makes sure to handle concurrent calls.
|
||||
// */
|
||||
// const loadHighlighter = singleton(async () => {
|
||||
// return await trace('highlighting.loadHighlighter', async () => {
|
||||
// if (typeof onigWasm !== 'string') {
|
||||
// // When running bun test, the import is a string, we ignore it and let the module
|
||||
// // loads it on its own.
|
||||
// //
|
||||
// // Otherwise for Vercel/Cloudflare, we need to load it ourselves.
|
||||
// await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj));
|
||||
// }
|
||||
|
||||
const highlighter = await createHighlighter({
|
||||
themes: [createCssVariablesTheme()],
|
||||
langs: [],
|
||||
});
|
||||
return highlighter;
|
||||
});
|
||||
});
|
||||
// const highlighter = await createHighlighter({
|
||||
// themes: [createCssVariablesTheme()],
|
||||
// langs: [],
|
||||
// });
|
||||
// return highlighter;
|
||||
// });
|
||||
// });
|
||||
|
||||
const loadLanguagesMutex = asyncMutexFunction();
|
||||
async function loadHighlighterLanguage(
|
||||
highlighter: HighlighterGeneric<any, any>,
|
||||
lang: keyof typeof bundledLanguages,
|
||||
) {
|
||||
await loadLanguagesMutex.runBlocking(async () => {
|
||||
if (highlighter.getLoadedLanguages().includes(lang)) {
|
||||
return;
|
||||
}
|
||||
// const loadLanguagesMutex = asyncMutexFunction();
|
||||
// async function loadHighlighterLanguage(
|
||||
// highlighter: HighlighterGeneric<any, any>,
|
||||
// lang: keyof typeof bundledLanguages,
|
||||
// ) {
|
||||
// await loadLanguagesMutex.runBlocking(async () => {
|
||||
// if (highlighter.getLoadedLanguages().includes(lang)) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
await trace(
|
||||
`highlighting.loadLanguage(${lang})`,
|
||||
async () => await highlighter.loadLanguage(lang),
|
||||
);
|
||||
});
|
||||
}
|
||||
// await trace(
|
||||
// `highlighting.loadLanguage(${lang})`,
|
||||
// async () => await highlighter.loadLanguage(lang),
|
||||
// );
|
||||
// });
|
||||
// }
|
||||
|
||||
@@ -6,6 +6,7 @@ import { tcls } from '@/lib/tailwind';
|
||||
import { BlockProps } from './Block';
|
||||
import { Caption } from './Caption';
|
||||
import { FileIcon } from './FileIcon';
|
||||
import { Link } from '../primitives';
|
||||
|
||||
export async function File(props: BlockProps<DocumentBlockFile>) {
|
||||
const { block, context } = props;
|
||||
@@ -21,9 +22,13 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
|
||||
|
||||
return (
|
||||
<Caption {...props} wrapperStyle={[]}>
|
||||
<a
|
||||
<Link
|
||||
href={file.downloadURL}
|
||||
download={file.name}
|
||||
insights={{
|
||||
target: block.data.ref,
|
||||
position: 'content',
|
||||
}}
|
||||
className={tcls(
|
||||
'group/file',
|
||||
'flex',
|
||||
@@ -77,7 +82,7 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
|
||||
{contentType}
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
</Link>
|
||||
</Caption>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
||||
return (
|
||||
<Link
|
||||
href={resolved.href}
|
||||
className="underline underline-offset-2 text-primary hover:text-primary-700 transition-colors "
|
||||
className="underline underline-offset-2 text-primary hover:text-primary-700 transition-colors"
|
||||
insights={{
|
||||
target: inline.data.ref,
|
||||
position: 'content',
|
||||
}}
|
||||
>
|
||||
<Inlines
|
||||
context={context}
|
||||
|
||||
@@ -38,6 +38,8 @@ export function ListItem(props: BlockProps<DocumentBlockListItem>) {
|
||||
'[&:is(h2)>div]:mt-0',
|
||||
'[&:is(h3)>div]:mt-0',
|
||||
'[&:is(h4)>div]:mt-0',
|
||||
// Override the "mx-auto" class from UnwrappedBlocks
|
||||
'mx-0',
|
||||
)}
|
||||
style="space-y-2 flex flex-col flex-1"
|
||||
/>
|
||||
@@ -135,7 +137,7 @@ function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.R
|
||||
className={tcls(
|
||||
textStyle.textSize,
|
||||
textStyle.lineHeight,
|
||||
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark/6 dark:text-light/5',
|
||||
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark-4 dark:text-light-4',
|
||||
)}
|
||||
>
|
||||
{props.children}
|
||||
|
||||
@@ -15,5 +15,15 @@ export async function Mention(props: InlineProps<DocumentInlineMention>) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <StyledLink href={resolved.href}>{resolved.text}</StyledLink>;
|
||||
return (
|
||||
<StyledLink
|
||||
href={resolved.href}
|
||||
insights={{
|
||||
target: inline.data.ref,
|
||||
position: 'content',
|
||||
}}
|
||||
>
|
||||
{resolved.text}
|
||||
</StyledLink>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DocumentBlockSwagger } from '@gitbook/api';
|
||||
import { DocumentBlockOpenAPI } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { OpenAPIOperation } from '@gitbook/react-openapi';
|
||||
import React from 'react';
|
||||
@@ -16,7 +16,7 @@ import './scalar.css';
|
||||
/**
|
||||
* Render an OpenAPI block.
|
||||
*/
|
||||
export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
|
||||
export async function OpenAPI(props: BlockProps<DocumentBlockOpenAPI>) {
|
||||
const { block, style } = props;
|
||||
return (
|
||||
<div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}>
|
||||
@@ -27,7 +27,7 @@ export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
|
||||
);
|
||||
}
|
||||
|
||||
async function OpenAPIBody(props: BlockProps<DocumentBlockSwagger>) {
|
||||
async function OpenAPIBody(props: BlockProps<DocumentBlockOpenAPI>) {
|
||||
const { block, context } = props;
|
||||
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ContentRef, DocumentTableViewCards } from '@gitbook/api';
|
||||
import React from 'react';
|
||||
|
||||
import { Link } from '@/components/primitives';
|
||||
import { Image } from '@/components/utils';
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
@@ -153,17 +154,21 @@ export async function RecordCard(
|
||||
'before:dark:ring-light/2',
|
||||
] as ClassValue;
|
||||
|
||||
if (target) {
|
||||
if (target && targetRef) {
|
||||
return (
|
||||
<a
|
||||
<Link
|
||||
href={target.href}
|
||||
className={tcls(style, [
|
||||
'hover:before:ring-dark/4',
|
||||
'dark:hover:before:ring-light/4',
|
||||
])}
|
||||
insights={{
|
||||
target: targetRef,
|
||||
position: 'content',
|
||||
}}
|
||||
>
|
||||
{body}
|
||||
</a>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ContentRef, DocumentBlockTable } from '@gitbook/api';
|
||||
import { ContentRef, ContentRefUser, DocumentBlockTable } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
@@ -148,6 +148,17 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
|
||||
href={ref.href}
|
||||
target="_blank"
|
||||
style={['flex', 'flex-row', 'items-center', 'gap-2']}
|
||||
insights={
|
||||
ref.file
|
||||
? {
|
||||
target: {
|
||||
kind: 'file',
|
||||
file: ref.file.id,
|
||||
},
|
||||
position: 'content',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{contentType === 'image' ? (
|
||||
<Image
|
||||
@@ -178,8 +189,9 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
|
||||
</Tag>
|
||||
);
|
||||
case 'content-ref': {
|
||||
const resolved = value
|
||||
? await context.resolveContentRef(value as ContentRef, {
|
||||
const contentRef = value ? (value as ContentRef) : null;
|
||||
const resolved = contentRef
|
||||
? await context.resolveContentRef(contentRef, {
|
||||
resolveAnchorText: true,
|
||||
iconStyle: ['mr-2', 'text-dark/6', 'dark:text-light/6'],
|
||||
})
|
||||
@@ -191,26 +203,51 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
|
||||
>
|
||||
{resolved?.icon ?? null}
|
||||
{resolved ? (
|
||||
<StyledLink href={resolved.href}>{resolved.text}</StyledLink>
|
||||
<StyledLink
|
||||
href={resolved.href}
|
||||
insights={
|
||||
contentRef
|
||||
? {
|
||||
target: contentRef,
|
||||
position: 'content',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{resolved.text}
|
||||
</StyledLink>
|
||||
) : null}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
case 'users': {
|
||||
const resolved = await Promise.all(
|
||||
(value as string[]).map((userId) =>
|
||||
context.resolveContentRef({
|
||||
(value as string[]).map(async (userId) => {
|
||||
const contentRef: ContentRefUser = {
|
||||
kind: 'user',
|
||||
user: userId,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const resolved = await context.resolveContentRef(contentRef);
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [contentRef, resolved] as const;
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
|
||||
{resolved.filter(filterOutNullable).map((file, index) => (
|
||||
<StyledLink key={index} href={file.href}>
|
||||
{file.text}
|
||||
{resolved.filter(filterOutNullable).map(([contentRef, resolved], index) => (
|
||||
<StyledLink
|
||||
key={index}
|
||||
href={resolved.href}
|
||||
insights={{
|
||||
target: contentRef,
|
||||
position: 'content',
|
||||
}}
|
||||
>
|
||||
{resolved.text}
|
||||
</StyledLink>
|
||||
))}
|
||||
</Tag>
|
||||
|
||||
@@ -40,6 +40,10 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
|
||||
'dark:text-light/8',
|
||||
'dark:hover:text-light/9',
|
||||
)}
|
||||
insights={{
|
||||
target: link.to,
|
||||
position: 'footer',
|
||||
}}
|
||||
>
|
||||
{link.title}
|
||||
</Link>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { DetailedHTMLProps, HTMLAttributes, useId } from 'react';
|
||||
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
import { Link } from '../primitives';
|
||||
import { Link, LinkInsightsProps } from '../primitives';
|
||||
|
||||
export type DropdownButtonProps<E extends HTMLElement = HTMLElement> = Omit<
|
||||
Partial<DetailedHTMLProps<HTMLAttributes<E>, E>>,
|
||||
@@ -110,19 +110,22 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
|
||||
/**
|
||||
* Menu item in a dropdown.
|
||||
*/
|
||||
export function DropdownMenuItem(props: {
|
||||
href: string | null;
|
||||
active?: boolean;
|
||||
className?: ClassValue;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { children, active = false, href, className } = props;
|
||||
export function DropdownMenuItem(
|
||||
props: {
|
||||
href: string | null;
|
||||
active?: boolean;
|
||||
className?: ClassValue;
|
||||
children: React.ReactNode;
|
||||
} & LinkInsightsProps,
|
||||
) {
|
||||
const { children, active = false, href, className, insights } = props;
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
prefetch={false}
|
||||
insights={insights}
|
||||
className={tcls(
|
||||
'px-3 py-1 text-sm rounded straight-corners:rounded-sm',
|
||||
active ? 'bg-primary/3 dark:bg-light/2 text-primary-600' : null,
|
||||
|
||||
@@ -95,7 +95,25 @@ export function Header(props: {
|
||||
<HeaderLogo site={site} space={space} customization={customization} />
|
||||
{!hasSiteSections && isMultiVariants ? (
|
||||
<div className="z-20 shrink hidden sm:block">
|
||||
<SpacesDropdown space={space} spaces={spaces} />
|
||||
<SpacesDropdown
|
||||
className={tcls(
|
||||
!isCustomizationDefault &&
|
||||
withTopHeader && [
|
||||
'bg-header-link/2',
|
||||
'dark:bg-header-link/2',
|
||||
'text-header-link/8',
|
||||
'dark:text-header-link/8',
|
||||
'ring-1',
|
||||
'ring-header-link/4',
|
||||
'dark:ring-header-link/4',
|
||||
'contrast-more:bg-header-background',
|
||||
'contrast-more:text-header-link',
|
||||
'contrast-more:ring-header-link',
|
||||
],
|
||||
)}
|
||||
space={space}
|
||||
spaces={spaces}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
CustomizationHeaderPreset,
|
||||
SiteCustomizationSettings,
|
||||
CustomizationHeaderItem,
|
||||
ContentRef,
|
||||
} from '@gitbook/api';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
@@ -35,7 +36,7 @@ export async function HeaderLink(props: {
|
||||
<Dropdown
|
||||
className="shrink"
|
||||
button={(buttonProps) => {
|
||||
if (!target) {
|
||||
if (!target || !link.to) {
|
||||
return (
|
||||
<HeaderItemDropdown
|
||||
{...buttonProps}
|
||||
@@ -47,6 +48,7 @@ export async function HeaderLink(props: {
|
||||
return (
|
||||
<HeaderLinkNavItem
|
||||
{...buttonProps}
|
||||
linkTarget={link.to}
|
||||
linkStyle={linkStyle}
|
||||
headerPreset={headerPreset}
|
||||
title={link.title}
|
||||
@@ -65,12 +67,13 @@ export async function HeaderLink(props: {
|
||||
);
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
if (!target || !link.to) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<HeaderLinkNavItem
|
||||
linkTarget={link.to}
|
||||
linkStyle={linkStyle}
|
||||
headerPreset={headerPreset}
|
||||
title={link.title}
|
||||
@@ -81,6 +84,7 @@ export async function HeaderLink(props: {
|
||||
}
|
||||
|
||||
export type HeaderLinkNavItemProps = {
|
||||
linkTarget: ContentRef;
|
||||
linkStyle: NonNullable<CustomizationHeaderItem['style']>;
|
||||
headerPreset: CustomizationHeaderPreset;
|
||||
title: string;
|
||||
@@ -89,14 +93,15 @@ export type HeaderLinkNavItemProps = {
|
||||
} & DropdownButtonProps<HTMLElement>;
|
||||
|
||||
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
|
||||
switch (props.linkStyle) {
|
||||
const { linkStyle, ...rest } = props;
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
case 'button-primary':
|
||||
return <HeaderItemButton {...props} linkStyle={props.linkStyle} />;
|
||||
return <HeaderItemButton {...rest} linkStyle={linkStyle} />;
|
||||
case 'link':
|
||||
return <HeaderItemLink {...props} />;
|
||||
return <HeaderItemLink {...rest} />;
|
||||
default:
|
||||
assertNever(props.linkStyle);
|
||||
assertNever(linkStyle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +110,7 @@ function HeaderItemButton(
|
||||
linkStyle: 'button-secondary' | 'button-primary';
|
||||
},
|
||||
) {
|
||||
const { linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
|
||||
const { linkTarget, linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
|
||||
const variant = (() => {
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
@@ -139,6 +144,10 @@ function HeaderItemButton(
|
||||
),
|
||||
}[linkStyle],
|
||||
)}
|
||||
insights={{
|
||||
target: linkTarget,
|
||||
position: 'header',
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{title}
|
||||
@@ -158,10 +167,18 @@ function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset
|
||||
);
|
||||
}
|
||||
|
||||
function HeaderItemLink(props: HeaderLinkNavItemProps) {
|
||||
const { headerPreset, title, isDropdown, href, ...rest } = props;
|
||||
function HeaderItemLink(props: Omit<HeaderLinkNavItemProps, 'linkStyle'>) {
|
||||
const { linkTarget, headerPreset, title, isDropdown, href, ...rest } = props;
|
||||
return (
|
||||
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
|
||||
<Link
|
||||
href={href}
|
||||
className={getHeaderLinkClassName({ headerPreset })}
|
||||
insights={{
|
||||
target: linkTarget,
|
||||
position: 'header',
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
<span className="truncate min-w-0">{title}</span>
|
||||
{isDropdown ? <DropdownChevron /> : null}
|
||||
</Link>
|
||||
@@ -198,5 +215,9 @@ async function SubHeaderLink(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <DropdownMenuItem href={target.href}>{link.title}</DropdownMenuItem>;
|
||||
return (
|
||||
<DropdownMenuItem href={target.href} insights={{ target: link.to, position: 'header' }}>
|
||||
{link.title}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -76,7 +76,19 @@ async function MoreMenuLink(props: {
|
||||
{'links' in link && link.links.length > 0 && (
|
||||
<hr className="first:hidden border-t border-light-3 dark:border-dark-3 my-1 -mx-2" />
|
||||
)}
|
||||
<DropdownMenuItem href={target?.href ?? null}>{link.title}</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
href={target?.href ?? null}
|
||||
insights={
|
||||
link.to
|
||||
? {
|
||||
target: link.to,
|
||||
position: 'header',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{link.title}
|
||||
</DropdownMenuItem>
|
||||
{'links' in link
|
||||
? link.links.map((subLink, index) => (
|
||||
<MoreMenuLink key={index} {...props} link={subLink} />
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
'use client';
|
||||
|
||||
import type * as api from '@gitbook/api';
|
||||
import { OpenAPIOperationContextProvider } from '@gitbook/react-openapi';
|
||||
import cookies from 'js-cookie';
|
||||
import * as React from 'react';
|
||||
import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
|
||||
|
||||
import { getSession } from './sessions';
|
||||
import { getVisitorId } from './visitorId';
|
||||
|
||||
type SiteEventName = api.SiteInsightsEvent['type'];
|
||||
|
||||
/**
|
||||
* Global context for all events in the session.
|
||||
*/
|
||||
interface InsightsEventContext {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
siteSectionId: string | undefined;
|
||||
siteSpaceId: string | undefined;
|
||||
spaceId: string;
|
||||
siteShareKey: string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context for an event on a page.
|
||||
*/
|
||||
interface InsightsEventPageContext {
|
||||
pageId: string | null;
|
||||
revisionId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options when tracking an event.
|
||||
*/
|
||||
interface InsightsEventOptions {
|
||||
/**
|
||||
* If true, the event will be sent immediately.
|
||||
* Passes true for events that could cause a page unload.
|
||||
*/
|
||||
immediate?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Input data for an event.
|
||||
*/
|
||||
type TrackEventInput<EventName extends SiteEventName> = { type: EventName } & Omit<
|
||||
Extract<api.SiteInsightsEvent, { type: EventName }>,
|
||||
'location' | 'session'
|
||||
>;
|
||||
|
||||
/**
|
||||
* Callback to track an event.
|
||||
*/
|
||||
type TrackEventCallback = <EventName extends SiteEventName>(
|
||||
event: TrackEventInput<EventName>,
|
||||
ctx?: InsightsEventPageContext,
|
||||
options?: InsightsEventOptions,
|
||||
) => void;
|
||||
|
||||
const InsightsContext = React.createContext<TrackEventCallback | null>(null);
|
||||
|
||||
interface InsightsProviderProps extends InsightsEventContext {
|
||||
enabled: boolean;
|
||||
apiHost: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the content of the app with the InsightsProvider to track events.
|
||||
*/
|
||||
export function InsightsProvider(props: InsightsProviderProps) {
|
||||
const { enabled, apiHost, children, ...context } = props;
|
||||
|
||||
const visitorIdRef = React.useRef<string | null>(null);
|
||||
const eventsRef = React.useRef<{
|
||||
[pathname: string]:
|
||||
| {
|
||||
url: string;
|
||||
events: TrackEventInput<SiteEventName>[];
|
||||
context: InsightsEventContext;
|
||||
pageContext?: InsightsEventPageContext;
|
||||
}
|
||||
| undefined;
|
||||
}>({});
|
||||
|
||||
/**
|
||||
* Get the visitor ID and store it in a ref.
|
||||
*/
|
||||
React.useEffect(() => {
|
||||
getVisitorId().then((visitorId) => {
|
||||
visitorIdRef.current = visitorId;
|
||||
});
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Synchronously flush all the pending events.
|
||||
*/
|
||||
const flushEventsSync = useEventCallback(() => {
|
||||
const session = getSession();
|
||||
const visitorId = visitorIdRef.current;
|
||||
if (!visitorId) {
|
||||
throw new Error('Visitor ID should be set before flushing events');
|
||||
}
|
||||
|
||||
const allEvents: api.SiteInsightsEvent[] = [];
|
||||
|
||||
for (const pathname in eventsRef.current) {
|
||||
const eventsForPathname = eventsRef.current[pathname];
|
||||
if (!eventsForPathname || !eventsForPathname.events.length) {
|
||||
continue;
|
||||
}
|
||||
if (!eventsForPathname.pageContext) {
|
||||
console.warn('No page context for flushing events of', pathname, eventsForPathname);
|
||||
continue;
|
||||
}
|
||||
|
||||
allEvents.push(
|
||||
...transformEvents({
|
||||
url: eventsForPathname.url,
|
||||
events: eventsForPathname.events,
|
||||
context,
|
||||
pageContext: eventsForPathname.pageContext,
|
||||
visitorId,
|
||||
sessionId: session.id,
|
||||
}),
|
||||
);
|
||||
|
||||
// Reset the events for the next flush
|
||||
eventsRef.current[pathname] = {
|
||||
...eventsForPathname,
|
||||
events: [],
|
||||
};
|
||||
}
|
||||
|
||||
if (allEvents.length > 0) {
|
||||
if (enabled) {
|
||||
console.log('Sending events', allEvents);
|
||||
sendEvents({
|
||||
apiHost,
|
||||
organizationId: context.organizationId,
|
||||
siteId: context.siteId,
|
||||
events: allEvents,
|
||||
});
|
||||
} else {
|
||||
console.log('Skipping sending events', allEvents);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const flushBatchedEvents = useDebounceCallback(async () => {
|
||||
const visitorId = visitorIdRef.current ?? (await getVisitorId());
|
||||
visitorIdRef.current = visitorId;
|
||||
|
||||
flushEventsSync();
|
||||
}, 1500);
|
||||
|
||||
const trackEvent: TrackEventCallback = useEventCallback(
|
||||
(
|
||||
event: TrackEventInput<SiteEventName>,
|
||||
ctx?: InsightsEventPageContext,
|
||||
options?: InsightsEventOptions,
|
||||
) => {
|
||||
console.log('Logging event', event, ctx);
|
||||
|
||||
const pathname = window.location.pathname;
|
||||
const previous = eventsRef.current[pathname];
|
||||
eventsRef.current[pathname] = {
|
||||
pageContext: previous?.pageContext ?? ctx,
|
||||
url: previous?.url ?? window.location.href,
|
||||
events: [
|
||||
...(previous?.events ?? []),
|
||||
{
|
||||
...event,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
context,
|
||||
};
|
||||
|
||||
if (eventsRef.current[pathname].pageContext !== undefined) {
|
||||
// If the pageId is set, we know that the page_view event has been tracked
|
||||
// and we can flush the events
|
||||
if (options?.immediate && visitorIdRef.current) {
|
||||
flushBatchedEvents.cancel();
|
||||
flushEventsSync();
|
||||
} else {
|
||||
flushBatchedEvents();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// When the page is unloaded, flush all events
|
||||
React.useEffect(() => {
|
||||
window.addEventListener('beforeunload', flushEventsSync);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', flushEventsSync);
|
||||
};
|
||||
}, [flushEventsSync]);
|
||||
|
||||
return (
|
||||
<InsightsContext.Provider value={trackEvent}>
|
||||
<OpenAPIOperationContextProvider
|
||||
onOpenClient={(operation) => {
|
||||
trackEvent({ type: 'api_client_open', operation });
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</OpenAPIOperationContextProvider>
|
||||
</InsightsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a callback to track an event.
|
||||
*/
|
||||
export function useTrackEvent(): TrackEventCallback {
|
||||
const trackEvent = React.useContext(InsightsContext);
|
||||
if (!trackEvent) {
|
||||
throw new Error('useTrackEvent must be used within an InsightsProvider');
|
||||
}
|
||||
|
||||
return trackEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Post the events to the server.
|
||||
*/
|
||||
function sendEvents(args: {
|
||||
apiHost: string;
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
events: api.SiteInsightsEvent[];
|
||||
}) {
|
||||
const { apiHost, organizationId, siteId, events } = args;
|
||||
const url = new URL(apiHost);
|
||||
url.pathname = `/v1/orgs/${organizationId}/sites/${siteId}/insights/events`;
|
||||
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
keepalive: true,
|
||||
body: JSON.stringify({
|
||||
events,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the events to the format expected by the API.
|
||||
*/
|
||||
function transformEvents(input: {
|
||||
url: string;
|
||||
events: TrackEventInput<SiteEventName>[];
|
||||
context: InsightsEventContext;
|
||||
pageContext: InsightsEventPageContext;
|
||||
visitorId: string;
|
||||
sessionId: string;
|
||||
}): api.SiteInsightsEvent[] {
|
||||
const session: api.SiteInsightsEventSession = {
|
||||
sessionId: input.sessionId,
|
||||
visitorId: input.visitorId,
|
||||
userAgent: window.navigator.userAgent,
|
||||
language: window.navigator.language,
|
||||
cookies: cookies.get(),
|
||||
referrer: document.referrer || null,
|
||||
};
|
||||
|
||||
const location: api.SiteInsightsEventLocation = {
|
||||
url: input.url,
|
||||
siteSection: input.context.siteSectionId ?? null,
|
||||
siteSpace: input.context.siteSpaceId ?? null,
|
||||
space: input.context.spaceId,
|
||||
siteShareKey: input.context.siteShareKey ?? null,
|
||||
page: input.pageContext.pageId,
|
||||
revision: input.pageContext.revisionId,
|
||||
};
|
||||
|
||||
return input.events.map((partialEvent) => {
|
||||
// @ts-expect-error: Partial event
|
||||
const event: api.SiteInsightsEvent = {
|
||||
...partialEvent,
|
||||
session,
|
||||
location,
|
||||
};
|
||||
|
||||
return event;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { useTrackEvent } from './InsightsProvider';
|
||||
|
||||
/**
|
||||
* Track a page view event.
|
||||
*/
|
||||
export function TrackPageViewEvent(props: { pageId: string | null; revisionId: string }) {
|
||||
const { pageId, revisionId } = props;
|
||||
//const trackEvent = useTrackEvent();
|
||||
|
||||
// React.useEffect(() => {
|
||||
// trackEvent(
|
||||
// {
|
||||
// type: 'page_view',
|
||||
// },
|
||||
// {
|
||||
// pageId,
|
||||
// revisionId,
|
||||
// },
|
||||
// );
|
||||
// }, [pageId, revisionId, trackEvent]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import cookies from 'js-cookie';
|
||||
|
||||
const GRANTED_COOKIE = '__gitbook_cookie_granted';
|
||||
|
||||
/**
|
||||
* Accept or reject cookies.
|
||||
*/
|
||||
export function setCookiesTracking(enabled: boolean) {
|
||||
cookies.set(GRANTED_COOKIE, enabled ? 'yes' : 'no', {
|
||||
expires: 365,
|
||||
sameSite: 'none',
|
||||
secure: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if cookies are accepted or not.
|
||||
* Return `undefined` if state is not known.
|
||||
*/
|
||||
export function isCookiesTrackingDisabled() {
|
||||
const state = cookies.get(GRANTED_COOKIE);
|
||||
|
||||
if (state === 'yes') {
|
||||
return false;
|
||||
} else if (state === 'no') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './InsightsProvider';
|
||||
export * from './visitorId';
|
||||
export * from './cookies';
|
||||
export * from './TrackPageViewEvent';
|
||||
@@ -0,0 +1,71 @@
|
||||
'use client';
|
||||
|
||||
import { generateRandomId } from './utils';
|
||||
|
||||
const SESSION_TTL = 1000 * 60 * 30; // 30 minutes
|
||||
|
||||
interface Session {
|
||||
id: string;
|
||||
lastActiveAt: number;
|
||||
}
|
||||
|
||||
let currentSession: Session | null = null;
|
||||
|
||||
const SESSION_KEY = '__gitbook_session';
|
||||
|
||||
/**
|
||||
* Get the current session.
|
||||
*/
|
||||
export function getSession(): Session {
|
||||
if (currentSession) {
|
||||
return currentSession;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawSession =
|
||||
typeof localStorage !== 'undefined' ? localStorage.getItem(SESSION_KEY) : null;
|
||||
|
||||
if (rawSession) {
|
||||
const storedSession = JSON.parse(rawSession);
|
||||
|
||||
if (
|
||||
typeof storedSession === 'object' &&
|
||||
typeof storedSession.lastActiveAt === 'number' &&
|
||||
typeof storedSession.id === 'string' &&
|
||||
storedSession.lastActiveAt + SESSION_TTL > Date.now()
|
||||
) {
|
||||
currentSession = storedSession as Session;
|
||||
touchSession();
|
||||
return currentSession;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing session', error);
|
||||
}
|
||||
|
||||
currentSession = {
|
||||
id: generateRandomId(),
|
||||
lastActiveAt: Date.now(),
|
||||
};
|
||||
saveSession();
|
||||
return currentSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the session.
|
||||
*/
|
||||
export function touchSession() {
|
||||
if (currentSession) {
|
||||
currentSession.lastActiveAt = Date.now();
|
||||
saveSession();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the session to the local storage.
|
||||
*/
|
||||
export function saveSession() {
|
||||
if (typeof localStorage !== 'undefined' && currentSession) {
|
||||
localStorage.setItem(SESSION_KEY, JSON.stringify(currentSession));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generate a random ID.
|
||||
*/
|
||||
export function generateRandomId(): string {
|
||||
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
||||
return `${crypto.randomUUID()}R`;
|
||||
}
|
||||
|
||||
// Fallback for old browsers
|
||||
return `${Math.random().toString(36).substring(2)}R`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import cookies from 'js-cookie';
|
||||
|
||||
import { isCookiesTrackingDisabled } from './cookies';
|
||||
import { generateRandomId } from './utils';
|
||||
|
||||
const VISITORID_COOKIE = '__session';
|
||||
|
||||
let visitorId: string | null = null;
|
||||
let pendingVisitorId: Promise<string> | null = null;
|
||||
|
||||
/**
|
||||
* Return the current visitor identifier.
|
||||
*/
|
||||
export async function getVisitorId(): Promise<string> {
|
||||
if (!visitorId) {
|
||||
if (!pendingVisitorId) {
|
||||
pendingVisitorId = fetchVisitorID().finally(() => {
|
||||
pendingVisitorId = null;
|
||||
});
|
||||
}
|
||||
|
||||
visitorId = await pendingVisitorId;
|
||||
}
|
||||
|
||||
return visitorId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Propose a visitor identifier to the GitBook.com server and get the devideId back.
|
||||
*/
|
||||
async function fetchVisitorID(): Promise<string> {
|
||||
const withoutCookies = isCookiesTrackingDisabled();
|
||||
|
||||
if (withoutCookies) {
|
||||
return generateRandomId();
|
||||
}
|
||||
|
||||
const existingTrackingCookie = cookies.get(VISITORID_COOKIE);
|
||||
|
||||
if (existingTrackingCookie) {
|
||||
// If the cookie already exists, we'll just use that. Avoids a server request.
|
||||
return existingTrackingCookie;
|
||||
} else {
|
||||
// No tracking deviceId set, we'll need to consolidate with the server.
|
||||
const proposed = generateRandomId();
|
||||
|
||||
const url = new URL(process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? `https://app.gitbook.com`);
|
||||
url.pathname = '/__session';
|
||||
url.searchParams.set('proposed', proposed);
|
||||
|
||||
try {
|
||||
const resp = await fetch(url, {
|
||||
method: 'GET', // Use GET to play nicely with SameSite cookies.
|
||||
credentials: 'include', // Make sure to send/receive cookies.
|
||||
cache: 'no-cache',
|
||||
mode: 'cors', // Need to use cors as we are on a different domain.
|
||||
});
|
||||
|
||||
const { deviceId } = (await resp.json()) as { deviceId: string };
|
||||
return deviceId;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch visitor session ID', error);
|
||||
return proposed;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,14 @@ import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
|
||||
import { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { shouldTrackPageViews } from '@/lib/tracking';
|
||||
|
||||
import { PageBodyBlankslate } from './PageBodyBlankslate';
|
||||
import { PageCover } from './PageCover';
|
||||
import { PageFooterNavigation } from './PageFooterNavigation';
|
||||
import { PageHeader } from './PageHeader';
|
||||
import { PreservePageLayout } from './PreservePageLayout';
|
||||
import { TrackPageView } from './TrackPageView';
|
||||
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
|
||||
import { TrackPageViewEvent } from '../Insights';
|
||||
import { PageFeedbackForm } from '../PageFeedback';
|
||||
import { DateRelative } from '../primitives';
|
||||
|
||||
@@ -39,7 +38,6 @@ export function PageBody(props: {
|
||||
}) {
|
||||
const {
|
||||
space,
|
||||
pointer,
|
||||
contentTarget,
|
||||
customization,
|
||||
context,
|
||||
@@ -146,14 +144,8 @@ export function PageBody(props: {
|
||||
) : null}
|
||||
</div>
|
||||
</main>
|
||||
{shouldTrackPageViews() ? (
|
||||
<TrackPageView
|
||||
sitePointer={pointer}
|
||||
spaceId={space.id}
|
||||
pageId={page.id}
|
||||
apiHost={api().client.endpoint}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<TrackPageViewEvent pageId={page.id} revisionId={space.revision} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,6 +61,10 @@ export async function PageBodyBlankslate(props: {
|
||||
leadingIcon={icon}
|
||||
title={child.title}
|
||||
href={resolved.href}
|
||||
insights={{
|
||||
target: child.target,
|
||||
position: 'content',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { pageHref } from '@/lib/links';
|
||||
import { resolvePrevNextPages } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { Link } from '../primitives';
|
||||
import { Link, LinkInsightsProps } from '../primitives';
|
||||
|
||||
/**
|
||||
* Show cards to go to previous/next pages at the bottom.
|
||||
@@ -47,6 +47,13 @@ export function PageFooterNavigation(props: {
|
||||
label={t(language, 'previous_page')}
|
||||
title={previous.title}
|
||||
href={pageHref(pages, previous)}
|
||||
insights={{
|
||||
target: {
|
||||
kind: 'page',
|
||||
page: previous.id,
|
||||
},
|
||||
position: 'content',
|
||||
}}
|
||||
reversed
|
||||
/>
|
||||
) : null}
|
||||
@@ -56,24 +63,34 @@ export function PageFooterNavigation(props: {
|
||||
label={t(language, 'next_page')}
|
||||
title={next.title}
|
||||
href={pageHref(pages, next)}
|
||||
insights={{
|
||||
target: {
|
||||
kind: 'page',
|
||||
page: next.id,
|
||||
},
|
||||
position: 'content',
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NavigationCard(props: {
|
||||
icon: IconName;
|
||||
label: React.ReactNode;
|
||||
title: string;
|
||||
href: string;
|
||||
reversed?: boolean;
|
||||
}) {
|
||||
const { icon, label, title, href, reversed } = props;
|
||||
function NavigationCard(
|
||||
props: {
|
||||
icon: IconName;
|
||||
label: React.ReactNode;
|
||||
title: string;
|
||||
href: string;
|
||||
reversed?: boolean;
|
||||
} & LinkInsightsProps,
|
||||
) {
|
||||
const { icon, label, title, href, reversed, insights } = props;
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
insights={insights}
|
||||
className={tcls(
|
||||
'group',
|
||||
'text-sm',
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import type { RequestSiteTrackPageView, RequestSpaceTrackPageView } from '@gitbook/api';
|
||||
import cookies from 'js-cookie';
|
||||
import * as React from 'react';
|
||||
|
||||
import { getVisitorId } from '@/lib/analytics';
|
||||
import { SiteContentPointer } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Track the page view for the current page to integrations.
|
||||
*/
|
||||
export function TrackPageView(props: {
|
||||
apiHost: string;
|
||||
sitePointer: SiteContentPointer;
|
||||
spaceId: string;
|
||||
pageId: string | undefined;
|
||||
}) {
|
||||
const { apiHost, sitePointer, spaceId, pageId } = props;
|
||||
|
||||
React.useEffect(() => {
|
||||
trackPageView({ apiHost, sitePointer, spaceId, pageId });
|
||||
}, [apiHost, spaceId, pageId, sitePointer]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function sendSpaceTrackPageViewRequest(args: {
|
||||
apiHost: string;
|
||||
spaceId: string;
|
||||
body: RequestSpaceTrackPageView;
|
||||
}) {
|
||||
const { apiHost, spaceId, body } = args;
|
||||
const url = new URL(apiHost);
|
||||
url.pathname = `/v1/spaces/${spaceId}/insights/track_view`;
|
||||
|
||||
await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function sendSiteTrackPageViewRequest(args: {
|
||||
apiHost: string;
|
||||
sitePointer: SiteContentPointer;
|
||||
body: RequestSiteTrackPageView;
|
||||
}) {
|
||||
const { apiHost, sitePointer, body } = args;
|
||||
const url = new URL(apiHost);
|
||||
url.pathname = `/v1/orgs/${sitePointer.organizationId}/sites/${sitePointer.siteId}/insights/track_view`;
|
||||
|
||||
await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
let latestPageId: string | undefined | null = null;
|
||||
|
||||
/**
|
||||
* Track the page view for the current page to GitBook.
|
||||
* We don't use the API client to avoid shipping 80kb of JS to the client.
|
||||
* And instead use a simple fetch.
|
||||
*/
|
||||
async function trackPageView(args: {
|
||||
apiHost: string;
|
||||
sitePointer: SiteContentPointer;
|
||||
spaceId: string;
|
||||
pageId: string | undefined;
|
||||
}) {
|
||||
const { apiHost, sitePointer, pageId, spaceId } = args;
|
||||
if (pageId === latestPageId) {
|
||||
// The hook can be called multiple times, we only want to track once.
|
||||
return;
|
||||
}
|
||||
|
||||
latestPageId = pageId;
|
||||
|
||||
const visitorId = await getVisitorId();
|
||||
const sharedTrackedProps = {
|
||||
url: window.location.href,
|
||||
pageId,
|
||||
visitor: {
|
||||
anonymousId: visitorId,
|
||||
userAgent: window.navigator.userAgent,
|
||||
language: window.navigator.language,
|
||||
cookies: cookies.get(),
|
||||
},
|
||||
referrer: document.referrer,
|
||||
};
|
||||
|
||||
try {
|
||||
sitePointer
|
||||
? await sendSiteTrackPageViewRequest({
|
||||
apiHost,
|
||||
sitePointer,
|
||||
body: {
|
||||
...sharedTrackedProps,
|
||||
spaceId,
|
||||
},
|
||||
})
|
||||
: await sendSpaceTrackPageViewRequest({ apiHost, spaceId, body: sharedTrackedProps });
|
||||
} catch (error) {
|
||||
console.error('Failed to track page view', error);
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ import React from 'react';
|
||||
|
||||
import { useLanguage } from '@/intl/client';
|
||||
import { t, tString } from '@/intl/translate';
|
||||
import { getVisitorId } from '@/lib/analytics';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { getVisitorId, useTrackEvent } from '../Insights';
|
||||
import { postPageFeedback } from './server-actions';
|
||||
|
||||
/**
|
||||
@@ -20,12 +20,20 @@ export function PageFeedbackForm(props: {
|
||||
}) {
|
||||
const { orientation = 'vertical', pageId, className } = props;
|
||||
const languages = useLanguage();
|
||||
// const trackEvent = useTrackEvent();
|
||||
const [submitted, setSubmitted] = React.useState(false);
|
||||
|
||||
const onSubmit = async (rating: PageFeedbackRating) => {
|
||||
setSubmitted(true);
|
||||
const visitorId = await getVisitorId();
|
||||
await postPageFeedback({ pageId, visitorId, rating });
|
||||
|
||||
// trackEvent({
|
||||
// type: 'page_post_feedback',
|
||||
// feedback: {
|
||||
// rating,
|
||||
// },
|
||||
// });
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,13 +11,12 @@ import assertNever from 'assert-never';
|
||||
import colorContrast from 'postcss-color-contrast/js';
|
||||
import colors from 'tailwindcss/colors';
|
||||
|
||||
import { fonts, ibmPlexMono } from '@/fonts';
|
||||
import { fontNotoColorEmoji, fonts, ibmPlexMono } from '@/fonts';
|
||||
import { getSpaceLanguage } from '@/intl/server';
|
||||
import { getStaticFileURL } from '@/lib/assets';
|
||||
import { hexToRgb, shadesOfColor } from '@/lib/colors';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { emojiFontClassName } from '../primitives';
|
||||
import { ClientContexts } from './ClientContexts';
|
||||
|
||||
import '@gitbook/icons/style.css';
|
||||
@@ -154,7 +153,7 @@ export async function CustomizationRootLayout(props: {
|
||||
</head>
|
||||
<body
|
||||
className={tcls(
|
||||
emojiFontClassName,
|
||||
fontNotoColorEmoji.className,
|
||||
`${fonts[customization.styling.font].className}`,
|
||||
`${ibmPlexMono.variable}`,
|
||||
'bg-light',
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
/* See packages/gitbook/src/fonts/index.ts */
|
||||
--font-emoji: 'Apple Color Emoji', var(--font-noto-color-emoji);
|
||||
--scrollbar-width: calc(100vw - 100%);
|
||||
|
||||
--dark-base: 20 20 20;
|
||||
@@ -196,26 +198,5 @@ html.dark {
|
||||
/* Emojis */
|
||||
|
||||
[class*='emoji'] {
|
||||
font-family: var(--font-emojis-sbix);
|
||||
}
|
||||
|
||||
/* Safari Only CSS here */
|
||||
_::-webkit-full-page-media,
|
||||
_:future,
|
||||
:root [class*='emoji'] {
|
||||
font-family: var(--font-emojis-sbix);
|
||||
}
|
||||
|
||||
/* Chrome Only CSS here */
|
||||
@media screen and (-webkit-min-device-pixel-ratio: 0) {
|
||||
.emoji {
|
||||
font-family: var(--font-emojis-colrv1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Firefox Only CSS here */
|
||||
@-moz-document url-prefix() {
|
||||
.emoji {
|
||||
font-family: var(--font-emojis-colrv1);
|
||||
}
|
||||
font-family: var(--font-emoji);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ export function HighlightQuery(props: {
|
||||
'py-0.5',
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
'group-[.is-active]:bg-primary-200',
|
||||
'group-[.is-active]:text-contrast-primary-200',
|
||||
'dark:group-[.is-active]:bg-primary-700',
|
||||
'dark:group-[.is-active]:text-contrast-primary-700',
|
||||
],
|
||||
} = props;
|
||||
const matches = matchString(text, query);
|
||||
|
||||
@@ -14,6 +14,7 @@ import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
|
||||
import { useSearch, useSearchLink } from './useSearch';
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { Link } from '../primitives';
|
||||
|
||||
type SearchState =
|
||||
@@ -44,6 +45,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
|
||||
const { pointer, query } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
// const trackEvent = useTrackEvent();
|
||||
const [, setSearchState] = useSearch();
|
||||
const [state, setState] = useRecoilState(searchAskState);
|
||||
const { organizationId, siteId, siteSpaceId } = pointer;
|
||||
@@ -51,42 +53,34 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
setState({
|
||||
type: 'loading',
|
||||
});
|
||||
setState({ type: 'loading' });
|
||||
|
||||
(async () => {
|
||||
const stream = iterateStreamResponse(
|
||||
streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query),
|
||||
);
|
||||
// trackEvent({
|
||||
// type: 'ask_question',
|
||||
// query,
|
||||
// });
|
||||
|
||||
setSearchState((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
ask: true,
|
||||
query,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
const response = streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query);
|
||||
const stream = iterateStreamResponse(response);
|
||||
|
||||
// When we pass in "ask" mode, the query could still be updated by the client
|
||||
// we ensure that the query is up-to-date before starting the stream.
|
||||
setSearchState((prev) => (prev ? { ...prev, query, ask: true } : null));
|
||||
|
||||
for await (const chunk of stream) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setState({
|
||||
type: 'answer',
|
||||
answer: chunk,
|
||||
});
|
||||
|
||||
setState({ type: 'answer', answer: chunk });
|
||||
}
|
||||
})().catch((error) => {
|
||||
})().catch(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState({
|
||||
type: 'error',
|
||||
});
|
||||
setState({ type: 'error' });
|
||||
});
|
||||
|
||||
return () => {
|
||||
@@ -96,7 +90,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
|
||||
cancelled = true;
|
||||
}
|
||||
};
|
||||
}, [organizationId, siteId, siteSpaceId, query]);
|
||||
}, [organizationId, siteId, siteSpaceId, query, setState, setSearchState]);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useLanguage, tString } from '@/intl/client';
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
import { useSearch } from './useSearch';
|
||||
import { useTrackEvent } from '../Insights';
|
||||
|
||||
/**
|
||||
* Button to open the search modal.
|
||||
@@ -17,6 +18,7 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
||||
|
||||
const language = useLanguage();
|
||||
const [, setSearchState] = useSearch();
|
||||
// const trackEvent = useTrackEvent();
|
||||
|
||||
const onClick = () => {
|
||||
setSearchState({
|
||||
@@ -24,6 +26,10 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
||||
global: false,
|
||||
query: '',
|
||||
});
|
||||
|
||||
// trackEvent({
|
||||
// type: 'search_open',
|
||||
// });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -52,8 +58,8 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
||||
'shadow-dark/4',
|
||||
'dark:shadow-none',
|
||||
|
||||
'text-dark/6',
|
||||
'dark:text-light/6',
|
||||
'text-dark/7',
|
||||
'dark:text-light-4/7',
|
||||
|
||||
'rounded-lg',
|
||||
'straight-corners:rounded-sm',
|
||||
@@ -128,11 +134,11 @@ const Shortcut = () => {
|
||||
'md:inline',
|
||||
'justify-end',
|
||||
'text-xs',
|
||||
'text-dark/6',
|
||||
'text-dark/7',
|
||||
'contrast-more:text-dark',
|
||||
'dark:text-light/6',
|
||||
'whitespace-nowrap',
|
||||
'dark:text-light-4/7',
|
||||
'contrast-more:dark:text-light',
|
||||
'whitespace-nowrap',
|
||||
`[font-feature-settings:"calt",_"case"]`,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { tcls } from '@/lib/tailwind';
|
||||
import { SearchAskAnswer, searchAskState } from './SearchAskAnswer';
|
||||
import { SearchResults, SearchResultsRef } from './SearchResults';
|
||||
import { SearchScopeToggle } from './SearchScopeToggle';
|
||||
import { SearchState, useSearch } from './useSearch';
|
||||
import { SearchState, UpdateSearchState, useSearch } from './useSearch';
|
||||
import { LoadingPane } from '../primitives/LoadingPane';
|
||||
|
||||
interface SearchModalProps {
|
||||
@@ -55,14 +55,6 @@ export function SearchModal(props: SearchModalProps) {
|
||||
};
|
||||
}, [isSearchOpened]);
|
||||
|
||||
// if (state === null) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
const onChangeQuery = (newQuery: SearchState) => {
|
||||
setSearchState(newQuery);
|
||||
};
|
||||
|
||||
const onClose = async (to?: string) => {
|
||||
await setSearchState(null);
|
||||
if (to) {
|
||||
@@ -133,7 +125,7 @@ export function SearchModal(props: SearchModalProps) {
|
||||
<SearchModalBody
|
||||
{...props}
|
||||
state={state}
|
||||
onChangeQuery={onChangeQuery}
|
||||
setSearchState={setSearchState}
|
||||
onClose={onClose}
|
||||
/>
|
||||
</div>
|
||||
@@ -146,7 +138,7 @@ export function SearchModal(props: SearchModalProps) {
|
||||
function SearchModalBody(
|
||||
props: SearchModalProps & {
|
||||
state: SearchState;
|
||||
onChangeQuery: (newQuery: SearchState) => void;
|
||||
setSearchState: UpdateSearchState;
|
||||
onClose: (to?: string) => void;
|
||||
},
|
||||
) {
|
||||
@@ -158,7 +150,7 @@ function SearchModalBody(
|
||||
withAsk,
|
||||
isMultiVariants,
|
||||
state,
|
||||
onChangeQuery,
|
||||
setSearchState,
|
||||
onClose,
|
||||
} = props;
|
||||
|
||||
@@ -170,10 +162,21 @@ function SearchModalBody(
|
||||
inputRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === 'Escape') {
|
||||
onClose();
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
if (event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
resultsRef.current?.moveUp();
|
||||
} else if (event.key === 'ArrowDown') {
|
||||
@@ -186,13 +189,17 @@ function SearchModalBody(
|
||||
};
|
||||
|
||||
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
onChangeQuery({
|
||||
setSearchState({
|
||||
ask: false, // When typing, we go back to the default search mode
|
||||
query: event.target.value,
|
||||
global: state.global,
|
||||
});
|
||||
};
|
||||
|
||||
const onSwitchToAsk = () => {
|
||||
setSearchState((state) => (state ? { ...state, ask: true } : null));
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
transition={{
|
||||
@@ -304,13 +311,7 @@ function SearchModalBody(
|
||||
global={isMultiVariants && state.global}
|
||||
query={state.query}
|
||||
withAsk={withAsk}
|
||||
onSwitchToAsk={() => {
|
||||
onChangeQuery({
|
||||
ask: true,
|
||||
query: state.query,
|
||||
global: state.global,
|
||||
});
|
||||
}}
|
||||
onSwitchToAsk={onSwitchToAsk}
|
||||
></SearchResults>
|
||||
) : null}
|
||||
{state.query && state.ask && withAsk ? (
|
||||
|
||||
@@ -23,26 +23,38 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
href={item.href}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'gap-4',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'px-4',
|
||||
'sm:px-12',
|
||||
'py-4',
|
||||
'sm:py-6',
|
||||
'p-4',
|
||||
'border-t',
|
||||
'first:border-t-0',
|
||||
'border-dark/2',
|
||||
'dark:border-light/2',
|
||||
'hover:bg-dark-4/2',
|
||||
'dark:border-light/1',
|
||||
'first:border-none',
|
||||
'text-base',
|
||||
'text-dark',
|
||||
'font-medium',
|
||||
'first:mt-0',
|
||||
'dark:text-light',
|
||||
'dark:hover:bg-light-4/2',
|
||||
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
|
||||
'hover:bg-dark/1',
|
||||
'dark:hover:bg-light/1',
|
||||
'group',
|
||||
active
|
||||
? [
|
||||
'is-active',
|
||||
'bg-primary-50',
|
||||
'text-contrast-primary-50',
|
||||
'dark:bg-primary-800',
|
||||
'dark:text-contrast-primary-800',
|
||||
'hover:bg-primary-100/8',
|
||||
'dark:hover:bg-primary-700/7',
|
||||
]
|
||||
: null,
|
||||
)}
|
||||
>
|
||||
<div className="size-4">
|
||||
<Icon
|
||||
icon="file-lines"
|
||||
className={tcls('size-4', active ? 'text-primary' : 'opacity-5')}
|
||||
/>
|
||||
</div>
|
||||
<div className={tcls('flex', 'flex-col', 'w-full')}>
|
||||
{item.spaceTitle ? (
|
||||
<div
|
||||
@@ -60,10 +72,19 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
) : null}
|
||||
<HighlightQuery query={query} text={item.title} />
|
||||
</div>
|
||||
<Icon
|
||||
icon="chevron-right"
|
||||
className={tcls('size-4', 'text-dark', 'dark:text-light', 'opacity-6')}
|
||||
/>
|
||||
<div
|
||||
className={tcls(
|
||||
'p-2',
|
||||
'rounded',
|
||||
'straight-corners:rounded-none',
|
||||
active ? ['bg-primary', 'text-contrast-primary'] : ['opacity-6'],
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon={active ? 'arrow-turn-down-left' : 'chevron-right'}
|
||||
className={tcls('size-4')}
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -26,16 +26,21 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
|
||||
onClick={onClick}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'px-4',
|
||||
'py-2',
|
||||
'hover:bg-dark-4/2',
|
||||
'text-dark/7',
|
||||
recommended ? ['py-2', 'text-dark/7', 'dark:text-light/8'] : 'py-4',
|
||||
'hover:bg-dark/1',
|
||||
'dark:hover:bg-light/1',
|
||||
'first:mt-0',
|
||||
'last:pb-3',
|
||||
'dark:text-light/8',
|
||||
'dark:hover:bg-light-4/2',
|
||||
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
|
||||
active && [
|
||||
'is-active',
|
||||
'bg-primary-50',
|
||||
'text-contrast-primary-50',
|
||||
'dark:bg-primary-800',
|
||||
'dark:text-contrast-primary-800',
|
||||
'hover:bg-primary-100/8',
|
||||
'dark:hover:bg-primary-700/7',
|
||||
],
|
||||
)}
|
||||
{...getLinkProp({
|
||||
ask: true,
|
||||
@@ -43,18 +48,41 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
|
||||
})}
|
||||
>
|
||||
<Icon
|
||||
icon="magnifying-glass"
|
||||
icon={recommended ? 'search' : 'sparkles'}
|
||||
className={tcls(
|
||||
'size-4',
|
||||
'shrink-0',
|
||||
'mt-0.5',
|
||||
'mt-1.5',
|
||||
'mr-4',
|
||||
'mt-1',
|
||||
'text-dark/5',
|
||||
'dark:text-light/5',
|
||||
active ? ['text-primary'] : ['text-dark/5', 'dark:text-light/5'],
|
||||
)}
|
||||
/>
|
||||
{recommended ? question : t(language, 'search_ask', [question])}
|
||||
<div className="w-full">
|
||||
{recommended ? (
|
||||
question
|
||||
) : (
|
||||
<>
|
||||
<div className="font-medium">{t(language, 'search_ask', [question])}</div>
|
||||
<div className={tcls('text-sm', 'text-dark/8', 'dark:text-light/8')}>
|
||||
{t(language, 'search_ask_description')}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={tcls(
|
||||
'p-2',
|
||||
'rounded',
|
||||
'self-center',
|
||||
'straight-corners:rounded-none',
|
||||
active ? ['bg-primary', 'text-contrast-primary'] : ['opacity-6'],
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon={active ? 'arrow-turn-down-left' : 'chevron-right'}
|
||||
className={tcls('size-4')}
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,6 @@ import { t, useLanguage } from '@/intl/client';
|
||||
import { SiteContentPointer } from '@/lib/api';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { isQuestion } from './isQuestion';
|
||||
import { SearchPageResultItem } from './SearchPageResultItem';
|
||||
import { SearchQuestionResultItem } from './SearchQuestionResultItem';
|
||||
import { SearchSectionResultItem } from './SearchSectionResultItem';
|
||||
@@ -15,6 +14,7 @@ import {
|
||||
searchSiteSpaceContent,
|
||||
searchAllSiteContent,
|
||||
} from './server-actions';
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { Loading } from '../primitives';
|
||||
|
||||
export interface SearchResultsRef {
|
||||
@@ -50,6 +50,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
const { children, query, pointer, spaceId, revisionId, global, withAsk, onSwitchToAsk } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
// const trackEvent = useTrackEvent();
|
||||
const debounceTimeout = React.useRef<Timer | null>(null);
|
||||
const [results, setResults] = React.useState<ResultType[] | null>(null);
|
||||
const [cursor, setCursor] = React.useState<number | null>(null);
|
||||
@@ -92,13 +93,16 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
}
|
||||
|
||||
debounceTimeout.current = setTimeout(async () => {
|
||||
setCursor(null);
|
||||
|
||||
const fetchedResults = await (global
|
||||
? searchAllSiteContent(query, pointer)
|
||||
: searchSiteSpaceContent(query, pointer, revisionId));
|
||||
|
||||
setResults(withAsk ? withQuestionResult(fetchedResults, query) : fetchedResults);
|
||||
|
||||
// trackEvent({
|
||||
// type: 'search_type_query',
|
||||
// query,
|
||||
// });
|
||||
}, 350);
|
||||
|
||||
return () => {
|
||||
@@ -110,6 +114,16 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
}
|
||||
}, [query, global, pointer, spaceId, revisionId, withAsk]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!query) {
|
||||
// Reset the cursor when there's no query
|
||||
setCursor(null);
|
||||
} else if (results && results.length > 0) {
|
||||
// Auto-focus the first result
|
||||
setCursor(0);
|
||||
}
|
||||
}, [results, query]);
|
||||
|
||||
// Scroll to the active result.
|
||||
React.useEffect(() => {
|
||||
if (cursor === null || !refs.current[cursor]) {
|
||||
@@ -256,10 +270,13 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Add a "Ask <question>" item at the top of the results list.
|
||||
*/
|
||||
function withQuestionResult(results: null | ResultType[], query: string): null | ResultType[] {
|
||||
const without = results ? results.filter((result) => result.type !== 'question') : null;
|
||||
|
||||
if (!isQuestion(query)) {
|
||||
if (query.length === 0) {
|
||||
return without;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -21,27 +22,39 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
|
||||
ref={ref}
|
||||
href={item.href}
|
||||
className={tcls(
|
||||
'search-section-result-item',
|
||||
'[&:has(+:not(&))]:mb-6',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'mb-2',
|
||||
'px-4',
|
||||
'sm:px-12',
|
||||
'hover:bg-dark-4/2',
|
||||
'dark:hover:bg-light-4/2',
|
||||
'items-center',
|
||||
'pl-6',
|
||||
'sm:pl-12',
|
||||
'pr-4',
|
||||
'text-dark/8',
|
||||
'dark:text-light/8',
|
||||
'hover:bg-dark/1',
|
||||
'dark:hover:bg-light/1',
|
||||
'font-normal',
|
||||
'transition-colors',
|
||||
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
|
||||
'py-2',
|
||||
'group',
|
||||
active && [
|
||||
'is-active',
|
||||
'bg-primary-50',
|
||||
'text-contrast-primary-50',
|
||||
'dark:bg-primary-800',
|
||||
'dark:text-contrast-primary-800',
|
||||
'hover:bg-primary-100/8',
|
||||
'dark:hover:bg-primary-700/7',
|
||||
],
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={tcls(
|
||||
'border-l-2',
|
||||
'px-4',
|
||||
'py-2',
|
||||
'py-1',
|
||||
'flex',
|
||||
'flex-1',
|
||||
'overflow-hidden',
|
||||
'flex-col',
|
||||
'border-dark/2',
|
||||
'dark:border-light/2',
|
||||
)}
|
||||
@@ -57,6 +70,20 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={tcls(
|
||||
'p-2',
|
||||
'rounded',
|
||||
'straight-corners:rounded-none',
|
||||
'bg-primary',
|
||||
'text-contrast-primary',
|
||||
'hidden',
|
||||
'sm:block',
|
||||
active ? ['opacity-11', 'block'] : ['opacity-0'],
|
||||
)}
|
||||
>
|
||||
<Icon icon="arrow-turn-down-left" className={tcls('size-4')} />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -16,18 +16,17 @@ const keyMap = {
|
||||
global: parseAsBoolean,
|
||||
};
|
||||
|
||||
const options: UseQueryStatesOptions = {
|
||||
history: 'replace',
|
||||
};
|
||||
export type UpdateSearchState = (
|
||||
update: React.SetStateAction<SearchState | null>,
|
||||
) => Promise<URLSearchParams>;
|
||||
|
||||
/**
|
||||
* Hook to access the current search query and update it.
|
||||
*/
|
||||
export function useSearch(): [
|
||||
SearchState | null,
|
||||
(update: React.SetStateAction<SearchState | null>) => Promise<URLSearchParams>,
|
||||
] {
|
||||
const [rawState, setRawState] = useQueryStates(keyMap, options);
|
||||
export function useSearch(): [SearchState | null, UpdateSearchState] {
|
||||
const [rawState, setRawState] = useQueryStates(keyMap, {
|
||||
history: 'replace',
|
||||
});
|
||||
|
||||
const state = React.useMemo<SearchState | null>(() => {
|
||||
if (rawState === null || rawState.q === null) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user