mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-15 23:25:16 +00:00
Compare commits
90 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 | |||
| 8d039d1348 | |||
| 87eea73081 | |||
| 67a6fb4c87 | |||
| 23584c9862 | |||
| 2f767125c4 | |||
| c73e07d42d | |||
| 6b5d7e6057 | |||
| 076dc48e89 | |||
| bb208ab36a | |||
| 60e35001b6 | |||
| 29a0d7ea02 | |||
| 1f2b7f7acf | |||
| 39e5cb63ef | |||
| 5b5928fb8d | |||
| 08068743a5 | |||
| 35eae1adcf | |||
| e85d357abd | |||
| 31396d8109 | |||
| 664debc0bc | |||
| 56c31c76b3 | |||
| 2d1a71f3d1 | |||
| c67cd73058 | |||
| 2572cb4352 | |||
| c9f6c7ccac | |||
| b6520b0dbc | |||
| 9fe8142117 | |||
| 57cdd25b5f | |||
| 1005ee5d52 | |||
| d9bb9f9a07 | |||
| 75a6fabe61 | |||
| 75e29b69cc | |||
| ffd3937538 | |||
| 575587e4c5 | |||
| 2ce59d7c92 | |||
| 3b3d6e2a73 | |||
| f2a467fdbf | |||
| 867481c66d | |||
| fc8065b7a8 | |||
| 28f1ed9205 | |||
| 568266bc9a | |||
| 7739f341b8 | |||
| 2b501f191c | |||
| aa2ed0fda1 | |||
| 51cba074d7 | |||
| 2c945c663c | |||
| d9a18ecabb | |||
| eab7931afb | |||
| 99b6c92377 | |||
| 4d56f1163b | |||
| 07cf835551 | |||
| 061c0c1a90 | |||
| 1ed18c05ef | |||
| ca134c8a60 | |||
| 7ba67fd852 | |||
| 7675c2c411 | |||
| 7c71363af8 | |||
| d48926eb2a | |||
| d843e5e06f | |||
| a2e564738e | |||
| 54a797a0b1 | |||
| a78c1ecb4d | |||
| 4771c78001 | |||
| b7a5106f36 | |||
| 4bcbdc50ff | |||
| 5d72b35c7f | |||
| ff50ac215c |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
"@babel/preset-react"
|
||||
],
|
||||
"ignore": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"public"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
1.1.40
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Adapt code to pull token from customer backend generated custom cookies
|
||||
@@ -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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Improve contrast of search box placeholder
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track events for site insights using the new dedicated API.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Improve colour contrast of list item decoration
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
'@gitbook/react-contentkit': minor
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Send redirectOnError param to getPublishedContent when token is pulled from cookie
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track clicks on links (header, footer, content) for site insights.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix emojis display
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Prevent codemirror from loading multiple versions in scalar
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix variant selector contrast for non-default themes
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@gitbook/react-openapi': patch
|
||||
---
|
||||
|
||||
Updated scalar depdenency
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix bullet list display on full size blocks
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Track an event into site insights when visitor is opening the Scalar API client.
|
||||
@@ -12,7 +12,7 @@ runs:
|
||||
|
||||
# Cache browser binaries, cache key is based on Playwright version and OS
|
||||
- name: 🧰 Cache Playwright browser binaries
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: '~/.cache/ms-playwright'
|
||||
|
||||
@@ -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'
|
||||
+26
-52
@@ -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
|
||||
@@ -18,28 +18,16 @@ jobs:
|
||||
checks: write
|
||||
statuses: write
|
||||
outputs:
|
||||
deployment_url: ${{ steps.deploy.outputs.url }}
|
||||
deployment_url: ${{ steps.deploy.outputs.deployment-url }}
|
||||
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:
|
||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||
- name: Cache Next.js build
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
${{ github.workspace }}/.next/cache
|
||||
# Generate a new cache whenever packages or source files change.
|
||||
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
# If source files changed but packages didn't, rebuild from a prior cache.
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-
|
||||
- name: Sets env vars for production
|
||||
run: |
|
||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
||||
@@ -58,7 +46,7 @@ jobs:
|
||||
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
|
||||
- id: deploy
|
||||
name: Deploy to Cloudflare
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
uses: cloudflare/wrangler-action@v3.11.0
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
@@ -67,7 +55,7 @@ jobs:
|
||||
command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
|
||||
- name: Outputs
|
||||
run: |
|
||||
echo "URL: ${{ steps.deploy.outputs.url }}"
|
||||
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
|
||||
echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}"
|
||||
- name: Archive build output
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -77,12 +65,12 @@ jobs:
|
||||
# Until https://github.com/cloudflare/wrangler-action/issues/301 is done
|
||||
- name: Update Deployment Status to Success
|
||||
env:
|
||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }}
|
||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
|
||||
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.deployment-url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
|
||||
https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.sha }}
|
||||
|
||||
- name: Find GitHub Comment
|
||||
@@ -102,8 +90,8 @@ jobs:
|
||||
issue-number: ${{ github.event.pull_request.number }}
|
||||
body: |
|
||||
**GitBook Preview**
|
||||
Latest commit: [${{ steps.deploy.outputs.url }}](${{ steps.deploy.outputs.url }})
|
||||
PR: [${{ steps.deploy.outputs.alias }}](${{ steps.deploy.outputs.alias }})
|
||||
Latest commit: [${{ steps.deploy.outputs.deployment-url }}](${{ steps.deploy.outputs.deployment-url }})
|
||||
PR: [${{ steps.deploy.outputs.deployment-alias-url }}](${{ steps.deploy.outputs.deployment-alias-url }})
|
||||
edit-mode: replace
|
||||
visual-testing:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -112,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
|
||||
@@ -138,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:
|
||||
@@ -157,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:
|
||||
@@ -172,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:
|
||||
@@ -187,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:
|
||||
@@ -201,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
|
||||
@@ -220,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
-32
@@ -1,34 +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"
|
||||
},
|
||||
"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"
|
||||
|
||||
@@ -11,8 +11,7 @@ migrations = [
|
||||
]
|
||||
|
||||
[observability]
|
||||
enabled = true
|
||||
head_sampling_rate = 0.01
|
||||
enabled = false
|
||||
|
||||
[env.preview]
|
||||
name = "gitbook-open-cache-preview"
|
||||
@@ -25,4 +24,4 @@ migrations = [
|
||||
|
||||
[env.preview.observability]
|
||||
enabled = true
|
||||
head_sampling_rate = 1
|
||||
head_sampling_rate = 0.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
|
||||
|
||||
@@ -1,20 +1,34 @@
|
||||
import { argosScreenshot } from '@argos-ci/playwright';
|
||||
import {
|
||||
CustomizationBackground,
|
||||
CustomizationCorners,
|
||||
CustomizationFont,
|
||||
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
|
||||
@@ -34,6 +48,18 @@ const allLocales: CustomizationLocale[] = [
|
||||
CustomizationLocale.Zh,
|
||||
];
|
||||
|
||||
const allThemeModes: CustomizationThemeMode[] = [
|
||||
CustomizationThemeMode.Light,
|
||||
CustomizationThemeMode.Dark,
|
||||
];
|
||||
|
||||
const allThemePresets: CustomizationHeaderPreset[] = [
|
||||
CustomizationHeaderPreset.Default,
|
||||
CustomizationHeaderPreset.Bold,
|
||||
CustomizationHeaderPreset.Contrast,
|
||||
CustomizationHeaderPreset.Custom,
|
||||
];
|
||||
|
||||
async function waitForCookiesDialog(page: Page) {
|
||||
const dialog = page.getByRole('dialog', { name: 'Cookies' });
|
||||
const accept = dialog.getByRole('button', { name: 'Accept' });
|
||||
@@ -95,7 +121,9 @@ const testCases: TestsCase[] = [
|
||||
name: 'Variants dropdown',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
|
||||
const spaceDrowpdown = page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.waitFor();
|
||||
},
|
||||
},
|
||||
@@ -111,7 +139,9 @@ const testCases: TestsCase[] = [
|
||||
name: 'Customized variant titles are displayed',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
|
||||
const spaceDrowpdown = page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
const variantSelectionDropdown = page.locator(
|
||||
@@ -143,9 +173,9 @@ const testCases: TestsCase[] = [
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -166,9 +196,9 @@ const testCases: TestsCase[] = [
|
||||
url: 'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -201,9 +231,9 @@ const testCases: TestsCase[] = [
|
||||
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -435,30 +465,38 @@ const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'Customization',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
tests: [
|
||||
tests: allThemeModes.flatMap((theme) => [
|
||||
{
|
||||
name: 'Without header',
|
||||
name: `Without header - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.None,
|
||||
links: [],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With duotone icons',
|
||||
name: `With duotone icons - Theme ${theme}`,
|
||||
url:
|
||||
'page-options/page-with-icon' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
icons: CustomizationIconsStyle.Duotone,
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With header buttons',
|
||||
name: `With header buttons - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
@@ -475,10 +513,101 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
{
|
||||
name: `Without tint - Default preset - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
...allThemePresets.flatMap((preset) => ({
|
||||
name: `With tint - Preset ${preset} - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
header: {
|
||||
preset,
|
||||
...(preset === CustomizationHeaderPreset.Custom
|
||||
? {
|
||||
backgroundColor: { light: '#C62C68', dark: '#EF96B8' },
|
||||
linkColor: { light: '#4DDE98', dark: '#0C693D' },
|
||||
}
|
||||
: {}),
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
})),
|
||||
{
|
||||
name: `With tint - Legacy background match - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
styling: {
|
||||
background: CustomizationBackground.Match,
|
||||
},
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
]),
|
||||
},
|
||||
{
|
||||
name: 'Ads',
|
||||
@@ -491,6 +620,55 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Shared space navigation (first site)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Navigation to shared space',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const sharedSpaceLink = page.locator('a.underline');
|
||||
await sharedSpaceLink.click();
|
||||
expect(page.locator('h1')).toHaveText('shared');
|
||||
const url = page.url();
|
||||
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
|
||||
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Shared space navigation (second site)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Navigation to shared space',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const sharedSpaceLink = page.locator('a.underline');
|
||||
await sharedSpaceLink.click();
|
||||
expect(page.locator('h1')).toHaveText('shared');
|
||||
const url = page.url();
|
||||
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
|
||||
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Site Redirects',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Redirect to SSO page',
|
||||
url: 'a/redirect/to/sso',
|
||||
run: async (page) => {
|
||||
await expect(page.locator('h1')).toHaveText('SSO');
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Share links',
|
||||
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
|
||||
@@ -698,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/',
|
||||
@@ -765,15 +997,339 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Adaptive Content - VA',
|
||||
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'isAlphaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
await expect(betaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isBetaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
await expect(alphaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isAlphaUser & isBetaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
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/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Default table',
|
||||
url: 'blocks/tables',
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Table with straight corners',
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
corners: CustomizationCorners.Straight,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Table with primary color',
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
// Test dark mode for each variant
|
||||
...allThemeModes.flatMap((theme) => [
|
||||
{
|
||||
name: `Table in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: `Table with straight corners in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
corners: CustomizationCorners.Straight,
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: `Table with primary color in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
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);
|
||||
@@ -799,7 +1355,66 @@ for (const testCase of testCases) {
|
||||
* Create a URL with customization settings.
|
||||
*/
|
||||
function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): string {
|
||||
const encoded = rison.encode_object(partial);
|
||||
/**
|
||||
* Default customization settings.
|
||||
*
|
||||
* The customization object passed to the URL should be a valid API settings object. Hence we extend the test with necessary defaults.
|
||||
*/
|
||||
const DEFAULT_CUSTOMIZATION: SiteCustomizationSettings = {
|
||||
styling: {
|
||||
primaryColor: { light: '#346DDB', dark: '#346DDB' },
|
||||
corners: CustomizationCorners.Rounded,
|
||||
font: CustomizationFont.Inter,
|
||||
background: CustomizationBackground.Plain,
|
||||
icons: CustomizationIconsStyle.Regular,
|
||||
sidebar: {
|
||||
background: CustomizationSidebarBackgroundStyle.Default,
|
||||
list: CustomizationSidebarListStyle.Default,
|
||||
},
|
||||
},
|
||||
internationalization: {
|
||||
locale: CustomizationLocale.En,
|
||||
},
|
||||
favicon: {},
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [],
|
||||
},
|
||||
footer: {
|
||||
groups: [],
|
||||
},
|
||||
themes: {
|
||||
default: CustomizationThemeMode.Light,
|
||||
toggeable: true,
|
||||
},
|
||||
pdf: {
|
||||
enabled: true,
|
||||
},
|
||||
feedback: {
|
||||
enabled: false,
|
||||
},
|
||||
aiSearch: {
|
||||
enabled: true,
|
||||
},
|
||||
advancedCustomization: {
|
||||
enabled: true,
|
||||
},
|
||||
git: {
|
||||
showEditLink: false,
|
||||
},
|
||||
pagination: {
|
||||
enabled: true,
|
||||
},
|
||||
trademark: {
|
||||
enabled: true,
|
||||
},
|
||||
privacyPolicy: {
|
||||
url: 'https://www.gitbook.com/privacy',
|
||||
},
|
||||
socialPreview: {},
|
||||
};
|
||||
|
||||
const encoded = rison.encode_object(deepMerge(DEFAULT_CUSTOMIZATION, partial));
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('customization', encoded);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "env-cmd --silent -f ../../.env.local next dev",
|
||||
"build": "next build",
|
||||
"build:cloudflare": "next-on-pages",
|
||||
"build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -16,7 +16,7 @@
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gitbook/api": "^0.73.0",
|
||||
"@gitbook/api": "^0.85.0",
|
||||
"@gitbook/cache-do": "workspace:*",
|
||||
"@gitbook/emoji-codepoints": "workspace:*",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
@@ -43,14 +43,14 @@
|
||||
"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",
|
||||
"parse-cache-control": "^1.0.1",
|
||||
"postcss-color-contrast": "^1.1.0",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1",
|
||||
"react-hotkeys-hook": "^4.4.1",
|
||||
"recoil": "^0.7.7",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
@@ -60,17 +60,18 @@
|
||||
"remark-rehype": "^11.1.0",
|
||||
"rison": "^0.1.1",
|
||||
"server-only": "^0.0.1",
|
||||
"shiki": "^1.22.0",
|
||||
"shiki": "^1.23.1",
|
||||
"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",
|
||||
"@playwright/test": "^1.42.1",
|
||||
"@cloudflare/next-on-pages": "^1.13.5",
|
||||
"@cloudflare/workers-types": "^4.20240725.0",
|
||||
"@playwright/test": "^1.42.1",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
@@ -78,10 +79,12 @@
|
||||
"@types/object-hash": "^3.0.6",
|
||||
"@types/parse-cache-control": "^1.0.4",
|
||||
"@types/psi": "^4.1.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@types/react": "18.3.13",
|
||||
"@types/react-dom": "18.3.1",
|
||||
"@types/rison": "^0.0.9",
|
||||
"autoprefixer": "^10",
|
||||
"deepmerge": "^4.3.1",
|
||||
"env-cmd": "^10.1.0",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "^14.2.5",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
@@ -89,8 +92,7 @@
|
||||
"postcss": "^8",
|
||||
"psi": "^4.1.0",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"typescript": "^5.5.3",
|
||||
"env-cmd": "^10.1.0",
|
||||
"ts-essentials": "^10.0.1"
|
||||
"ts-essentials": "^10.0.1",
|
||||
"typescript": "^5.5.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
verifyImageSignature,
|
||||
resizeImage,
|
||||
CloudflareImageOptions,
|
||||
imagesResizingSignVersion,
|
||||
checkIsSizableImageURL,
|
||||
} from '@/lib/images';
|
||||
import { parseImageAPIURL } from '@/lib/urls';
|
||||
@@ -18,28 +19,29 @@ export const runtime = 'edge';
|
||||
export async function GET(request: NextRequest) {
|
||||
let urlParam = request.nextUrl.searchParams.get('url');
|
||||
const signature = request.nextUrl.searchParams.get('sign');
|
||||
// The current signature algorithm sets version as 1, but we need to support the older version as well
|
||||
// for previously generated content. In this case, we default to version 0.
|
||||
const signatureVersion = (request.nextUrl.searchParams.get('sv') as '1') || '0';
|
||||
|
||||
// The current signature algorithm sets version as 2, but we need to support the older version as well
|
||||
const signatureVersion = request.nextUrl.searchParams.get('sv') as string | undefined;
|
||||
if (!urlParam || !signature) {
|
||||
return new Response('Missing url/sign parameters', { status: 400 });
|
||||
}
|
||||
|
||||
const url = parseImageAPIURL(urlParam);
|
||||
|
||||
// Prevent infinite loops
|
||||
if (url.includes('/~gitbook/image')) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// Check again if the image can be sized, even though we checked when rendering the Image component
|
||||
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
|
||||
// Also prevent infinite redirects.
|
||||
if (!checkIsSizableImageURL(url)) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// For older signatures, we redirect to the url.
|
||||
if (signatureVersion !== imagesResizingSignVersion) {
|
||||
return Response.redirect(url, 302);
|
||||
}
|
||||
|
||||
// Verify the signature
|
||||
const verified = await verifyImageSignature(url, { signature, version: signatureVersion });
|
||||
const verified = await verifyImageSignature(url, { signature });
|
||||
if (!verified) {
|
||||
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -8,10 +8,10 @@ import { useScrollPage } from '@/components/hooks';
|
||||
/**
|
||||
* Client component to initialize interactivity for a page.
|
||||
*/
|
||||
export function PageClientLayout(props: {}) {
|
||||
export function PageClientLayout(props: { withSections?: boolean }) {
|
||||
// We use this hook in the page layout to ensure the elements for the blocks
|
||||
// are rendered before we scroll to a hash or to the top of the page
|
||||
useScrollPage();
|
||||
useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
|
||||
|
||||
useStripFallbackQueryParam();
|
||||
return null;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { TrackPageViewEvent } from '@/components/Insights';
|
||||
import { getSpaceLanguage, t } from '@/intl/server';
|
||||
import { getSiteLayoutData } 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 getSiteLayoutData(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';
|
||||
@@ -35,6 +34,7 @@ export default async function Page(props: {
|
||||
customization,
|
||||
pages,
|
||||
page,
|
||||
ancestors,
|
||||
document,
|
||||
} = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
@@ -73,7 +73,7 @@ export default async function Page(props: {
|
||||
page,
|
||||
};
|
||||
|
||||
const withSections = Boolean(sections && sections.length > 0);
|
||||
const withSections = Boolean(sections && sections.list.length > 0);
|
||||
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
|
||||
|
||||
return (
|
||||
@@ -103,6 +103,7 @@ export default async function Page(props: {
|
||||
customization={customization}
|
||||
context={contentRefContext}
|
||||
page={page}
|
||||
ancestors={ancestors}
|
||||
document={document}
|
||||
withPageFeedback={
|
||||
// Display the page feedback in the page footer if the aside is not visible
|
||||
@@ -111,7 +112,7 @@ export default async function Page(props: {
|
||||
/>
|
||||
</div>
|
||||
<React.Suspense fallback={null}>
|
||||
<PageClientLayout />
|
||||
<PageClientLayout withSections={withSections} />
|
||||
</React.Suspense>
|
||||
</>
|
||||
);
|
||||
@@ -150,7 +151,8 @@ export async function generateMetadata({
|
||||
.join(' | '),
|
||||
description: page.description ?? '',
|
||||
alternates: {
|
||||
canonical: absoluteHref(getPagePath(pages, page), true),
|
||||
// Trim trailing slashes in canonical URL to match the redirect behavior
|
||||
canonical: absoluteHref(getPagePath(pages, page), true).replace(/\/+$/, ''),
|
||||
},
|
||||
openGraph: {
|
||||
images: [
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -42,7 +43,7 @@ export default async function ContentLayout(props: { children: React.ReactNode }
|
||||
sections,
|
||||
} = await fetchContentData();
|
||||
|
||||
ReactDOM.preconnect(api().endpoint);
|
||||
ReactDOM.preconnect(api().client.endpoint);
|
||||
if (assetsDomain) {
|
||||
ReactDOM.preconnect(assetsDomain);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ContentVisibility } from '@gitbook/api';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import { getCollection, getSite, getSpace } from '@/lib/api';
|
||||
import { getSpace, getSite } from '@/lib/api';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
import { getSiteContentPointer } from '@/lib/pointer';
|
||||
import { isSpaceIndexable } from '@/lib/seo';
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ImageResponse } from 'next/og';
|
||||
import { NextRequest } from 'next/server';
|
||||
import React from 'react';
|
||||
|
||||
import { getCurrentSiteCustomization, getSite, getSpace } from '@/lib/api';
|
||||
import { getSite, getSiteData, getSpace } from '@/lib/api';
|
||||
import { getEmojiForCode } from '@/lib/emojis';
|
||||
import { getSiteContentPointer } from '@/lib/pointer';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -38,9 +38,9 @@ export async function GET(req: NextRequest) {
|
||||
const pointer = getSiteContentPointer();
|
||||
const spaceId = pointer.spaceId;
|
||||
|
||||
const [space, customization] = await Promise.all([
|
||||
const [space, { customization }] = await Promise.all([
|
||||
getSpace(spaceId, pointer.siteShareKey),
|
||||
getCurrentSiteCustomization(pointer),
|
||||
getSiteData(pointer),
|
||||
]);
|
||||
const site = await getSite(pointer.organizationId, pointer.siteId);
|
||||
const contentTitle = getContentTitle(space, customization, site);
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { RevisionPage, SiteSection, SiteSpace, Space } from '@gitbook/api';
|
||||
import { assert } from 'ts-essentials';
|
||||
import { RevisionPage } from '@gitbook/api';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import {
|
||||
getRevisionPageByPath,
|
||||
getDocument,
|
||||
ContentTarget,
|
||||
getSpaceContentData,
|
||||
getSiteData,
|
||||
getSite,
|
||||
getCurrentSiteCustomization,
|
||||
getSiteStructure,
|
||||
getSiteRedirectBySource,
|
||||
} from '@/lib/api';
|
||||
import { resolvePagePath, resolvePageId } from '@/lib/pages';
|
||||
import { getSiteContentPointer } from '@/lib/pointer';
|
||||
@@ -21,35 +19,18 @@ export interface PageIdParams {
|
||||
pageId: string;
|
||||
}
|
||||
|
||||
type SectionsList = { list: SiteSection[]; section: SiteSection };
|
||||
|
||||
/**
|
||||
* Fetch all the data needed to render the content layout.
|
||||
*/
|
||||
export async function fetchContentData() {
|
||||
const content = getSiteContentPointer();
|
||||
|
||||
const [{ space, contentTarget, pages, customization, scripts }, siteStructure] =
|
||||
const [{ space, contentTarget, pages }, { customization, site, sections, spaces, scripts }] =
|
||||
await Promise.all([
|
||||
getSpaceContentData(content, content.siteShareKey),
|
||||
getSiteData(content),
|
||||
fetchSiteStructure({
|
||||
organizationId: content.organizationId,
|
||||
siteId: content.siteId,
|
||||
siteShareKey: content.siteShareKey,
|
||||
}),
|
||||
]);
|
||||
|
||||
const site = siteStructure.site;
|
||||
|
||||
const siteSections =
|
||||
content.siteSectionId && siteStructure.sections
|
||||
? parseSiteSectionsList(content.siteSectionId, siteStructure.sections)
|
||||
: null;
|
||||
|
||||
const spaces =
|
||||
siteStructure.spaces ??
|
||||
(siteSections ? parseSpacesFromSiteSpaces(siteSections.section.siteSpaces) : []);
|
||||
|
||||
// we grab the space attached to the parent as it contains overriden customizations
|
||||
const spaceRelativeToParent = spaces?.find((space) => space.id === content.spaceId);
|
||||
|
||||
@@ -58,53 +39,39 @@ export async function fetchContentData() {
|
||||
contentTarget,
|
||||
space: spaceRelativeToParent ?? space,
|
||||
pages,
|
||||
sections: siteSections,
|
||||
site,
|
||||
sections,
|
||||
spaces,
|
||||
shareKey: content.siteShareKey,
|
||||
customization,
|
||||
scripts,
|
||||
ancestors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function parseSiteSectionsList(siteSectionId: string, sections: SiteSection[]) {
|
||||
const section = sections.find((section) => section.id === siteSectionId);
|
||||
assert(sectionIsDefined(section), 'A section must be defined when there are multiple sections');
|
||||
return { list: sections, section } satisfies SectionsList;
|
||||
}
|
||||
|
||||
function sectionIsDefined(section?: SiteSection): section is NonNullable<SiteSection> {
|
||||
return typeof section !== 'undefined' && section !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all the data needed to render the content.
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(params: PagePathParams | PageIdParams) {
|
||||
const content = getSiteContentPointer();
|
||||
const contentData = await fetchContentData();
|
||||
|
||||
const { space, contentTarget, pages, customization, scripts } = await getSiteData(content);
|
||||
const page = await resolvePage(contentTarget, pages, params);
|
||||
const [siteStructure, document] = await Promise.all([
|
||||
fetchSiteStructure({
|
||||
organizationId: content.organizationId,
|
||||
siteId: content.siteId,
|
||||
siteShareKey: content.siteShareKey,
|
||||
}),
|
||||
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null,
|
||||
]);
|
||||
const page = await resolvePage({
|
||||
organizationId: contentData.space.organization,
|
||||
siteId: contentData.site.id,
|
||||
spaceId: contentData.contentTarget.spaceId,
|
||||
revisionId: contentData.contentTarget.revisionId,
|
||||
pages: contentData.pages,
|
||||
shareKey: contentData.shareKey,
|
||||
params,
|
||||
});
|
||||
const document = page?.page.documentId
|
||||
? await getDocument(contentData.space.id, page.page.documentId)
|
||||
: null;
|
||||
|
||||
return {
|
||||
content,
|
||||
contentTarget,
|
||||
space,
|
||||
pages,
|
||||
customization,
|
||||
scripts,
|
||||
ancestors: [],
|
||||
...contentData,
|
||||
...page,
|
||||
...siteStructure,
|
||||
document,
|
||||
};
|
||||
}
|
||||
@@ -113,11 +80,17 @@ export async function fetchPageData(params: PagePathParams | PageIdParams) {
|
||||
* Resolve a page from the params.
|
||||
* If the path can't be found, we try to resolve it from the API to handle redirects.
|
||||
*/
|
||||
async function resolvePage(
|
||||
contentTarget: ContentTarget,
|
||||
pages: RevisionPage[],
|
||||
params: PagePathParams | PageIdParams,
|
||||
) {
|
||||
async function resolvePage(input: {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
spaceId: string;
|
||||
revisionId: string;
|
||||
shareKey: string | undefined;
|
||||
pages: RevisionPage[];
|
||||
params: PagePathParams | PageIdParams;
|
||||
}) {
|
||||
const { organizationId, siteId, spaceId, revisionId, pages, shareKey, params } = input;
|
||||
|
||||
if ('pageId' in params) {
|
||||
return resolvePageId(pages, params.pageId);
|
||||
}
|
||||
@@ -131,78 +104,31 @@ async function resolvePage(
|
||||
return page;
|
||||
}
|
||||
|
||||
// If page can't be found, we try with the API, in case we have a redirect
|
||||
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
|
||||
// The page rendering will take care of redirecting to a normalized pathname.
|
||||
//
|
||||
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
|
||||
if (rawPathname.length <= 512) {
|
||||
const resolved = await getRevisionPageByPath(
|
||||
contentTarget.spaceId,
|
||||
contentTarget.revisionId,
|
||||
rawPathname,
|
||||
);
|
||||
// If page can't be found, we try with the API, in case we have a redirect at space level.
|
||||
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
|
||||
// The page rendering will take care of redirecting to a normalized pathname.
|
||||
const resolved = await getRevisionPageByPath(spaceId, revisionId, rawPathname);
|
||||
if (resolved) {
|
||||
return resolvePageId(pages, resolved.id);
|
||||
}
|
||||
|
||||
// If a page still can't be found, we try with the API, in case we have a redirect at site level.
|
||||
const resolvedSiteRedirect = await getSiteRedirectBySource({
|
||||
organizationId,
|
||||
siteId,
|
||||
source: rawPathname.startsWith('/') ? rawPathname : `/${rawPathname}`,
|
||||
siteShareKey: input.shareKey,
|
||||
});
|
||||
if (resolvedSiteRedirect) {
|
||||
return redirect(resolvedSiteRedirect.target);
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the structure of an organization site.
|
||||
* This includes the site and its sections or spaces.
|
||||
*/
|
||||
async function fetchSiteStructure(args: {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
siteShareKey: string | undefined;
|
||||
}) {
|
||||
const { organizationId, siteId, siteShareKey } = args;
|
||||
const [orgSite, siteStructure, siteParentCustomizations] = await Promise.all([
|
||||
getSite(organizationId, siteId),
|
||||
getSiteStructure({ organizationId, siteId, siteShareKey }),
|
||||
getCurrentSiteCustomization({ organizationId, siteId, siteSpaceId: undefined }),
|
||||
]);
|
||||
|
||||
const siteSections =
|
||||
siteStructure.type === 'sections' && siteStructure.structure
|
||||
? siteStructure.structure
|
||||
: null;
|
||||
const siteSpaces =
|
||||
siteStructure.type === 'siteSpaces' && siteStructure.structure
|
||||
? parseSpacesFromSiteSpaces(siteStructure.structure)
|
||||
: null;
|
||||
|
||||
// override the title with the customization title
|
||||
const site = {
|
||||
...orgSite,
|
||||
...(siteParentCustomizations?.title ? { title: siteParentCustomizations.title } : {}),
|
||||
};
|
||||
|
||||
return {
|
||||
site,
|
||||
spaces: siteSpaces,
|
||||
sections: siteSections,
|
||||
};
|
||||
}
|
||||
|
||||
function parseSpacesFromSiteSpaces(siteSpaces: SiteSpace[]) {
|
||||
const spaces: Record<string, Space> = {};
|
||||
siteSpaces.forEach((siteSpace) => {
|
||||
spaces[siteSpace.space.id] = {
|
||||
...siteSpace.space,
|
||||
title: siteSpace.title ?? siteSpace.space.title,
|
||||
urls: {
|
||||
...siteSpace.space.urls,
|
||||
published: siteSpace.urls.published,
|
||||
},
|
||||
};
|
||||
});
|
||||
return Object.values(spaces);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the page path from the params.
|
||||
*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CustomizationRootLayout } from '@/components/RootLayout';
|
||||
import { getSiteLayoutData } from '@/lib/api';
|
||||
import { getSiteData } from '@/lib/api';
|
||||
import { getSiteContentPointer } from '@/lib/pointer';
|
||||
|
||||
/**
|
||||
@@ -10,7 +10,7 @@ export default async function SiteRootLayout(props: { children: React.ReactNode
|
||||
const { children } = props;
|
||||
|
||||
const pointer = getSiteContentPointer();
|
||||
const { customization } = await getSiteLayoutData(pointer);
|
||||
const { customization } = await getSiteData(pointer);
|
||||
|
||||
return (
|
||||
<CustomizationRootLayout customization={customization}>{children}</CustomizationRootLayout>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { SpaceIntegrationScript } from '@gitbook/api';
|
||||
|
||||
import { CustomizationRootLayout } from '@/components/RootLayout';
|
||||
import { getSiteLayoutData, getSpaceCustomization } from '@/lib/api';
|
||||
import { getSiteData, getSpaceCustomization } from '@/lib/api';
|
||||
|
||||
import { getSiteOrSpacePointerForPDF } from './pointer';
|
||||
|
||||
@@ -14,7 +14,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
|
||||
|
||||
const pointer = getSiteOrSpacePointerForPDF();
|
||||
const { customization } = await ('siteId' in pointer
|
||||
? getSiteLayoutData(pointer)
|
||||
? getSiteData(pointer)
|
||||
: getSpaceLayoutData(pointer.spaceId));
|
||||
|
||||
return (
|
||||
@@ -26,7 +26,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
|
||||
* Fetch all the layout data about a space at once.
|
||||
*/
|
||||
async function getSpaceLayoutData(spaceId: string) {
|
||||
const [customization, scripts] = await Promise.all([
|
||||
const [{ customization }, scripts] = await Promise.all([
|
||||
getSpaceCustomization(spaceId),
|
||||
[] as SpaceIntegrationScript[],
|
||||
]);
|
||||
|
||||
@@ -11,23 +11,24 @@ import { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import * as React from 'react';
|
||||
|
||||
import { DocumentView, createHighlightingContext } 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,
|
||||
getCurrentSiteCustomization,
|
||||
} 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';
|
||||
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 { SiteContentPointer, SpaceContentPointer } from '../../../../lib/api';
|
||||
import { PDFSearchParams, getPDFSearchParams } from '../../../../lib/urls';
|
||||
|
||||
import './pdf.css';
|
||||
import { PageControlButtons } from './PageControlButtons';
|
||||
@@ -40,11 +41,9 @@ export const runtime = 'edge';
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const pointer = getSiteOrSpacePointerForPDF();
|
||||
const [space, customization] = await Promise.all([
|
||||
const [space, { customization }] = await Promise.all([
|
||||
getSpace(pointer.spaceId, 'siteId' in pointer ? pointer.siteShareKey : undefined),
|
||||
'siteId' in pointer
|
||||
? getCurrentSiteCustomization(pointer)
|
||||
: getSpaceCustomization(pointer.spaceId),
|
||||
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -57,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));
|
||||
@@ -67,10 +68,8 @@ export default async function PDFHTMLOutput(props: { searchParams: { [key: strin
|
||||
currentPDFUrl += '?' + searchParams.toString();
|
||||
|
||||
// Load the content,
|
||||
const [customization, { space, contentTarget, pages: rootPages }] = await Promise.all([
|
||||
'siteId' in pointer
|
||||
? getCurrentSiteCustomization(pointer)
|
||||
: getSpaceCustomization(pointer.spaceId),
|
||||
const [{ customization }, { space, contentTarget, pages: rootPages }] = await Promise.all([
|
||||
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
|
||||
getSpaceContentData(pointer, 'siteId' in pointer ? pointer.siteShareKey : undefined),
|
||||
]);
|
||||
const language = getSpaceLanguage(customization);
|
||||
@@ -231,7 +230,6 @@ async function PDFPageDocument(props: {
|
||||
const { space, page, refContext } = props;
|
||||
|
||||
const document = page.documentId ? await getDocument(space.id, page.documentId) : null;
|
||||
const shouldHighlightCode = createHighlightingContext();
|
||||
|
||||
return (
|
||||
<PrintPage id={pagePDFContainerId(page)}>
|
||||
@@ -254,7 +252,6 @@ async function PDFPageDocument(props: {
|
||||
contentRefContext: refContext,
|
||||
resolveContentRef: (ref) => resolveContentRef(ref, refContext),
|
||||
getId: (id) => pagePDFContainerId(page, id),
|
||||
shouldHighlightCode,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
// @ts-ignore
|
||||
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
|
||||
|
||||
import { withMiddlewareHeadersStorage } from './lib/middleware';
|
||||
|
||||
/**
|
||||
* We use a custom entrypoint until we can move to opennext (https://github.com/opennextjs/opennextjs-cloudflare/issues/92).
|
||||
* There is a bug in next-on-pages where headers can't be set on the response in the middleware for RSC requests (https://github.com/cloudflare/next-on-pages/issues/897).
|
||||
*/
|
||||
export default {
|
||||
async fetch(request, env, ctx) {
|
||||
const response = await withMiddlewareHeadersStorage(() =>
|
||||
nextOnPagesHandler.fetch(request, env, ctx),
|
||||
);
|
||||
|
||||
return response;
|
||||
},
|
||||
} as ExportedHandler<{ ASSETS: Fetcher }>;
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -22,10 +22,8 @@ import { Heading } from './Heading';
|
||||
import { Hint } from './Hint';
|
||||
import { Images } from './Images';
|
||||
import { IntegrationBlock } from './Integration';
|
||||
import { List } from './List';
|
||||
import { ListItem } from './ListItem';
|
||||
import { ListOrdered } from './ListOrdered';
|
||||
import { ListTasks } from './ListTasks';
|
||||
import { ListUnordered } from './ListUnordered';
|
||||
import { BlockMath } from './Math';
|
||||
import { OpenAPI } from './OpenAPI';
|
||||
import { Paragraph } from './Paragraph';
|
||||
@@ -65,11 +63,9 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
|
||||
case 'heading-3':
|
||||
return <Heading {...props} block={block} />;
|
||||
case 'list-ordered':
|
||||
return <ListOrdered {...props} block={block} />;
|
||||
case 'list-unordered':
|
||||
return <ListUnordered {...props} block={block} />;
|
||||
case 'list-tasks':
|
||||
return <ListTasks {...props} block={block} />;
|
||||
return <List {...props} block={block} />;
|
||||
case 'list-item':
|
||||
return <ListItem {...props} block={block} />;
|
||||
case 'code':
|
||||
|
||||
@@ -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',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -48,7 +52,7 @@ async function SpaceRefCard(
|
||||
return null;
|
||||
}
|
||||
|
||||
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId));
|
||||
const { customization: spaceCustomization } = getSpaceCustomization(spaceId);
|
||||
const customFavicon = spaceCustomization?.favicon;
|
||||
const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined;
|
||||
const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined;
|
||||
|
||||
@@ -71,7 +71,7 @@ export function Caption(
|
||||
'text-center',
|
||||
'mt-2',
|
||||
'text-dark/7',
|
||||
'dark:text-light/6',
|
||||
'dark:text-light/7',
|
||||
)}
|
||||
>
|
||||
<Inlines
|
||||
|
||||
@@ -15,8 +15,7 @@ import './theme.css';
|
||||
*/
|
||||
export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
|
||||
const { block, document, style, context } = props;
|
||||
const withHighlighting = context.shouldHighlightCode(context.content?.spaceId);
|
||||
const lines = withHighlighting ? await highlight(block) : plainHighlighting(block);
|
||||
const lines = await highlight(block);
|
||||
|
||||
const id = block.key!;
|
||||
|
||||
@@ -99,6 +98,8 @@ export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
|
||||
'overflow-auto',
|
||||
'bg-light-2',
|
||||
'dark:bg-dark-2',
|
||||
'border-light-4',
|
||||
'dark:border-dark-4',
|
||||
'hide-scroll',
|
||||
titleRoundingStyle,
|
||||
)}
|
||||
@@ -282,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>;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,6 @@ export function PlainCodeBlock(props: { code: string; syntax: string }) {
|
||||
mode: 'default',
|
||||
contentRefContext: null,
|
||||
resolveContentRef: async () => null,
|
||||
shouldHighlightCode: () => true,
|
||||
}}
|
||||
block={block}
|
||||
ancestorBlocks={[]}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
const CODE_HIGHLIGHT_BLOCK_LIMIT = 50;
|
||||
|
||||
/**
|
||||
* Spaces where we'll always use plain highlighting.
|
||||
*/
|
||||
const PLAIN_HIGHLIGHTING_SPACES: string[] = [
|
||||
'V9geAO9ITPi8WOYK5o0r',
|
||||
'puRmcwVxGFtHph8IjXaf',
|
||||
'e3jwbMOrr4RhKtZ9C0XL',
|
||||
'ryjzVNizLfd6pYogN3dm',
|
||||
];
|
||||
|
||||
/**
|
||||
* Protect against memory issues when highlighting a large number of code blocks.
|
||||
* This context only allows 50 code blocks per render to be highlighted.
|
||||
* Once highlighting can scale up to a large number of code blocks, it can be removed.
|
||||
*
|
||||
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
|
||||
*/
|
||||
export function createHighlightingContext() {
|
||||
let count = 0;
|
||||
return (spaceId?: string | undefined) => {
|
||||
if (!spaceId || PLAIN_HIGHLIGHTING_SPACES.includes(spaceId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
return count < CODE_HIGHLIGHT_BLOCK_LIMIT;
|
||||
};
|
||||
}
|
||||
@@ -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: 120,
|
||||
});
|
||||
// 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),
|
||||
// );
|
||||
// });
|
||||
// }
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
export * from './CodeBlock';
|
||||
export * from './PlainCodeBlock';
|
||||
export * from './createHighlightingContext';
|
||||
|
||||
@@ -38,16 +38,6 @@ export interface DocumentContext {
|
||||
*/
|
||||
getId?: (id: string) => string;
|
||||
|
||||
/**
|
||||
* Returns true if the given code block should be highlighted.
|
||||
* This function was added to protect against memory issues when highlighting
|
||||
* a large number of code blocks.
|
||||
* Once highlighting can scale up to a large number of code blocks, it can be removed.
|
||||
*
|
||||
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
|
||||
*/
|
||||
shouldHighlightCode: (spaceId: string | undefined) => boolean;
|
||||
|
||||
/**
|
||||
* True if the blocks should be wrapped in suspense boundary for isolated loading skeletons.
|
||||
* @default true
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'px-4',
|
||||
'py-4',
|
||||
'hint',
|
||||
'p-4',
|
||||
'transition-colors',
|
||||
'rounded-md',
|
||||
'straight-corners:rounded-none',
|
||||
@@ -26,19 +26,16 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
|
||||
)}
|
||||
>
|
||||
<div className={tcls('flex', 'flex-row')}>
|
||||
<div
|
||||
<Icon
|
||||
icon={hintStyle.icon}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'items-start',
|
||||
'justify-center',
|
||||
'pr-3',
|
||||
'size-5',
|
||||
'mr-4',
|
||||
'mt-0.5',
|
||||
firstLine.lineHeight,
|
||||
hintStyle.iconColor,
|
||||
)}
|
||||
>
|
||||
<Icon icon={hintStyle.icon} className={tcls('size-4')} />
|
||||
</div>
|
||||
/>
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
@@ -48,7 +45,7 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
|
||||
// render hash icon on the other side of the heading
|
||||
'flip-heading-hash',
|
||||
)}
|
||||
style={['flex-1', 'space-y-4', '[&>p]:text-sm', '[&>p]:leading-relaxed']}
|
||||
style={['flex-1', 'space-y-4', '[&_.hint]:border', '[&_pre]:border']}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -65,130 +62,69 @@ const HINT_STYLES: {
|
||||
} = {
|
||||
info: {
|
||||
icon: 'circle-info',
|
||||
iconColor: ['text-periwinkle-700', 'dark:text-periwinkle-400'],
|
||||
iconColor: ['text-primary-500', 'dark:text-primary-400'],
|
||||
bodyColor: [
|
||||
'[&>a]:text-periwinkle-700',
|
||||
'[&>a:hover]:text-periwinkle-800',
|
||||
'[&>code]:bg-periwinkle-700/4',
|
||||
'[&>code]:text-inherit',
|
||||
'[&>code]:shadow-none',
|
||||
|
||||
'text-periwinkle-900',
|
||||
|
||||
'dark:text-periwinkle-200',
|
||||
'dark:[&>a]:text-periwinkle',
|
||||
'dark:[&>a:hover]:text-periwinkle-600',
|
||||
'dark:[&>code]:bg-periwinkle-200/2',
|
||||
'dark:[&>code]:text-inherit',
|
||||
'decoration-periwinkle-700/6',
|
||||
'dark:decoration-periwinkle/6',
|
||||
'[&_a]:text-primary-500',
|
||||
'[&_a:hover]:text-primary-600',
|
||||
'dark:[&_a]:text-primary-400',
|
||||
'dark:[&_a:hover]:text-primary-300',
|
||||
],
|
||||
style: [
|
||||
'bg-gradient-to-b',
|
||||
'from-periwinkle/6',
|
||||
'to-periwinkle/5',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'ring-dark/1',
|
||||
'dark:ring-periwinkle/1',
|
||||
'dark:from-periwinkle/2',
|
||||
'dark:to-periwinkle/[0.1]',
|
||||
'bg-dark-1/1',
|
||||
'border-dark/3',
|
||||
'dark:bg-light/1',
|
||||
'dark:border-light/3',
|
||||
'[&_.can-override-bg]:bg-dark-1/2',
|
||||
'[&_.can-override-text]:text-dark',
|
||||
'dark:[&_.can-override-bg]:bg-light/2',
|
||||
'dark:[&_.can-override-text]:text-light',
|
||||
],
|
||||
},
|
||||
warning: {
|
||||
icon: 'circle-exclamation',
|
||||
iconColor: ['text-yellow-800', 'dark:text-yellow'],
|
||||
iconColor: ['text-amber-500', 'dark:text-orange-400'], // Darker shades of orange-* mismatch with lighter shades, so in light mode we use amber text on top of orange bg.
|
||||
bodyColor: [
|
||||
'[&>a]:text-yellow-700',
|
||||
'[&>a:hover]:text-yellow-800',
|
||||
'[&>code]:bg-yellow-600/5',
|
||||
'[&>code]:text-inherit',
|
||||
'[&>code]:shadow-none',
|
||||
|
||||
'text-yellow-900',
|
||||
|
||||
'dark:text-yellow-200',
|
||||
'dark:[&>a]:text-yellow',
|
||||
'dark:[&>a:hover]:text-yellow-600',
|
||||
'dark:[&>code]:bg-yellow-200/2',
|
||||
'dark:[&>code]:text-inherit',
|
||||
'decoration-yellow-700/6',
|
||||
'dark:decoration-yellow/6',
|
||||
],
|
||||
style: [
|
||||
'bg-gradient-to-b',
|
||||
'from-yellow/6',
|
||||
'to-yellow/5',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'ring-dark/1',
|
||||
'dark:ring-yellow/[0.02]',
|
||||
'dark:from-yellow/[0.06]',
|
||||
'dark:to-yellow/2',
|
||||
'[&_a]:text-orange-800',
|
||||
'[&_a:hover]:text-orange-900',
|
||||
'dark:[&_a]:text-orange-400',
|
||||
'dark:[&_a:hover]:text-orange-300',
|
||||
'[&_.can-override-bg]:bg-orange-500/3',
|
||||
'[&_.can-override-text]:text-orange-800',
|
||||
'dark:[&_.can-override-text]:text-orange-400',
|
||||
'decoration-orange-800/6',
|
||||
'dark:decoration-orange-400/6',
|
||||
],
|
||||
style: ['bg-orange-500/2', 'border-orange-500/4'],
|
||||
},
|
||||
danger: {
|
||||
icon: 'triangle-exclamation',
|
||||
iconColor: ['text-pomegranate-700', 'dark:text-pomegranate-400'],
|
||||
iconColor: ['text-red-500', 'dark:text-red-400'],
|
||||
bodyColor: [
|
||||
'[&>a]:text-pomegranate-600/9',
|
||||
'[&>a:hover]:text-pomegranate-800',
|
||||
'[&>code]:bg-pomegranate-600/4',
|
||||
'[&>code]:text-inherit',
|
||||
'[&>code]:shadow-none',
|
||||
|
||||
'text-pomegranate-900',
|
||||
|
||||
'dark:text-pomegranate-100',
|
||||
'dark:[&>a]:text-pomegranate',
|
||||
'dark:[&>a:hover]:text-pomegranate-600',
|
||||
'dark:[&>code]:bg-pomegranate-200/2',
|
||||
'dark:[&>code]:text-inherit',
|
||||
'decoration-pomegranate-600/6',
|
||||
'dark:decoration-pomegranate/6',
|
||||
],
|
||||
style: [
|
||||
'bg-gradient-to-b',
|
||||
'from-pomegranate/4',
|
||||
'to-pomegranate/3',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'ring-dark/1',
|
||||
'dark:ring-pomegranate/1',
|
||||
'dark:from-pomegranate/2',
|
||||
'dark:to-pomegranate/3',
|
||||
'[&_a]:text-red-800',
|
||||
'[&_a:hover]:text-red-900',
|
||||
'dark:[&_a]:text-red-400',
|
||||
'dark:[&_a:hover]:text-red-300',
|
||||
'[&_.can-override-bg]:bg-red-500/3',
|
||||
'[&_.can-override-text]:text-red-400',
|
||||
'decoration-red-800/6',
|
||||
'dark:decoration-red-400/6',
|
||||
],
|
||||
style: ['bg-red-500/2', 'border-red-500/4'],
|
||||
},
|
||||
success: {
|
||||
icon: 'circle-check',
|
||||
iconColor: ['text-teal-700', 'dark:text-teal-400'],
|
||||
iconColor: ['text-green-500', 'dark:text-green-400'],
|
||||
bodyColor: [
|
||||
'[&>a]:text-teal-600',
|
||||
'[&>a:hover]:text-teal-800',
|
||||
'[&>code]:bg-teal-600/4',
|
||||
'[&>code]:text-inherit',
|
||||
'[&>code]:shadow-none',
|
||||
|
||||
'text-teal-800',
|
||||
|
||||
'dark:text-teal-100',
|
||||
'dark:[&>a]:text-teal-400',
|
||||
'dark:[&>a:hover]:text-teal-500',
|
||||
'dark:[&>code]:bg-teal-200/2',
|
||||
'dark:[&>code]:text-inherit',
|
||||
'decoration-teal/6',
|
||||
'dark:decoration-teal/6',
|
||||
],
|
||||
style: [
|
||||
'bg-gradient-to-b',
|
||||
'from-teal/4',
|
||||
'to-teal/3',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'ring-dark/1',
|
||||
'dark:ring-teal/1',
|
||||
'dark:from-teal/2',
|
||||
'dark:to-teal/3',
|
||||
'[&_a]:text-green-800',
|
||||
'[&_a:hover]:text-green-900',
|
||||
'dark:[&_a]:text-green-400',
|
||||
'dark:[&_a:hover]:text-green-300',
|
||||
'[&_.can-override-bg]:bg-green-500/3',
|
||||
'[&_.can-override-text]:text-green-800',
|
||||
'dark:[&_.can-override-text]:text-green-400',
|
||||
'decoration-green-800/6',
|
||||
'dark:decoration-green-400/6',
|
||||
],
|
||||
style: ['bg-green-500/2', 'border-green-500/4'],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -25,7 +25,11 @@ export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
|
||||
|
||||
return (
|
||||
/* Ensure images dont expand to the size of the container where this Image may be nested in. Now it's always nested in a size-restricted container */
|
||||
<span className={tcls(size !== 'line' ? ['inline-flex', 'max-w-[300px]'] : null)}>
|
||||
<span
|
||||
className={tcls(
|
||||
size !== 'line' ? ['inline-flex', 'max-w-[300px]', 'align-middle'] : null,
|
||||
)}
|
||||
>
|
||||
<Image
|
||||
alt={inline.data.caption ?? ''}
|
||||
sizes={await getImageSizes(size, src)}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
DocumentBlockListOrdered,
|
||||
DocumentBlockListTasks,
|
||||
DocumentBlockListUnordered,
|
||||
} from '@gitbook/api';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
export function List(
|
||||
props: BlockProps<
|
||||
DocumentBlockListUnordered | DocumentBlockListOrdered | DocumentBlockListTasks
|
||||
>,
|
||||
) {
|
||||
const { block, style, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
return (
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
tag={getListTag(block.type)}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={['space-y-2', style]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function getListTag(
|
||||
type:
|
||||
| DocumentBlockListUnordered['type']
|
||||
| DocumentBlockListOrdered['type']
|
||||
| DocumentBlockListTasks['type'],
|
||||
) {
|
||||
switch (type) {
|
||||
case 'list-ordered':
|
||||
return 'ol';
|
||||
case 'list-unordered':
|
||||
case 'list-tasks':
|
||||
return 'ul';
|
||||
default:
|
||||
assertNever(type);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
.olListItemBullet {
|
||||
/* Align the bullet container with the first line of text */
|
||||
line-height: inherit;
|
||||
height: 1lh;
|
||||
/* Align the bullet content with the middle of the text */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.olListItemBullet::before {
|
||||
@apply text-base;
|
||||
--tw-content: attr(data-value) '. ';
|
||||
content: var(--tw-content);
|
||||
}
|
||||
@@ -1,114 +1,233 @@
|
||||
import {
|
||||
DocumentBlock,
|
||||
DocumentBlockListItem,
|
||||
DocumentBlockListOrdered,
|
||||
DocumentBlockListTasks,
|
||||
DocumentBlockListUnordered,
|
||||
} from '@gitbook/api';
|
||||
import classNames from 'classnames';
|
||||
import assertNever from 'assert-never';
|
||||
import { assert } from 'ts-essentials';
|
||||
|
||||
import { Checkbox } from '@/components/primitives';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
import styles from './ListItem.module.css';
|
||||
import { getBlockTextStyle } from './spacing';
|
||||
|
||||
export function ListItem(props: BlockProps<DocumentBlockListItem>) {
|
||||
const { block, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
const textStyle = getBlockTextStyle(block);
|
||||
const parent = ancestorBlocks[ancestorBlocks.length - 1];
|
||||
assert(
|
||||
(parent && parent.type === 'list-ordered') ||
|
||||
parent.type === 'list-unordered' ||
|
||||
parent.type === 'list-tasks',
|
||||
'Invalid parent list type',
|
||||
);
|
||||
|
||||
const parent = ancestorBlocks[ancestorBlocks.length - 1] as
|
||||
| DocumentBlockListOrdered
|
||||
| DocumentBlockListUnordered
|
||||
| DocumentBlockListTasks
|
||||
| undefined;
|
||||
const blocksElement = (
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
blockStyle={tcls(
|
||||
'min-h-[1lh]',
|
||||
// flip heading hash icon if list item is a heading
|
||||
'flip-heading-hash',
|
||||
// remove margin-top for the first heading in a list
|
||||
'[&: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"
|
||||
/>
|
||||
);
|
||||
|
||||
const ListItemType = () => {
|
||||
switch (parent?.type) {
|
||||
case 'list-tasks':
|
||||
return (
|
||||
<li>
|
||||
<div className={tcls('flex', 'flex-row')}>
|
||||
<div
|
||||
className={tcls(
|
||||
textStyle.textSize,
|
||||
'flex',
|
||||
'flex-col',
|
||||
'justify-center',
|
||||
'h-[1lh]',
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
id={block.key!}
|
||||
disabled
|
||||
checked={block.data?.checked}
|
||||
className={tcls('relative')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label htmlFor={block.key} className={tcls('flex-1')}>
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
blockStyle={tcls('flip-heading-hash')}
|
||||
style={tcls('ml-2', 'space-y-2')}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
case 'list-ordered':
|
||||
const start = parent.data.start ?? 1;
|
||||
const indexInParent = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
|
||||
const index = indexInParent + start;
|
||||
|
||||
return (
|
||||
<li value={index} className={tcls(textStyle.lineHeight)}>
|
||||
<div
|
||||
data-value={index}
|
||||
className={classNames(
|
||||
'bullet',
|
||||
styles.olListItemBullet,
|
||||
tcls(textStyle.textSize),
|
||||
)}
|
||||
></div>
|
||||
{/* zero width space to force layouts with empty lists */}
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={tcls('space-y-2', 'flex-1', 'flex', 'flex-col')}
|
||||
blockStyle={tcls(
|
||||
textStyle.lineHeight,
|
||||
'min-h-[1lh]',
|
||||
//flip heading hash icon if list item is a heading
|
||||
'flip-heading-hash',
|
||||
)}
|
||||
switch (parent.type) {
|
||||
case 'list-tasks':
|
||||
return (
|
||||
<ListItemLI block={block}>
|
||||
<ListItemPrefix block={block}>
|
||||
<Checkbox
|
||||
id={block.key!}
|
||||
disabled
|
||||
checked={block.data?.checked}
|
||||
className="relative"
|
||||
size="small"
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<li className={tcls(textStyle.lineHeight)}>
|
||||
<div className={tcls('bullet', textStyle.textSize)}></div>
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={tcls('space-y-2', 'flex', 'flex-col')}
|
||||
blockStyle={tcls(
|
||||
'min-h-[1lh]',
|
||||
//flip heading hash icon if list item is a heading
|
||||
'flip-heading-hash',
|
||||
)}
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
};
|
||||
</ListItemPrefix>
|
||||
|
||||
return <ListItemType />;
|
||||
<label htmlFor={block.key} className={tcls('flex-1')}>
|
||||
{blocksElement}
|
||||
</label>
|
||||
</ListItemLI>
|
||||
);
|
||||
case 'list-ordered':
|
||||
return (
|
||||
<ListItemLI block={block}>
|
||||
<ListItemPrefix block={block}>
|
||||
<PseudoBefore
|
||||
content={getOrderedListItemPrefixContent({
|
||||
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
|
||||
block,
|
||||
parent,
|
||||
})}
|
||||
style={{
|
||||
fontSize: 'min(1em, 24px)',
|
||||
}}
|
||||
/>
|
||||
</ListItemPrefix>
|
||||
{blocksElement}
|
||||
</ListItemLI>
|
||||
);
|
||||
case 'list-unordered':
|
||||
return (
|
||||
<ListItemLI block={block}>
|
||||
<ListItemPrefix block={block}>
|
||||
<PseudoBefore
|
||||
content={getUnorderedListItemsPrefixContent({
|
||||
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
|
||||
})}
|
||||
fontFamily="Arial"
|
||||
style={{ fontSize: 'min(1.5em, 24px)', lineHeight: 1 }}
|
||||
/>
|
||||
</ListItemPrefix>
|
||||
{blocksElement}
|
||||
</ListItemLI>
|
||||
);
|
||||
default:
|
||||
assertNever(parent);
|
||||
}
|
||||
}
|
||||
|
||||
function getListItemDepth(input: {
|
||||
ancestorBlocks: DocumentBlock[];
|
||||
type: DocumentBlockListOrdered['type'] | DocumentBlockListUnordered['type'];
|
||||
}): number {
|
||||
const { ancestorBlocks, type } = input;
|
||||
|
||||
let depth = -1;
|
||||
|
||||
for (let i = ancestorBlocks.length - 1; i >= 0; i--) {
|
||||
const block = ancestorBlocks[i];
|
||||
if (block.type === type) {
|
||||
depth = depth + 1;
|
||||
continue;
|
||||
}
|
||||
if (block.type === 'list-item') {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return depth;
|
||||
}
|
||||
|
||||
function ListItemLI(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
|
||||
const textStyle = getBlockTextStyle(props.block);
|
||||
return <li className={tcls(textStyle.lineHeight, 'flex items-start')}>{props.children}</li>;
|
||||
}
|
||||
|
||||
function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
|
||||
const textStyle = getBlockTextStyle(props.block);
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
textStyle.textSize,
|
||||
textStyle.lineHeight,
|
||||
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark-4 dark:text-light-4',
|
||||
)}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getUnorderedListItemsPrefixContent(input: { depth: number }): string {
|
||||
switch (input.depth % 3) {
|
||||
case 0:
|
||||
return '•';
|
||||
case 1:
|
||||
return '◦';
|
||||
case 2:
|
||||
return '▪';
|
||||
default:
|
||||
return '•';
|
||||
}
|
||||
}
|
||||
|
||||
function PseudoBefore(props: {
|
||||
style?: React.CSSProperties;
|
||||
content: string;
|
||||
fontFamily?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="before:font-var before:content-[--pseudoBefore--content]"
|
||||
style={
|
||||
{
|
||||
'--pseudoBefore--content': `'${props.content}'`,
|
||||
'--font-family': props.fontFamily ?? 'inherit',
|
||||
...props.style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function getOrderedListItemPrefixContent(input: {
|
||||
depth: number;
|
||||
parent: DocumentBlockListOrdered;
|
||||
block: DocumentBlockListItem;
|
||||
}): string {
|
||||
const { parent, block } = input;
|
||||
const start = parent.data.start ?? 1;
|
||||
const index = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
|
||||
const value = index + start;
|
||||
switch (input.depth % 3) {
|
||||
// Use numbers
|
||||
case 0: {
|
||||
return `${value}.`;
|
||||
}
|
||||
// Use letters
|
||||
case 1: {
|
||||
const letters = 'abcdefghijklmnopqrstuvwxyz';
|
||||
return `${letters[(value - 1) % letters.length]}.`;
|
||||
}
|
||||
// Use roman numbers
|
||||
case 2: {
|
||||
return `${toRoman(value).toLowerCase()}.`;
|
||||
}
|
||||
default:
|
||||
return '•';
|
||||
}
|
||||
}
|
||||
|
||||
function toRoman(input: number): string {
|
||||
const lookup = {
|
||||
M: 1000,
|
||||
CM: 900,
|
||||
D: 500,
|
||||
CD: 400,
|
||||
C: 100,
|
||||
XC: 90,
|
||||
L: 50,
|
||||
XL: 40,
|
||||
X: 10,
|
||||
IX: 9,
|
||||
V: 5,
|
||||
IV: 4,
|
||||
I: 1,
|
||||
};
|
||||
let roman = '';
|
||||
let number = input;
|
||||
for (const i in lookup) {
|
||||
while (number >= lookup[i as keyof typeof lookup]) {
|
||||
roman += i;
|
||||
number -= lookup[i as keyof typeof lookup];
|
||||
}
|
||||
}
|
||||
return roman;
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { DocumentBlockListOrdered } from '@gitbook/api';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
export function ListOrdered(props: BlockProps<DocumentBlockListOrdered>) {
|
||||
const { block, style, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
return (
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
tag="ol"
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={[
|
||||
'space-y-2',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'[&>li]:gap-[1ch]',
|
||||
|
||||
'[counter-reset:list-decimal]',
|
||||
|
||||
'[&>li]:flex',
|
||||
'[&>li]:flex-row',
|
||||
|
||||
/* '[&>li>.bullet]:w-[1ch]', */
|
||||
'[&>li>.bullet]:tabular-nums',
|
||||
'[&>li>.bullet]:whitespace-nowrap',
|
||||
'[&>li>.bullet]:list-decimal',
|
||||
|
||||
'[&>li>.bullet]:before:h-[1lh]',
|
||||
'[&>li>.bullet]:before:leading-[inherit]',
|
||||
'[&>li>.bullet]:before:flex',
|
||||
/* '[&>li>.bullet]:before:pr-[1ch]', */
|
||||
'[&>li>.bullet]:text-dark/6',
|
||||
|
||||
//remove any spacing when using heading as list item
|
||||
'[&>li>div_div]:mt-0',
|
||||
|
||||
'dark:[&>li>.bullet]:text-light/6',
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { DocumentBlockListTasks, DocumentBlockListUnordered } from '@gitbook/api';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
export function ListTasks(props: BlockProps<DocumentBlockListTasks>) {
|
||||
const { block, style, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
return (
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
tag="ul"
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={[
|
||||
'list-none',
|
||||
'[&>li]:pl-[.25ch]',
|
||||
//remove any spacing when using heading as list item
|
||||
'[&>li>div_div]:mt-0',
|
||||
'space-y-2',
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { DocumentBlockListUnordered } from '@gitbook/api';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
export function ListUnordered(props: BlockProps<DocumentBlockListUnordered>) {
|
||||
const { block, style, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
const nestedBulletStyle = [
|
||||
// Level 1
|
||||
'[&>li>.bullet:before]:bullet-circleFilled',
|
||||
// Level 2
|
||||
`[&_&>li>.bullet:before]:bullet-circle`,
|
||||
// Level 3
|
||||
`[&_&_&>li>.bullet:before]:bullet-dash`,
|
||||
// Level 4
|
||||
`[&_&_&_&>li>.bullet:before]:bullet-squareFilled`,
|
||||
// Level 5
|
||||
`[&_&_&_&_&>li>.bullet:before]:bullet-square`,
|
||||
// Level 6 // reset back to reg bullets here
|
||||
`[&_&_&_&_&_&>li>.bullet:before]:bullet-circleFilled`,
|
||||
];
|
||||
|
||||
return (
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
tag="ul"
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
style={[
|
||||
'list-none',
|
||||
'space-y-2',
|
||||
'[&>li]:relative',
|
||||
'[&>li]:ps-[2.25ch]',
|
||||
//remove any spacing when using heading as list item
|
||||
'[&>li>div_div]:mt-0',
|
||||
//custom content setup for lists
|
||||
'[&>li>.bullet]:before:bg-dark/6',
|
||||
'[&>li>.bullet]:before:absolute',
|
||||
'[&>li>.bullet]:before:left-0',
|
||||
'[&>li>.bullet]:before:w-[1ch]',
|
||||
'[&>li>.bullet]:before:h-[1lh]',
|
||||
'[&>li>.bullet]:before:[mask-repeat:no-repeat]',
|
||||
'[&>li>.bullet]:before:[mask-position:left]',
|
||||
'dark:[&>li>.bullet]:before:bg-light/6',
|
||||
nestedBulletStyle,
|
||||
style,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
.light .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-300, 180 180 180)),
|
||||
rgb(var(--tint-color-300, 180 180 180)),
|
||||
rgb(var(--dark-base, 23 23 23)) 96%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
@@ -23,12 +23,12 @@
|
||||
--scalar-background-1: rgb(var(--light-base, 255 255 255));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-800, 30 30 30)),
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 96%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-800, 30 30 30)),
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 90%
|
||||
);
|
||||
--scalar-background-accent: #007d9c1f;
|
||||
@@ -57,13 +57,16 @@
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
|
||||
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
|
||||
#eeeeed 0px 0 0 1px;
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--dark-base, 22 22 22));
|
||||
}
|
||||
.dark .scalar-modal-layout,
|
||||
.dark .scalar-app,
|
||||
.dark .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700, 70 70 70)),
|
||||
rgb(var(--tint-color-700, 70 70 70)),
|
||||
rgb(var(--light-base, 255 255 255)) 100%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
@@ -81,12 +84,12 @@
|
||||
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-200, 200 200 200)),
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 92%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-200, 200 200 200)),
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 88%
|
||||
);
|
||||
--scalar-background-accent: #8ab4f81f;
|
||||
@@ -114,6 +117,9 @@
|
||||
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
|
||||
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px,
|
||||
0 0 0 1px rgba(255, 255, 255, 0.1);
|
||||
|
||||
--scalar-selection-background: rgba(96, 175, 255, 0.4);
|
||||
--scalar-selection-color: rgb(var(--light-base, 255 255 255));
|
||||
}
|
||||
.scalar-modal-layout,
|
||||
.scalar-app,
|
||||
|
||||
@@ -7,6 +7,11 @@ export function Stepper(props: BlockProps<DocumentBlockStepper>) {
|
||||
const { block, style, ancestorBlocks, ...contextProps } = props;
|
||||
|
||||
return (
|
||||
<Blocks {...contextProps} nodes={block.nodes} ancestorBlocks={[...ancestorBlocks, block]} />
|
||||
<Blocks
|
||||
blockStyle={style}
|
||||
{...contextProps}
|
||||
nodes={block.nodes}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,17 +30,17 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
|
||||
})();
|
||||
|
||||
return (
|
||||
<div className="flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto">
|
||||
<div className={tcls('flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto', style)}>
|
||||
<div className="relative select-none">
|
||||
<div
|
||||
className={tcls(
|
||||
'flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
|
||||
'can-override-bg can-override-text flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
|
||||
'font-medium text-primary-800 dark:text-primary-200',
|
||||
)}
|
||||
>
|
||||
{index + 1}
|
||||
</div>
|
||||
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900" />
|
||||
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900 can-override-bg" />
|
||||
</div>
|
||||
<Blocks
|
||||
{...contextProps}
|
||||
|
||||
@@ -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,8 +1,8 @@
|
||||
import { ContentRef, DocumentBlockTable } from '@gitbook/api';
|
||||
import { ContentRef, ContentRefUser, DocumentBlockTable } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
import { Checkbox, Emoji } from '@/components/primitives';
|
||||
import { Checkbox } from '@/components/primitives';
|
||||
import { StyledLink } from '@/components/primitives';
|
||||
import { Image } from '@/components/utils';
|
||||
import { getNodeFragmentByName } from '@/lib/document';
|
||||
@@ -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>
|
||||
|
||||
@@ -1,44 +1,43 @@
|
||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import React from 'react';
|
||||
|
||||
import { RecordColumnValue } from './RecordColumnValue';
|
||||
import { TableRecordKV, TableViewProps } from './Table';
|
||||
import styles from './table.module.css';
|
||||
import { getColumnWidth } from './ViewGrid';
|
||||
|
||||
export async function RecordRow(
|
||||
export function RecordRow(
|
||||
props: TableViewProps<DocumentTableViewGrid> & {
|
||||
record: TableRecordKV;
|
||||
autoSizedColumns: string[];
|
||||
fixedColumns: string[];
|
||||
},
|
||||
) {
|
||||
const { view } = props;
|
||||
const columnsLengthThreshold = view.columns.length >= 7;
|
||||
|
||||
const tableTR = columnsLengthThreshold
|
||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
||||
: ['[&>*+*]:border-l', '[&>*+*]:pl-4'];
|
||||
const { view, autoSizedColumns, fixedColumns } = props;
|
||||
|
||||
return (
|
||||
<tr className={tcls(tableTR, 'border-dark/3', 'dark:border-light/2')}>
|
||||
<div className={styles.row} role="row">
|
||||
{view.columns.map((column) => {
|
||||
const columnWidth = getColumnWidth({
|
||||
column,
|
||||
columnWidths: view.columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
});
|
||||
return (
|
||||
<td
|
||||
<div
|
||||
key={column}
|
||||
className={tcls(
|
||||
'align-middle',
|
||||
'min-w-[8rem]',
|
||||
'border-dark/2',
|
||||
'py-3',
|
||||
'text-sm',
|
||||
'lg:text-base',
|
||||
'dark:border-light/2',
|
||||
)}
|
||||
role="cell"
|
||||
className={styles.cell}
|
||||
style={{
|
||||
width: columnWidth,
|
||||
minWidth: columnWidth || '100px',
|
||||
}}
|
||||
>
|
||||
<div className={tcls('pr-4 ', 'text-balance')}>
|
||||
<RecordColumnValue key={column} {...props} column={column} />
|
||||
</div>
|
||||
</td>
|
||||
<RecordColumnValue {...props} column={column} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||
import * as React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
@@ -7,159 +8,113 @@ import { TableViewProps } from './Table';
|
||||
import styles from './table.module.css';
|
||||
import { getColumnAlignment } from './utils';
|
||||
|
||||
/* Columns are sized in 3 ways:
|
||||
1. Set to auto-size by default, these columns share the available width
|
||||
2. Explicitly set by the user by dragging column separator (we then turn off auto-size)
|
||||
3. Auto-size is turned off without setting a width, we then default to a fixed width of 100px
|
||||
*/
|
||||
export function ViewGrid(props: TableViewProps<DocumentTableViewGrid>) {
|
||||
const { block, view, records, style } = props;
|
||||
const columnsOverThreshold = view.columns.length >= 7;
|
||||
|
||||
const tableWrapper = columnsOverThreshold
|
||||
? [
|
||||
// has over X columns
|
||||
'overflow-x-auto',
|
||||
'overflow-y-hidden',
|
||||
'mx-auto',
|
||||
'rounded-md',
|
||||
'border',
|
||||
'border-dark/3',
|
||||
'dark:border-light/2',
|
||||
]
|
||||
: ['overflow-x-auto', 'overflow-y-hidden', 'mx-auto'];
|
||||
/* Calculate how many columns are auto-sized vs fixed width */
|
||||
const columnWidths = view.columnWidths;
|
||||
const autoSizedColumns = view.columns.filter((column) => !columnWidths?.[column]);
|
||||
const fixedColumns = view.columns.filter((column) => columnWidths?.[column]);
|
||||
|
||||
const tableTR = columnsOverThreshold
|
||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
||||
: ['[&>*+*]:border-l', '[&>*+*]:px-4'];
|
||||
const tableWidth = autoSizedColumns.length > 0 ? 'w-full' : 'w-fit';
|
||||
|
||||
const tableTH = columnsOverThreshold ? ['py-3'] : ['py-1', 'pt-0'];
|
||||
|
||||
// Only show the header when configured and not empty
|
||||
/* Only show the header when configured and not empty */
|
||||
const withHeader =
|
||||
!view.hideHeader &&
|
||||
view.columns.some((columnId) => block.data.definition[columnId].title.trim().length > 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${tcls(style, 'relative', 'grid', tableWrapper, styles.progressContainer)}`}
|
||||
>
|
||||
{/* ProgressScroller: */}
|
||||
<div
|
||||
className={`${styles.progressOpacitySharp} ${tcls(
|
||||
'grid',
|
||||
'items-center',
|
||||
'grid-area-1-1',
|
||||
'w-[5rem]',
|
||||
'h-full',
|
||||
'top-0',
|
||||
'z-[1]',
|
||||
'sticky',
|
||||
'left-[calc(100%-5rem)]',
|
||||
'pointer-events-none',
|
||||
)}`}
|
||||
>
|
||||
<svg
|
||||
className={`${styles.progressSvg} ${tcls(
|
||||
'grid-area-1-1',
|
||||
'relative',
|
||||
'[strokeDasharray:_0_100]',
|
||||
'z-[1]',
|
||||
'w-7',
|
||||
'mt-3',
|
||||
'mr-3',
|
||||
'self-start',
|
||||
'justify-self-end',
|
||||
'stroke-primary-600',
|
||||
'shadow-1xs',
|
||||
'bg-light',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'rounded-full',
|
||||
'ring-dark/2',
|
||||
'dark:ring-light/2',
|
||||
'dark:bg-dark',
|
||||
'dark:stroke-primary-400',
|
||||
)}`}
|
||||
preserveAspectRatio="xMaxYMid meet"
|
||||
width="100%"
|
||||
viewBox="0 0 26 26"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<circle
|
||||
cx="13"
|
||||
className={`${styles.strokeOpacityProgressInverted}`}
|
||||
cy="13"
|
||||
r="12.5"
|
||||
fill="none"
|
||||
stroke="inherit"
|
||||
strokeWidth="1.5"
|
||||
pathLength="100"
|
||||
strokeLinecap="round"
|
||||
strokeOpacity={0}
|
||||
/>
|
||||
|
||||
<path
|
||||
strokeDasharray="none"
|
||||
d="M12 10L15 13L12 16"
|
||||
stroke="inherit"
|
||||
fill="none"
|
||||
strokeOpacity={0.64}
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<div
|
||||
className={`${styles.progressOpacity} ${tcls(
|
||||
'bg-gradient-to-r',
|
||||
'from-transparent',
|
||||
'to-light',
|
||||
'to-40%',
|
||||
'grid-area-1-1',
|
||||
'w-full',
|
||||
'h-full',
|
||||
'dark:from-transparent',
|
||||
'dark:to-dark/10',
|
||||
)}`}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
{/* Table: */}
|
||||
<table className={tcls('w-full', 'grid-area-1-1', 'table-auto')}>
|
||||
{withHeader ? (
|
||||
<thead>
|
||||
<tr className={tcls(tableTR)}>
|
||||
<div className={tcls(style, styles.tableWrapper)}>
|
||||
{/* Table */}
|
||||
<div role="table" className={tcls('flex', 'flex-col')}>
|
||||
{/* Header */}
|
||||
{withHeader && (
|
||||
<div
|
||||
role="rowgroup"
|
||||
className={tcls(
|
||||
tableWidth,
|
||||
styles.rowGroup,
|
||||
'straight-corners:rounded-none',
|
||||
)}
|
||||
>
|
||||
<div role="row" className={tcls('flex', 'w-full')}>
|
||||
{view.columns.map((column) => {
|
||||
const columnWidth = view.columnWidths?.[column];
|
||||
const alignment = getColumnAlignment(block.data.definition[column]);
|
||||
|
||||
return (
|
||||
<th
|
||||
<div
|
||||
key={column}
|
||||
role="columnheader"
|
||||
className={tcls(
|
||||
tableTH,
|
||||
'align-middle',
|
||||
'text-balance',
|
||||
'border-b',
|
||||
'border-b-dark/5',
|
||||
'text-left',
|
||||
'text-xs',
|
||||
'lg:text-base',
|
||||
'dark:border-l-light/2',
|
||||
'dark:border-b-light/4',
|
||||
styles.columnHeader,
|
||||
alignment === 'right' ? 'text-right' : null,
|
||||
alignment === 'center' ? 'text-center' : null,
|
||||
)}
|
||||
style={columnWidth ? { width: columnWidth } : undefined}
|
||||
style={{
|
||||
width: getColumnWidth({
|
||||
column,
|
||||
columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
}),
|
||||
minWidth: columnWidths?.[column] || '100px',
|
||||
}}
|
||||
title={block.data.definition[column].title}
|
||||
>
|
||||
{block.data.definition[column].title}
|
||||
</th>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
) : null}
|
||||
<tbody className={tcls('[&>*+*]:border-t')}>
|
||||
{records.map((record) => {
|
||||
return <RecordRow key={record[0]} {...props} record={record} />;
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
role="rowgroup"
|
||||
className={tcls('flex', 'flex-col', tableWidth, '[&>*+*]:border-t')}
|
||||
>
|
||||
{records.map((record) => (
|
||||
<RecordRow
|
||||
key={record[0]}
|
||||
record={record}
|
||||
autoSizedColumns={autoSizedColumns}
|
||||
fixedColumns={fixedColumns}
|
||||
{...props}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const getColumnWidth = ({
|
||||
column,
|
||||
columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
}: {
|
||||
column: string;
|
||||
columnWidths: Record<string, number> | undefined;
|
||||
autoSizedColumns: string[];
|
||||
fixedColumns: string[];
|
||||
}) => {
|
||||
const columnWidth = columnWidths?.[column];
|
||||
|
||||
/* Column was explicitly set by user or user turned off auto-sizing (in that case, columnWidth should've also been set to 100px) */
|
||||
if (columnWidth) return `${columnWidth}px`;
|
||||
|
||||
/* Fallback minimum width for columns, so the columns don't become unreadable from being too narrow and instead table will become scrollable. */
|
||||
const minAutoColumnWidth = '100px';
|
||||
|
||||
const totalFixedWidth = fixedColumns.reduce((sum, col) => {
|
||||
return sum + (columnWidths?.[col] || 0);
|
||||
}, 0);
|
||||
|
||||
/* Column should use auto-sizing, which means it grows to fill available space */
|
||||
const availableWidth = `calc((100% - ${totalFixedWidth}px) / ${autoSizedColumns.length})`;
|
||||
return `clamp(${minAutoColumnWidth}, ${availableWidth}, 100%)`;
|
||||
};
|
||||
|
||||
@@ -1,87 +1,59 @@
|
||||
/* Hide it on browsers (firefox / safari) that do not support it */
|
||||
.progressOpacitySharp {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@supports (animation-timeline: scroll()) {
|
||||
.progressContainer {
|
||||
scroll-timeline-name: --squareTimeline;
|
||||
scroll-timeline-axis: x;
|
||||
}
|
||||
|
||||
.progressOpacity {
|
||||
animation-name: opacityProgress;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.progressOpacitySharp {
|
||||
display: grid;
|
||||
opacity: 0;
|
||||
animation-name: opacityProgressSharp;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.strokeOpacityProgressInverted {
|
||||
animation-name: strokeOpacityProgressInverted;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.progressSvg {
|
||||
animation-name: svgProgress;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
@keyframes opacityProgress {
|
||||
0%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes opacityProgressSharp {
|
||||
0%,
|
||||
98% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes strokeOpacityProgressInverted {
|
||||
0%,
|
||||
10% {
|
||||
stroke-opacity: 0;
|
||||
}
|
||||
30% {
|
||||
stroke-opacity: 0.88;
|
||||
}
|
||||
100% {
|
||||
stroke-opacity: 0.88;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes svgProgress {
|
||||
from {
|
||||
stroke-dasharray: 0 100;
|
||||
}
|
||||
to {
|
||||
stroke-dasharray: 100 100;
|
||||
}
|
||||
/* Detect whether a scrollbar exists on the table */
|
||||
@keyframes detect-scroll {
|
||||
from,
|
||||
to {
|
||||
--can-scroll: ;
|
||||
}
|
||||
}
|
||||
|
||||
/* Apply styles to the Table if scrollbar exists */
|
||||
.tableWrapper {
|
||||
animation: detect-scroll linear;
|
||||
animation-timeline: scroll(self x);
|
||||
|
||||
--border-radius-if-can-scroll: var(--can-scroll) 0.375rem;
|
||||
--border-radius-if-cant-scroll: 0;
|
||||
border-radius: var(--border-radius-if-can-scroll, var(--border-radius-if-cant-scroll));
|
||||
|
||||
--border-width-if-can-scroll: var(--can-scroll) 1px;
|
||||
--border-width-if-cant-scroll: 0;
|
||||
border-width: var(--border-width-if-can-scroll, var(--border-width-if-cant-scroll));
|
||||
|
||||
@apply relative grid w-full overflow-x-auto overflow-y-hidden mx-auto border-dark/3;
|
||||
}
|
||||
|
||||
:global(.dark) .tableWrapper {
|
||||
@apply border-tint-50;
|
||||
}
|
||||
|
||||
.columnHeader {
|
||||
@apply text-sm font-medium py-3 px-4 text-tint-900;
|
||||
}
|
||||
|
||||
:global(.dark) .columnHeader {
|
||||
@apply text-white;
|
||||
}
|
||||
|
||||
.row {
|
||||
@apply flex border-tint-700/2;
|
||||
}
|
||||
|
||||
:global(.dark) .row {
|
||||
@apply border-tint-300/3;
|
||||
}
|
||||
|
||||
.rowGroup {
|
||||
@apply flex flex-col border rounded-lg bg-tint-800/1 border-tint-700/2;
|
||||
}
|
||||
|
||||
:global(.dark) .rowGroup {
|
||||
@apply bg-tint-300/2 border-tint-300/3;
|
||||
}
|
||||
|
||||
.cell {
|
||||
@apply flex-1 align-middle border-dark/2 py-2 px-4 text-sm;
|
||||
}
|
||||
|
||||
:global(.dark) .cell {
|
||||
@apply border-light/2;
|
||||
}
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
export * from './DocumentView';
|
||||
export { createHighlightingContext } from './CodeBlock';
|
||||
|
||||
@@ -6,46 +6,44 @@ import {
|
||||
} from '@gitbook/api';
|
||||
import { assertNever } from 'assert-never';
|
||||
|
||||
import { ClassValue } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
* Get the line height of a block
|
||||
*/
|
||||
export function getBlockTextStyle(block: DocumentBlock): {
|
||||
/** Tailwind class for the text size */
|
||||
textSize: ClassValue;
|
||||
textSize: string;
|
||||
/** Tailwind class for the height (h-*) */
|
||||
lineHeight: ClassValue;
|
||||
lineHeight: string;
|
||||
/** Tailwind class for the margin top (mt-*) */
|
||||
marginTop?: ClassValue;
|
||||
marginTop?: string;
|
||||
} {
|
||||
switch (block.type) {
|
||||
case 'paragraph':
|
||||
return {
|
||||
textSize: ['text-base'],
|
||||
textSize: 'text-base',
|
||||
lineHeight: 'leading-normal',
|
||||
};
|
||||
case 'heading-1':
|
||||
return {
|
||||
textSize: ['text-3xl', 'font-semibold'],
|
||||
textSize: 'text-3xl font-semibold',
|
||||
lineHeight: 'leading-tight',
|
||||
marginTop: '[margin-top:_1em]',
|
||||
marginTop: 'mt-[1em]',
|
||||
};
|
||||
case 'heading-2':
|
||||
return {
|
||||
textSize: ['text-2xl', 'font-semibold'],
|
||||
textSize: 'text-2xl font-semibold',
|
||||
lineHeight: 'leading-snug',
|
||||
marginTop: '[margin-top:_0.75em]',
|
||||
marginTop: 'mt-[0.75em]',
|
||||
};
|
||||
case 'heading-3':
|
||||
return {
|
||||
textSize: ['text-base', 'font-semibold'],
|
||||
textSize: 'text-base font-semibold',
|
||||
lineHeight: 'leading-snug',
|
||||
marginTop: '[margin-top:_0.5em]',
|
||||
marginTop: 'mt-[0.5em]',
|
||||
};
|
||||
case 'divider':
|
||||
return {
|
||||
textSize: [],
|
||||
textSize: '',
|
||||
lineHeight: 'leading-none',
|
||||
};
|
||||
case 'list-ordered':
|
||||
@@ -56,7 +54,7 @@ export function getBlockTextStyle(block: DocumentBlock): {
|
||||
return getBlockTextStyle(block.nodes[0]);
|
||||
default:
|
||||
return {
|
||||
textSize: ['text-base'],
|
||||
textSize: 'text-base',
|
||||
lineHeight: 'leading-normal',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export function FooterLinksGroup(props: {
|
||||
|
||||
return (
|
||||
<div className={tcls('flex', 'flex-col', 'gap-3')}>
|
||||
<p className={tcls('text-base', 'font-medium')}>{group.title}</p>
|
||||
<p className={tcls('text-base', 'font-semibold')}>{group.title}</p>
|
||||
{group.links.map((link, index) => {
|
||||
return <FooterLink key={index} link={link} context={context} />;
|
||||
})}
|
||||
@@ -32,7 +32,18 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
|
||||
return (
|
||||
<Link
|
||||
href={resolved.href}
|
||||
className={tcls('text-sm', 'text-primary-400', 'hover:text-primary-500')}
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'font-normal',
|
||||
'text-dark/8',
|
||||
'hover:text-dark/9',
|
||||
'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>>,
|
||||
@@ -25,7 +25,7 @@ export function Dropdown<E extends HTMLElement>(props: {
|
||||
const dropdownId = useId();
|
||||
|
||||
return (
|
||||
<div className={tcls('group/dropdown', 'relative flex')}>
|
||||
<div className={tcls('group/dropdown', 'relative flex shrink min-w-0')}>
|
||||
{button({
|
||||
id: dropdownId,
|
||||
tabIndex: 0,
|
||||
@@ -39,12 +39,12 @@ export function Dropdown<E extends HTMLElement>(props: {
|
||||
aria-labelledby={dropdownId}
|
||||
className={tcls(
|
||||
'w-52',
|
||||
'max-h-56',
|
||||
'max-h-80',
|
||||
'flex',
|
||||
'absolute',
|
||||
'top-full',
|
||||
'left-0',
|
||||
'z-10',
|
||||
'z-20',
|
||||
'origin-top-left',
|
||||
'invisible',
|
||||
'transition-opacity',
|
||||
@@ -82,11 +82,12 @@ export function Dropdown<E extends HTMLElement>(props: {
|
||||
/**
|
||||
* Animated chevron to display in the dropdown button.
|
||||
*/
|
||||
export function DropdownChevron(props: {}) {
|
||||
export function DropdownChevron() {
|
||||
return (
|
||||
<Icon
|
||||
icon="chevron-down"
|
||||
className={tcls(
|
||||
'shrink-0',
|
||||
'opacity-6',
|
||||
'size-3',
|
||||
'ms-1',
|
||||
@@ -109,32 +110,42 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
|
||||
/**
|
||||
* Menu item in a dropdown.
|
||||
*/
|
||||
export function DropdownMenuItem(props: {
|
||||
href: string;
|
||||
active?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { children, active = false, href } = 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,
|
||||
'hover:bg-dark/2 dark:hover:bg-light/2',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
prefetch={false}
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'text-sm',
|
||||
'px-3',
|
||||
'py-1',
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
active
|
||||
? ['bg-primary/3', 'dark:bg-light/2', 'text-primary-600']
|
||||
: ['hover:bg-dark/2', 'dark:hover:bg-light/2'],
|
||||
'text-xs px-3 py-1 font-medium text-dark/8 dark:text-light/8',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
import {
|
||||
CustomizationSettings,
|
||||
Site,
|
||||
SiteCustomizationSettings,
|
||||
SiteSection,
|
||||
Space,
|
||||
} from '@gitbook/api';
|
||||
import { CustomizationSettings, Site, SiteCustomizationSettings, Space } from '@gitbook/api';
|
||||
import { CustomizationHeaderPreset } from '@gitbook/api';
|
||||
import { Suspense } from 'react';
|
||||
|
||||
import { CONTAINER_STYLE, HEADER_HEIGHT_DESKTOP } from '@/components/layout';
|
||||
import { t, getSpaceLanguage } from '@/intl/server';
|
||||
import type { SectionsList } from '@/lib/api';
|
||||
import { ContentRefContext } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
@@ -20,6 +15,7 @@ import { HeaderLogo } from './HeaderLogo';
|
||||
import { SpacesDropdown } from './SpacesDropdown';
|
||||
import { SearchButton } from '../Search';
|
||||
import { SiteSectionTabs } from '../SiteSectionTabs';
|
||||
import { HeaderMobileMenu } from './HeaderMobileMenu';
|
||||
/**
|
||||
* Render the header for the space.
|
||||
*/
|
||||
@@ -27,14 +23,12 @@ export function Header(props: {
|
||||
space: Space;
|
||||
site: Site | null;
|
||||
spaces: Space[];
|
||||
sections: { list: SiteSection[]; section: SiteSection } | null;
|
||||
sections: SectionsList | null;
|
||||
context: ContentRefContext;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
withTopHeader?: boolean;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
const { children, context, space, site, spaces, sections, customization, withTopHeader } =
|
||||
props;
|
||||
const { context, space, site, spaces, sections, customization, withTopHeader } = props;
|
||||
const isCustomizationDefault =
|
||||
customization.header.preset === CustomizationHeaderPreset.Default;
|
||||
const hasSiteSections = sections && sections.list.length > 1;
|
||||
@@ -52,109 +46,179 @@ export function Header(props: {
|
||||
'w-full',
|
||||
'flex-none',
|
||||
'shadow-thinbottom',
|
||||
'dark:shadow-light/2',
|
||||
'bg-light',
|
||||
'dark:bg-dark',
|
||||
withTopHeader ? null : 'lg:hidden',
|
||||
'lg:z-10',
|
||||
'dark:shadow-light/1',
|
||||
`${isCustomizationDefault || !withTopHeader ? 'bg-light' : 'bg-header-background'}`,
|
||||
`${
|
||||
isCustomizationDefault || !withTopHeader
|
||||
? 'dark:bg-dark'
|
||||
: 'bg-header-background'
|
||||
}`,
|
||||
'text-sm',
|
||||
'bg-opacity-9',
|
||||
'dark:bg-opacity-9',
|
||||
'backdrop-blur-lg',
|
||||
'contrast-more:bg-opacity-11',
|
||||
'contrast-more:dark:bg-opacity-11',
|
||||
)}
|
||||
>
|
||||
<div className={tcls('scroll-nojump')}>
|
||||
<div
|
||||
className={tcls(
|
||||
'gap-4',
|
||||
'grid',
|
||||
'grid-flow-col',
|
||||
'auto-cols-[auto_auto_1fr_auto]',
|
||||
'h-16',
|
||||
'items-center',
|
||||
'align-center',
|
||||
'justify-between',
|
||||
'w-full',
|
||||
CONTAINER_STYLE,
|
||||
)}
|
||||
>
|
||||
<HeaderLogo site={site} space={space} customization={customization} />
|
||||
<span>
|
||||
{!hasSiteSections && isMultiVariants ? (
|
||||
<SpacesDropdown space={space} spaces={spaces} />
|
||||
) : null}
|
||||
</span>
|
||||
<HeaderLinks>
|
||||
{customization.header.links.map((link, index) => {
|
||||
return (
|
||||
<HeaderLink
|
||||
key={index}
|
||||
link={link}
|
||||
<div
|
||||
className={tcls(
|
||||
!isCustomizationDefault &&
|
||||
withTopHeader && [
|
||||
'bg-header-background',
|
||||
'shadow-thinbottom',
|
||||
'dark:shadow-light/2',
|
||||
],
|
||||
)}
|
||||
>
|
||||
<div className={tcls('scroll-nojump')}>
|
||||
<div
|
||||
className={tcls(
|
||||
'gap-4',
|
||||
'lg:gap-8',
|
||||
'flex',
|
||||
'h-16',
|
||||
'items-center',
|
||||
'justify-between',
|
||||
'w-full',
|
||||
CONTAINER_STYLE,
|
||||
)}
|
||||
>
|
||||
<div className="flex max-w-full shrink min-w-0 gap-2 lg:gap-4 justify-start items-center">
|
||||
<HeaderMobileMenu
|
||||
className={tcls(
|
||||
'lg:hidden',
|
||||
'-ml-2',
|
||||
customization.header.preset ===
|
||||
CustomizationHeaderPreset.Default
|
||||
? ['text-dark', 'dark:text-light']
|
||||
: 'text-header-link',
|
||||
)}
|
||||
/>
|
||||
<HeaderLogo site={site} space={space} customization={customization} />
|
||||
{!hasSiteSections && isMultiVariants ? (
|
||||
<div className="z-20 shrink hidden sm:block">
|
||||
<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>
|
||||
|
||||
{customization.header.links.length > 0 && (
|
||||
<HeaderLinks>
|
||||
{customization.header.links.map((link, index) => {
|
||||
return (
|
||||
<HeaderLink
|
||||
key={index}
|
||||
link={link}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<HeaderLinkMore
|
||||
label={t(getSpaceLanguage(customization), 'more')}
|
||||
links={customization.header.links}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<HeaderLinkMore
|
||||
label={t(getSpaceLanguage(customization), 'more')}
|
||||
links={customization.header.links}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
</HeaderLinks>
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'md:w-56',
|
||||
'grow-0',
|
||||
'shrink-0',
|
||||
'justify-self-end',
|
||||
</HeaderLinks>
|
||||
)}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<SearchButton
|
||||
style={
|
||||
!isCustomizationDefault && withTopHeader
|
||||
? [
|
||||
'bg-header-link/3',
|
||||
'shadow-sm',
|
||||
'ring-header-link/3',
|
||||
'[&>span]:!text-header-link/7',
|
||||
'[&_svg]:text-header-link',
|
||||
'contrast-more:bg-transparent',
|
||||
'contrast-more:ring-header-link',
|
||||
'contrast-more:[&>span]:!text-header-link',
|
||||
'dark:bg-header-link/3',
|
||||
'dark:ring-header-link/3',
|
||||
'[&>span]:!text-header-link/7',
|
||||
'dark:[&_svg]:text-header-link',
|
||||
'dark:contrast-more:bg-transparent',
|
||||
'dark:contrast-more:ring-header-link',
|
||||
'dark:contrast-more:[&>span]:!text-header-link',
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<span className={tcls('flex-1')}>
|
||||
{t(
|
||||
getSpaceLanguage(customization),
|
||||
customization.aiSearch.enabled ? 'search_or_ask' : 'search',
|
||||
)}
|
||||
</span>
|
||||
</SearchButton>
|
||||
</Suspense>
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'md:min-w-56',
|
||||
'grow-0',
|
||||
'shrink-0',
|
||||
'justify-self-end',
|
||||
)}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<SearchButton
|
||||
style={
|
||||
!isCustomizationDefault && withTopHeader
|
||||
? [
|
||||
'bg-header-link/2',
|
||||
'dark:bg-header-link/2',
|
||||
'hover:bg-header-link/3',
|
||||
'dark:hover:bg-header-link/3',
|
||||
|
||||
'text-header-link/8',
|
||||
'dark:text-header-link/8',
|
||||
'hover:text-header-link',
|
||||
'dark:hover:text-header-link',
|
||||
|
||||
'ring-header-link/4',
|
||||
'dark:ring-header-link/4',
|
||||
'hover:ring-header-link/5',
|
||||
'dark:hover:ring-header-link/5',
|
||||
|
||||
'[&_svg]:text-header-link/10',
|
||||
'dark:[&_svg]:text-header-link/10',
|
||||
'[&_.shortcut]:text-header-link/8',
|
||||
'dark:[&_.shortcut]:text-header-link/8',
|
||||
|
||||
'contrast-more:bg-header-background',
|
||||
'contrast-more:text-header-link',
|
||||
'contrast-more:ring-header-link',
|
||||
'contrast-more:hover:bg-header-background',
|
||||
'contrast-more:hover:ring-header-link',
|
||||
'contrast-more:focus:text-header-link',
|
||||
'contrast-more:focus:bg-header-background',
|
||||
'contrast-more:focus:ring-header-link',
|
||||
'dark:contrast-more:bg-header-background',
|
||||
'dark:contrast-more:text-header-link',
|
||||
'dark:contrast-more:ring-header-link',
|
||||
'dark:contrast-more:hover:bg-header-background',
|
||||
'dark:contrast-more:hover:ring-header-link',
|
||||
'dark:contrast-more:focus:text-header-link',
|
||||
'dark:contrast-more:focus:bg-header-background',
|
||||
'dark:contrast-more:focus:ring-header-link',
|
||||
|
||||
'shadow-none',
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<span className={tcls('flex-1')}>
|
||||
{t(
|
||||
getSpaceLanguage(customization),
|
||||
customization.aiSearch.enabled
|
||||
? 'search_or_ask'
|
||||
: 'search',
|
||||
)}
|
||||
...
|
||||
</span>
|
||||
</SearchButton>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{sections ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark z-[9] mt-0.5',
|
||||
'scroll-nojump',
|
||||
'w-full',
|
||||
// Handle long section tabs, particularly on smaller screens.
|
||||
'overflow-x-auto hide-scroll',
|
||||
)}
|
||||
>
|
||||
<div className={tcls(CONTAINER_STYLE)}>
|
||||
<SiteSectionTabs sections={sections.list} section={sections.section} />
|
||||
</div>
|
||||
<SiteSectionTabs {...sections} />
|
||||
</div>
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {
|
||||
CustomizationContentLink,
|
||||
CustomizationHeaderLink,
|
||||
CustomizationSettings,
|
||||
CustomizationHeaderPreset,
|
||||
SiteCustomizationSettings,
|
||||
CustomizationHeaderItem,
|
||||
ContentRef,
|
||||
} from '@gitbook/api';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
@@ -21,93 +22,42 @@ import { Button, Link } from '../primitives';
|
||||
|
||||
export async function HeaderLink(props: {
|
||||
context: ContentRefContext;
|
||||
link: CustomizationHeaderLink;
|
||||
link: CustomizationHeaderItem;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
}) {
|
||||
const { context, link, customization } = props;
|
||||
|
||||
const target = await resolveContentRef(link.to, context);
|
||||
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const target = link.to ? await resolveContentRef(link.to, context) : null;
|
||||
const headerPreset = customization.header.preset;
|
||||
|
||||
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => {
|
||||
const linkStyle = link.style ?? 'link';
|
||||
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
case 'button-primary': {
|
||||
const variant = (() => {
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
return 'secondary';
|
||||
case 'button-primary':
|
||||
return 'primary';
|
||||
default:
|
||||
assertNever(linkStyle);
|
||||
}
|
||||
})();
|
||||
return (
|
||||
<Button
|
||||
href={target.href}
|
||||
variant={variant}
|
||||
size="medium"
|
||||
className={tcls(
|
||||
{
|
||||
'button-primary':
|
||||
headerPreset === CustomizationHeaderPreset.Custom ||
|
||||
headerPreset === CustomizationHeaderPreset.Bold
|
||||
? tcls(
|
||||
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
|
||||
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
|
||||
)
|
||||
: null,
|
||||
'button-secondary': tcls(
|
||||
'bg:transparent hover:bg-transparent',
|
||||
'dark:bg-transparent dark:hover:bg-transparent',
|
||||
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
|
||||
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
|
||||
),
|
||||
}[linkStyle],
|
||||
)}
|
||||
>
|
||||
{link.title}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
case 'link': {
|
||||
return (
|
||||
<Link
|
||||
{...linkProps}
|
||||
href={target.href}
|
||||
className={tcls(
|
||||
'overflow-hidden',
|
||||
'text-sm lg:text-base',
|
||||
'flex flex-row items-center',
|
||||
'whitespace-nowrap',
|
||||
'hover:text-header-link-400 dark:hover:text-light',
|
||||
|
||||
headerPreset === CustomizationHeaderPreset.Default
|
||||
? ['text-dark/8', 'dark:text-light/8']
|
||||
: ['text-header-link-500 hover:text-header-link-400'],
|
||||
)}
|
||||
>
|
||||
<span className={tcls('truncate')}>{link.title}</span>
|
||||
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
default:
|
||||
assertNever(linkStyle);
|
||||
}
|
||||
};
|
||||
const linkStyle = link.style ?? 'link';
|
||||
|
||||
if (link.links && link.links.length > 0) {
|
||||
return (
|
||||
<Dropdown button={renderLink}>
|
||||
<Dropdown
|
||||
className="shrink"
|
||||
button={(buttonProps) => {
|
||||
if (!target || !link.to) {
|
||||
return (
|
||||
<HeaderItemDropdown
|
||||
{...buttonProps}
|
||||
headerPreset={headerPreset}
|
||||
title={link.title}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<HeaderLinkNavItem
|
||||
{...buttonProps}
|
||||
linkTarget={link.to}
|
||||
linkStyle={linkStyle}
|
||||
headerPreset={headerPreset}
|
||||
title={link.title}
|
||||
isDropdown
|
||||
href={target?.href}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
>
|
||||
<DropdownMenu>
|
||||
{link.links.map((subLink, index) => (
|
||||
<SubHeaderLink key={index} {...props} link={subLink} />
|
||||
@@ -117,7 +67,140 @@ export async function HeaderLink(props: {
|
||||
);
|
||||
}
|
||||
|
||||
return renderLink({});
|
||||
if (!target || !link.to) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<HeaderLinkNavItem
|
||||
linkTarget={link.to}
|
||||
linkStyle={linkStyle}
|
||||
headerPreset={headerPreset}
|
||||
title={link.title}
|
||||
isDropdown={false}
|
||||
href={target.href}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export type HeaderLinkNavItemProps = {
|
||||
linkTarget: ContentRef;
|
||||
linkStyle: NonNullable<CustomizationHeaderItem['style']>;
|
||||
headerPreset: CustomizationHeaderPreset;
|
||||
title: string;
|
||||
href: string;
|
||||
isDropdown: boolean;
|
||||
} & DropdownButtonProps<HTMLElement>;
|
||||
|
||||
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
|
||||
const { linkStyle, ...rest } = props;
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
case 'button-primary':
|
||||
return <HeaderItemButton {...rest} linkStyle={linkStyle} />;
|
||||
case 'link':
|
||||
return <HeaderItemLink {...rest} />;
|
||||
default:
|
||||
assertNever(linkStyle);
|
||||
}
|
||||
}
|
||||
|
||||
function HeaderItemButton(
|
||||
props: Omit<HeaderLinkNavItemProps, 'linkStyle'> & {
|
||||
linkStyle: 'button-secondary' | 'button-primary';
|
||||
},
|
||||
) {
|
||||
const { linkTarget, linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
|
||||
const variant = (() => {
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
return 'secondary';
|
||||
case 'button-primary':
|
||||
return 'primary';
|
||||
default:
|
||||
assertNever(linkStyle);
|
||||
}
|
||||
})();
|
||||
return (
|
||||
<Button
|
||||
href={href}
|
||||
variant={variant}
|
||||
size="medium"
|
||||
className={tcls(
|
||||
{
|
||||
'button-primary':
|
||||
headerPreset === CustomizationHeaderPreset.Custom ||
|
||||
headerPreset === CustomizationHeaderPreset.Bold
|
||||
? tcls(
|
||||
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
|
||||
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
|
||||
)
|
||||
: null,
|
||||
'button-secondary': tcls(
|
||||
'bg:transparent hover:bg-transparent',
|
||||
'dark:bg-transparent dark:hover:bg-transparent',
|
||||
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
|
||||
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
|
||||
),
|
||||
}[linkStyle],
|
||||
)}
|
||||
insights={{
|
||||
target: linkTarget,
|
||||
position: 'header',
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{title}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
|
||||
return tcls(
|
||||
'flex items-center shrink',
|
||||
'hover:text-header-link-400 dark:hover:text-light',
|
||||
'min-w-0',
|
||||
|
||||
props.headerPreset === CustomizationHeaderPreset.Default
|
||||
? ['text-dark/8', 'dark:text-light/8']
|
||||
: ['text-header-link-500 hover:text-header-link-400'],
|
||||
);
|
||||
}
|
||||
|
||||
function HeaderItemLink(props: Omit<HeaderLinkNavItemProps, 'linkStyle'>) {
|
||||
const { linkTarget, headerPreset, title, isDropdown, href, ...rest } = props;
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className={getHeaderLinkClassName({ headerPreset })}
|
||||
insights={{
|
||||
target: linkTarget,
|
||||
position: 'header',
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
<span className="truncate min-w-0">{title}</span>
|
||||
{isDropdown ? <DropdownChevron /> : null}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function HeaderItemDropdown(
|
||||
props: {
|
||||
headerPreset: CustomizationHeaderPreset;
|
||||
title: string;
|
||||
} & DropdownButtonProps<HTMLElement>,
|
||||
) {
|
||||
const { headerPreset, title, ...rest } = props;
|
||||
return (
|
||||
<span
|
||||
className={tcls(getHeaderLinkClassName({ headerPreset }), 'cursor-default')}
|
||||
{...rest}
|
||||
>
|
||||
{title}
|
||||
<DropdownChevron />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
async function SubHeaderLink(props: {
|
||||
@@ -132,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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CustomizationHeaderLink,
|
||||
CustomizationContentLink,
|
||||
CustomizationHeaderItem,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationSettings,
|
||||
SiteCustomizationSettings,
|
||||
@@ -10,7 +11,7 @@ import React from 'react';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||
import { Dropdown, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||
import styles from './headerLinks.module.css';
|
||||
|
||||
/**
|
||||
@@ -18,7 +19,7 @@ import styles from './headerLinks.module.css';
|
||||
*/
|
||||
export function HeaderLinkMore(props: {
|
||||
label: React.ReactNode;
|
||||
links: CustomizationHeaderLink[];
|
||||
links: CustomizationHeaderItem[];
|
||||
context: ContentRefContext;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
}) {
|
||||
@@ -30,20 +31,27 @@ export function HeaderLinkMore(props: {
|
||||
const renderButton = () => (
|
||||
<button
|
||||
className={tcls(
|
||||
'px-1',
|
||||
!isCustomizationDefault
|
||||
? ['text-header-link-500']
|
||||
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
|
||||
'hover:text-header-link-400',
|
||||
isCustomizationDefault
|
||||
? [
|
||||
'text-dark/8',
|
||||
'dark:text-light/8',
|
||||
'hover:text-primary',
|
||||
'dark:hover:text-primary',
|
||||
]
|
||||
: ['text-header-link', 'hover:text-header-link/8'],
|
||||
'flex',
|
||||
'gap-1',
|
||||
'items-center',
|
||||
)}
|
||||
>
|
||||
<span className="sr-only">{label}</span>
|
||||
<Icon icon="ellipsis" className={tcls('opacity-6', 'size-3', 'ms-1')} />
|
||||
<Icon icon="ellipsis" className={tcls('size-4')} />
|
||||
<DropdownChevron />
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`${styles.linkEllipsis} items-center`}>
|
||||
<div className={`${styles.linkEllipsis} items-center z-20`}>
|
||||
<Dropdown button={renderButton} className="-translate-x-48 md:translate-x-0">
|
||||
<DropdownMenu>
|
||||
{links.map((link, index) => (
|
||||
@@ -55,14 +63,37 @@ export function HeaderLinkMore(props: {
|
||||
);
|
||||
}
|
||||
|
||||
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderLink }) {
|
||||
async function MoreMenuLink(props: {
|
||||
context: ContentRefContext;
|
||||
link: CustomizationHeaderItem | CustomizationContentLink;
|
||||
}) {
|
||||
const { context, link } = props;
|
||||
|
||||
const target = await resolveContentRef(link.to, context);
|
||||
const target = link.to ? await resolveContentRef(link.to, context) : null;
|
||||
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <DropdownMenuItem href={target.href}>{link.title}</DropdownMenuItem>;
|
||||
return (
|
||||
<>
|
||||
{'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}
|
||||
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} />
|
||||
))
|
||||
: null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export async function HeaderLinks({ children }: HeaderLinksProps) {
|
||||
<div
|
||||
className={tcls(
|
||||
styles.containerHeaderlinks,
|
||||
'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56',
|
||||
'grow shrink flex justify-end items-center gap-x-6 lg:gap-x-8 min-w-9 z-20',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -30,65 +30,51 @@ export function HeaderLogo(props: HeaderLogoProps) {
|
||||
const { customization } = props;
|
||||
|
||||
return (
|
||||
<div className={tcls('flex', 'flex-row', 'gap-2')}>
|
||||
<HeaderMobileMenu
|
||||
className={tcls(
|
||||
'lg:hidden',
|
||||
customization.header.preset === CustomizationHeaderPreset.Default
|
||||
? ['text-dark', 'dark:text-light']
|
||||
: 'text-header-link',
|
||||
)}
|
||||
/>
|
||||
<Link
|
||||
href={absoluteHref('')}
|
||||
className={tcls(
|
||||
'group/headerlogo',
|
||||
'flex-1',
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'shrink-0',
|
||||
)}
|
||||
>
|
||||
{customization.header.logo ? (
|
||||
<Image
|
||||
alt="Logo"
|
||||
sources={{
|
||||
light: {
|
||||
src: customization.header.logo.light,
|
||||
},
|
||||
dark: customization.header.logo.dark
|
||||
? {
|
||||
src: customization.header.logo.dark,
|
||||
}
|
||||
: null,
|
||||
}}
|
||||
sizes={[
|
||||
{
|
||||
media: '(max-width: 1024px)',
|
||||
width: 128,
|
||||
},
|
||||
{
|
||||
width: 192,
|
||||
},
|
||||
]}
|
||||
priority="high"
|
||||
style={tcls(
|
||||
'max-w-[8rem]',
|
||||
'lg:max-w-[12rem]',
|
||||
'max-h-[3rem]',
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
'overflow-hidden',
|
||||
'object-contain',
|
||||
'object-left',
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<LogoFallback {...props} />
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
<Link
|
||||
href={absoluteHref('')}
|
||||
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')}
|
||||
>
|
||||
{customization.header.logo ? (
|
||||
<Image
|
||||
alt="Logo"
|
||||
sources={{
|
||||
light: {
|
||||
src: customization.header.logo.light,
|
||||
},
|
||||
dark: customization.header.logo.dark
|
||||
? {
|
||||
src: customization.header.logo.dark,
|
||||
}
|
||||
: null,
|
||||
}}
|
||||
sizes={[
|
||||
{
|
||||
media: '(max-width: 1024px)',
|
||||
width: 160,
|
||||
},
|
||||
{
|
||||
width: 260,
|
||||
},
|
||||
]}
|
||||
priority="high"
|
||||
style={tcls(
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
'overflow-hidden',
|
||||
'shrink',
|
||||
'min-w-0',
|
||||
'max-w-40',
|
||||
'lg:max-w-64',
|
||||
'max-h-10',
|
||||
'lg:max-h-12',
|
||||
'h-full',
|
||||
'w-auto',
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<LogoFallback {...props} />
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -111,13 +97,13 @@ function LogoFallback(props: HeaderLogoProps) {
|
||||
className={tcls(
|
||||
'text-pretty',
|
||||
'line-clamp-3',
|
||||
'leading-[1.1]',
|
||||
'tracking-tight',
|
||||
'max-w-[18ch]',
|
||||
'lg:max-w-[24ch]',
|
||||
'lg:text-lg/tight',
|
||||
'font-semibold',
|
||||
'ms-3',
|
||||
'text-base/tight',
|
||||
'lg:text-lg/tight',
|
||||
customization.header.preset === CustomizationHeaderPreset.Default ||
|
||||
customization.header.preset === CustomizationHeaderPreset.None
|
||||
? ['text-dark', 'dark:text-light']
|
||||
|
||||
@@ -5,8 +5,8 @@ import { tcls } from '@/lib/tailwind';
|
||||
import { Dropdown, DropdownChevron, DropdownMenu } from './Dropdown';
|
||||
import { SpacesDropdownMenuItem } from './SpacesDropdownMenuItem';
|
||||
|
||||
export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
const { space, spaces } = props;
|
||||
export function SpacesDropdown(props: { space: Space; spaces: Space[]; className?: string }) {
|
||||
const { space, spaces, className } = props;
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
@@ -20,25 +20,27 @@ export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
'items-center',
|
||||
'rounded-2xl',
|
||||
'straight-corners:rounded-none',
|
||||
'bg-light-2',
|
||||
'border',
|
||||
'border-light-3',
|
||||
'text-dark-4',
|
||||
|
||||
'hover:cursor-pointer',
|
||||
'bg-dark/1',
|
||||
'dark:bg-light/1',
|
||||
|
||||
'text-sm',
|
||||
'text-dark-4',
|
||||
'dark:text-light-4',
|
||||
|
||||
'contrast-more:bg-light',
|
||||
'contrast-more:ring-1',
|
||||
'contrast-more:ring-dark',
|
||||
'dark:contrast-more:ring-light',
|
||||
'dark:contrast-more:bg-dark',
|
||||
|
||||
'px-3',
|
||||
'py-1',
|
||||
'contrast-more:border-dark',
|
||||
'contrast-more:bg-light',
|
||||
'contrast-more:text-dark',
|
||||
'dark:bg-dark-3',
|
||||
'dark:border-dark-4',
|
||||
'dark:text-light-4',
|
||||
'contrast-more:dark:border-light',
|
||||
'contrast-more:dark:bg-dark',
|
||||
'contrast-more:dark:text-light',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{space.title}
|
||||
<span className="line-clamp-2">{space.title}</span>
|
||||
<DropdownChevron />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -60,12 +60,12 @@
|
||||
}
|
||||
.containerHeaderlinks > :nth-child(n + 5) ~ .linkEllipsis {
|
||||
display: flex;
|
||||
& div > :nth-child(n + 5) {
|
||||
& div > a:nth-of-type(n + 5) {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@container headerlinks ( width < 900px ) {
|
||||
@container headerlinks ( width < 850px ) {
|
||||
.containerHeaderlinks > :nth-child(n + 6) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { Transition, motion, useReducedMotion } from 'framer-motion';
|
||||
import React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export function AnimatedLine({ transition }: { transition?: Transition }) {
|
||||
const prefersReducedMotion = useReducedMotion();
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
layout
|
||||
layoutId="sections-line"
|
||||
className={tcls([
|
||||
'border-primary',
|
||||
'border-l',
|
||||
'dark:border-primary-400',
|
||||
'h-full',
|
||||
'absolute',
|
||||
'z-20',
|
||||
'-left-[5px]',
|
||||
])}
|
||||
transition={prefersReducedMotion ? { duration: 0 } : transition}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { motion } from 'framer-motion';
|
||||
import React from 'react';
|
||||
|
||||
import { useScrollActiveId } from '@/components/hooks';
|
||||
import { DocumentSection } from '@/lib/document';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AnimatedLine } from './AnimatedLine';
|
||||
import { HEADER_HEIGHT_DESKTOP } from '../layout';
|
||||
|
||||
/**
|
||||
@@ -13,6 +14,13 @@ import { HEADER_HEIGHT_DESKTOP } from '../layout';
|
||||
*/
|
||||
const SECTION_INTERSECTING_THRESHOLD = 0.9;
|
||||
|
||||
const springCurve = {
|
||||
type: 'spring',
|
||||
stiffness: 700,
|
||||
damping: 50,
|
||||
mass: 0.8,
|
||||
};
|
||||
|
||||
export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
|
||||
const { sections } = props;
|
||||
|
||||
@@ -28,37 +36,44 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
|
||||
});
|
||||
|
||||
return (
|
||||
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'space-y-1')}>
|
||||
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'pl-1')}>
|
||||
{sections.map((section) => (
|
||||
<li key={section.id} className={tcls('flex', 'flex-row')}>
|
||||
<motion.li
|
||||
key={section.id}
|
||||
className={tcls('flex', 'flex-row', 'relative', 'h-fit')}
|
||||
>
|
||||
{activeId === section.id ? <AnimatedLine transition={springCurve} /> : null}
|
||||
<a
|
||||
href={`#${section.id}`}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'z-10',
|
||||
'w-full',
|
||||
'items-baseline',
|
||||
'left-[-1px]',
|
||||
'relative',
|
||||
'text-sm',
|
||||
'py-1',
|
||||
'ps-3',
|
||||
'hover:text-primary',
|
||||
'pe-2',
|
||||
'transition-all',
|
||||
'border-l',
|
||||
'border-transparent',
|
||||
'duration-200',
|
||||
section.depth > 1 ? ['ps-6', 'opacity-8'] : null,
|
||||
activeId === section.id
|
||||
? [
|
||||
'text-primary',
|
||||
'border-primary',
|
||||
'dark:text-primary-400',
|
||||
'dark:border-primary-400',
|
||||
'opacity-[1]',
|
||||
'[&>span]:bg-primary-400',
|
||||
'dark:[&>span]:bg-primary-600',
|
||||
'dark:[&>span]:text-dark',
|
||||
]
|
||||
: '',
|
||||
: [
|
||||
'text-neutral-500',
|
||||
'dark:text-neutral-400',
|
||||
'hover:text-neutral-900',
|
||||
'dark:hover:text-neutral-100',
|
||||
],
|
||||
)}
|
||||
>
|
||||
{section.tag ? (
|
||||
@@ -71,7 +86,7 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
|
||||
|
||||
{section.title}
|
||||
</a>
|
||||
</li>
|
||||
</motion.li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
|
||||
@@ -11,17 +11,17 @@ import { getSpaceLanguage } from '@/intl/server';
|
||||
import { t } from '@/intl/translate';
|
||||
import { ContentTarget, SiteContentPointer, api } from '@/lib/api';
|
||||
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, createHighlightingContext } from '../DocumentView';
|
||||
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
|
||||
import { TrackPageViewEvent } from '../Insights';
|
||||
import { PageFeedbackForm } from '../PageFeedback';
|
||||
import { DateRelative } from '../primitives';
|
||||
|
||||
@@ -31,17 +31,18 @@ export function PageBody(props: {
|
||||
contentTarget: ContentTarget;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
page: RevisionPageDocument;
|
||||
ancestors: AncestorRevisionPage[];
|
||||
document: JSONDocument | null;
|
||||
context: ContentRefContext;
|
||||
withPageFeedback: boolean;
|
||||
}) {
|
||||
const {
|
||||
space,
|
||||
pointer,
|
||||
contentTarget,
|
||||
customization,
|
||||
context,
|
||||
page,
|
||||
ancestors,
|
||||
document,
|
||||
withPageFeedback,
|
||||
} = props;
|
||||
@@ -49,7 +50,6 @@ export function PageBody(props: {
|
||||
const asFullWidth = document ? hasFullWidthBlock(document) : false;
|
||||
const language = getSpaceLanguage(customization);
|
||||
const updatedAt = page.updatedAt ?? page.createdAt;
|
||||
const shouldHighlightCode = createHighlightingContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -80,7 +80,7 @@ export function PageBody(props: {
|
||||
<PageCover as="hero" page={page} cover={page.cover} context={context} />
|
||||
) : null}
|
||||
|
||||
<PageHeader page={page} />
|
||||
<PageHeader page={page} ancestors={ancestors} pages={context.pages} />
|
||||
{document && !isNodeEmpty(document) ? (
|
||||
<React.Suspense
|
||||
fallback={
|
||||
@@ -100,7 +100,6 @@ export function PageBody(props: {
|
||||
contentRefContext: context,
|
||||
resolveContentRef: (ref, options) =>
|
||||
resolveContentRef(ref, context, options),
|
||||
shouldHighlightCode,
|
||||
}}
|
||||
/>
|
||||
</React.Suspense>
|
||||
@@ -145,14 +144,8 @@ export function PageBody(props: {
|
||||
) : null}
|
||||
</div>
|
||||
</main>
|
||||
{shouldTrackPageViews() ? (
|
||||
<TrackPageView
|
||||
sitePointer={pointer}
|
||||
spaceId={space.id}
|
||||
pageId={page.id}
|
||||
apiHost={api().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,11 +1,19 @@
|
||||
import { RevisionPageDocument } from '@gitbook/api';
|
||||
import { RevisionPage, RevisionPageDocument } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { pageHref } from '@/lib/links';
|
||||
import { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { PageIcon } from '../PageIcon';
|
||||
import { StyledLink } from '../primitives';
|
||||
|
||||
export function PageHeader(props: { page: RevisionPageDocument }) {
|
||||
const { page } = props;
|
||||
export function PageHeader(props: {
|
||||
page: RevisionPageDocument;
|
||||
ancestors: AncestorRevisionPage[];
|
||||
pages: RevisionPage[];
|
||||
}) {
|
||||
const { page, ancestors, pages } = props;
|
||||
|
||||
if (!page.layout.title && !page.layout.description) {
|
||||
return null;
|
||||
@@ -15,6 +23,48 @@ export function PageHeader(props: { page: RevisionPageDocument }) {
|
||||
<header
|
||||
className={tcls('max-w-3xl', 'mx-auto', 'mb-6', 'space-y-3', 'page-api-block:ml-0')}
|
||||
>
|
||||
{ancestors.length > 0 && (
|
||||
<nav>
|
||||
<ol className={tcls('flex', 'flex-wrap', 'items-center', 'gap-2')}>
|
||||
{ancestors.map((breadcrumb, index) => (
|
||||
<>
|
||||
<li key={breadcrumb.id}>
|
||||
<StyledLink
|
||||
href={pageHref(pages, breadcrumb)}
|
||||
style={tcls(
|
||||
'no-underline',
|
||||
'hover:underline',
|
||||
'text-xs',
|
||||
'tracking-wide',
|
||||
'font-semibold',
|
||||
'uppercase',
|
||||
'flex',
|
||||
'items-center',
|
||||
'gap-1',
|
||||
)}
|
||||
>
|
||||
<PageIcon
|
||||
page={breadcrumb}
|
||||
style={tcls('size-4', 'text-base', 'leading-none')}
|
||||
/>
|
||||
{breadcrumb.title}
|
||||
</StyledLink>
|
||||
</li>
|
||||
{index != ancestors.length - 1 && (
|
||||
<Icon
|
||||
icon="chevron-right"
|
||||
className={tcls(
|
||||
'size-3',
|
||||
'text-light-4',
|
||||
'dark:text-dark-4',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
)}
|
||||
{page.layout.title ? (
|
||||
<h1 className={tcls('text-4xl', 'font-bold', 'flex', 'items-center', 'gap-4')}>
|
||||
<PageIcon page={page} style={['text-dark/6', 'dark:text-light/6']} />
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -18,7 +18,7 @@ export async function postPageFeedback(args: {
|
||||
`No siteSpaceId in pointer. organizationId: ${organizationId}, siteId: ${siteId}, pageId: ${args.pageId}`,
|
||||
);
|
||||
|
||||
await api().orgs.createSitesPageFeedback(
|
||||
await api().client.orgs.createSitesPageFeedback(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteSpaceId,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user