mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-23 11:03:39 +00:00
Compare commits
51 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 |
@@ -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
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix an issue with the cookie banner buttons being non responsive
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'@gitbook/react-openapi': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Add an optional client context to get a callback called when the Scalar client is opened for a block.
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'@gitbook/cache-do': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Disable cloudflare observability in production
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Update styling of search+ask modal
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix a regression in variant drop-down caused by missing z-index.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Add scroll margin to the top when there are sections
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Improve contrast of search box placeholder
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Smoother tab transition for sections
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': minor
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix an issue where the active site section indicator appeared above any dropdowns.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Don't adjust fallback font for mono font.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Optimize performances by using new API endpoint for fetching site data.
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Track events for site insights using the new dedicated API.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Improve colour contrast of list item decoration
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'@gitbook/react-openapi': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Bump @scalar/api-client-react version
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
'@gitbook/react-contentkit': minor
|
||||||
|
'gitbook': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Send redirectOnError param to getPublishedContent when token is pulled from cookie
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'@gitbook/react-openapi': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Support Integers in Response example
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Track clicks on links (header, footer, content) for site insights.
|
||||||
@@ -2,4 +2,4 @@
|
|||||||
'gitbook': patch
|
'gitbook': patch
|
||||||
---
|
---
|
||||||
|
|
||||||
Restyle hint blocks
|
Fix emojis display
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix security issue with image resizing that could be used for phishing
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'@gitbook/react-openapi': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Prevent codemirror from loading multiple versions in scalar
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'@gitbook/react-openapi': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
bumped the scalar api client dependency
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix variant selector contrast for non-default themes
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'@gitbook/react-openapi': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Bumped scalar api client pacakge
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': minor
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix an issue where the space dropdown was shown under the site sections in Safari.
|
|
||||||
@@ -2,4 +2,4 @@
|
|||||||
'@gitbook/react-openapi': patch
|
'@gitbook/react-openapi': patch
|
||||||
---
|
---
|
||||||
|
|
||||||
Fixed scalar api client routing
|
Updated scalar depdenency
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix - whitespace added to site section tabs with icons.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Add icons to sections
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix bullet list display on full size blocks
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
style: adds missing scalar css variables
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'gitbook': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Track an event into site insights when visitor is opening the Scalar API client.
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': minor
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix an issue where the space dropdown could appear behind the header.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'gitbook': minor
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix the styling of site section tabs on smaller screens.
|
|
||||||
@@ -12,7 +12,7 @@ runs:
|
|||||||
|
|
||||||
# Cache browser binaries, cache key is based on Playwright version and OS
|
# Cache browser binaries, cache key is based on Playwright version and OS
|
||||||
- name: 🧰 Cache Playwright browser binaries
|
- name: 🧰 Cache Playwright browser binaries
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
id: playwright-cache
|
id: playwright-cache
|
||||||
with:
|
with:
|
||||||
path: '~/.cache/ms-playwright'
|
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'
|
||||||
+19
-45
@@ -5,7 +5,7 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
env:
|
env:
|
||||||
NPMRC_FONT_AWESOME_TOKEN: ${{ secrets.NPMRC_FONT_AWESOME_TOKEN }}
|
NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
name: Deploy to Cloudflare Pages
|
name: Deploy to Cloudflare Pages
|
||||||
@@ -22,24 +22,12 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
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
|
- name: Sets env vars for production
|
||||||
run: |
|
run: |
|
||||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
||||||
@@ -112,10 +100,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
- name: Setup Playwright
|
- name: Setup Playwright
|
||||||
@@ -138,10 +124,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
@@ -157,10 +141,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
@@ -172,10 +154,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
@@ -187,10 +167,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
@@ -201,16 +179,14 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
name: Build (Open Source)
|
name: Build (Open Source)
|
||||||
env:
|
env:
|
||||||
NPMRC_FONT_AWESOME_TOKEN: ''
|
NPM_TOKEN_READONLY: ''
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install
|
||||||
env:
|
env:
|
||||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||||
- run: bun run build
|
- run: bun run build
|
||||||
@@ -220,10 +196,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -17,10 +17,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
|
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
@@ -34,7 +32,7 @@ jobs:
|
|||||||
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
|
# 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
|
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
|
||||||
GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
|
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_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
release-preview:
|
release-preview:
|
||||||
@@ -45,10 +43,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout Repo
|
- name: Checkout Repo
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
- name: Setup bun
|
- name: Setup Bun
|
||||||
uses: oven-sh/setup-bun@v1
|
uses: ./.github/composite/setup-bun
|
||||||
with:
|
|
||||||
bun-version: 1.1.18
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: bun install --frozen-lockfile
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
|
|||||||
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
[install.scopes]
|
[install.scopes]
|
||||||
"awesome.me" = { token = "$NPMRC_FONT_AWESOME_TOKEN", url = "https://npm.fontawesome.com/" }
|
"gitbook" = { token = "$NPM_TOKEN_READONLY", url = "https://registry.npmjs.org" }
|
||||||
|
|||||||
Vendored
+5
@@ -0,0 +1,5 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||||
+43
-33
@@ -1,35 +1,45 @@
|
|||||||
{
|
{
|
||||||
"name": "gitbook",
|
"name": "gitbook",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"devDependencies": {
|
"type": "module",
|
||||||
"@changesets/cli": "^2.27.7",
|
"devDependencies": {
|
||||||
"prettier": "^3.0.3",
|
"@changesets/cli": "^2.27.7",
|
||||||
"turbo": "^2.1.2"
|
"prettier": "^3.0.3",
|
||||||
},
|
"turbo": "^2.1.2"
|
||||||
"packageManager": "bun@1.1.18",
|
},
|
||||||
"patchedDependencies": {
|
"packageManager": "bun@1.1.18",
|
||||||
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
|
"patchedDependencies": {
|
||||||
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
|
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
|
||||||
},
|
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
|
||||||
"private": true,
|
},
|
||||||
"scripts": {
|
"overrides": {
|
||||||
"dev": "turbo run dev",
|
"@codemirror/state": "6.4.1"
|
||||||
"build": "turbo run build",
|
},
|
||||||
"build:cloudflare": "turbo run build:cloudflare",
|
"private": true,
|
||||||
"lint": "turbo run lint",
|
"scripts": {
|
||||||
"lint:fix": "turbo run lint -- --fix",
|
"dev": "turbo run dev",
|
||||||
"typecheck": "turbo run typecheck",
|
"build": "turbo run build",
|
||||||
"format": "prettier ./ --ignore-unknown --write",
|
"build:cloudflare": "turbo run build:cloudflare",
|
||||||
"format:check": "prettier ./ --ignore-unknown --list-different",
|
"lint": "turbo run lint",
|
||||||
"unit": "turbo run unit",
|
"lint:fix": "turbo run lint -- --fix",
|
||||||
"e2e": "turbo run e2e",
|
"typecheck": "turbo run typecheck",
|
||||||
"changeset": "changeset",
|
"format": "prettier ./ --ignore-unknown --write",
|
||||||
"release": "turbo run release && changeset publish",
|
"format:check": "prettier ./ --ignore-unknown --list-different",
|
||||||
"release:preview": "turbo run release:preview",
|
"unit": "turbo run unit",
|
||||||
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
|
"e2e": "turbo run e2e",
|
||||||
"clean": "turbo run clean"
|
"changeset": "changeset",
|
||||||
},
|
"release": "turbo run release && changeset publish",
|
||||||
"workspaces": [
|
"release:preview": "turbo run release:preview",
|
||||||
"packages/*"
|
"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
|
# @gitbook/cache-do
|
||||||
|
|
||||||
|
## 0.1.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- b7a5106: Disable cloudflare observability in production
|
||||||
|
|
||||||
## 0.1.0
|
## 0.1.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
"default": "./dist/api.js"
|
"default": "./dist/api.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"version": "0.1.0",
|
"version": "0.1.1",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@msgpack/msgpack": "^3.0.0-beta2",
|
"@msgpack/msgpack": "^3.0.0-beta2",
|
||||||
"lru_map": "^0.4.1"
|
"lru_map": "^0.4.1"
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,45 @@
|
|||||||
# gitbook
|
# 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
|
## 0.4.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,20 +1,34 @@
|
|||||||
import { argosScreenshot } from '@argos-ci/playwright';
|
import { argosScreenshot } from '@argos-ci/playwright';
|
||||||
import {
|
import {
|
||||||
|
CustomizationBackground,
|
||||||
|
CustomizationCorners,
|
||||||
|
CustomizationFont,
|
||||||
CustomizationHeaderPreset,
|
CustomizationHeaderPreset,
|
||||||
CustomizationIconsStyle,
|
CustomizationIconsStyle,
|
||||||
CustomizationLocale,
|
CustomizationLocale,
|
||||||
|
CustomizationSidebarBackgroundStyle,
|
||||||
|
CustomizationSidebarListStyle,
|
||||||
|
CustomizationThemeMode,
|
||||||
SiteCustomizationSettings,
|
SiteCustomizationSettings,
|
||||||
} from '@gitbook/api';
|
} 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 jwt from 'jsonwebtoken';
|
||||||
import rison from 'rison';
|
import rison from 'rison';
|
||||||
import { DeepPartial } from 'ts-essentials';
|
import { DeepPartial } from 'ts-essentials';
|
||||||
|
|
||||||
|
import {
|
||||||
|
getVisitorAuthCookieName,
|
||||||
|
getVisitorAuthCookieValue,
|
||||||
|
VISITOR_TOKEN_COOKIE,
|
||||||
|
} from '@/lib/visitor-token';
|
||||||
|
|
||||||
import { getContentTestURL } from '../tests/utils';
|
import { getContentTestURL } from '../tests/utils';
|
||||||
|
|
||||||
interface Test {
|
interface Test {
|
||||||
name: string;
|
name: string;
|
||||||
url: string; // URL to visit for testing
|
url: string; // URL to visit for testing
|
||||||
|
cookies?: Parameters<BrowserContext['addCookies']>[0];
|
||||||
run?: (page: Page) => Promise<unknown>; // The test to run
|
run?: (page: Page) => Promise<unknown>; // The test to run
|
||||||
fullPage?: boolean; // Whether the test should be fullscreened during testing
|
fullPage?: boolean; // Whether the test should be fullscreened during testing
|
||||||
screenshot?: false; // Should a screenshot be stored
|
screenshot?: false; // Should a screenshot be stored
|
||||||
@@ -34,6 +48,18 @@ const allLocales: CustomizationLocale[] = [
|
|||||||
CustomizationLocale.Zh,
|
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) {
|
async function waitForCookiesDialog(page: Page) {
|
||||||
const dialog = page.getByRole('dialog', { name: 'Cookies' });
|
const dialog = page.getByRole('dialog', { name: 'Cookies' });
|
||||||
const accept = dialog.getByRole('button', { name: 'Accept' });
|
const accept = dialog.getByRole('button', { name: 'Accept' });
|
||||||
@@ -95,7 +121,9 @@ const testCases: TestsCase[] = [
|
|||||||
name: 'Variants dropdown',
|
name: 'Variants dropdown',
|
||||||
url: '',
|
url: '',
|
||||||
run: async (page) => {
|
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();
|
await spaceDrowpdown.waitFor();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -111,7 +139,9 @@ const testCases: TestsCase[] = [
|
|||||||
name: 'Customized variant titles are displayed',
|
name: 'Customized variant titles are displayed',
|
||||||
url: '',
|
url: '',
|
||||||
run: async (page) => {
|
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();
|
await spaceDrowpdown.click();
|
||||||
|
|
||||||
const variantSelectionDropdown = page.locator(
|
const variantSelectionDropdown = page.locator(
|
||||||
@@ -143,9 +173,9 @@ const testCases: TestsCase[] = [
|
|||||||
url: 'api-multi-versions/reference/api-reference/pets',
|
url: 'api-multi-versions/reference/api-reference/pets',
|
||||||
screenshot: false,
|
screenshot: false,
|
||||||
run: async (page) => {
|
run: async (page) => {
|
||||||
const spaceDrowpdown = await page.waitForSelector(
|
const spaceDrowpdown = await page
|
||||||
'[data-testid="space-dropdown-button"]',
|
.locator('[data-testid="space-dropdown-button"]')
|
||||||
);
|
.locator('visible=true');
|
||||||
await spaceDrowpdown.click();
|
await spaceDrowpdown.click();
|
||||||
|
|
||||||
// Click the second variant in the dropdown
|
// 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',
|
url: 'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/reference/api-reference/pets',
|
||||||
screenshot: false,
|
screenshot: false,
|
||||||
run: async (page) => {
|
run: async (page) => {
|
||||||
const spaceDrowpdown = await page.waitForSelector(
|
const spaceDrowpdown = await page
|
||||||
'[data-testid="space-dropdown-button"]',
|
.locator('[data-testid="space-dropdown-button"]')
|
||||||
);
|
.locator('visible=true');
|
||||||
await spaceDrowpdown.click();
|
await spaceDrowpdown.click();
|
||||||
|
|
||||||
// Click the second variant in the dropdown
|
// 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}`;
|
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
|
||||||
})(),
|
})(),
|
||||||
run: async (page) => {
|
run: async (page) => {
|
||||||
const spaceDrowpdown = await page.waitForSelector(
|
const spaceDrowpdown = await page
|
||||||
'[data-testid="space-dropdown-button"]',
|
.locator('[data-testid="space-dropdown-button"]')
|
||||||
);
|
.locator('visible=true');
|
||||||
await spaceDrowpdown.click();
|
await spaceDrowpdown.click();
|
||||||
|
|
||||||
// Click the second variant in the dropdown
|
// Click the second variant in the dropdown
|
||||||
@@ -435,30 +465,38 @@ const testCases: TestsCase[] = [
|
|||||||
{
|
{
|
||||||
name: 'Customization',
|
name: 'Customization',
|
||||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||||
tests: [
|
tests: allThemeModes.flatMap((theme) => [
|
||||||
{
|
{
|
||||||
name: 'Without header',
|
name: `Without header - Theme ${theme}`,
|
||||||
url: getCustomizationURL({
|
url: getCustomizationURL({
|
||||||
header: {
|
header: {
|
||||||
preset: CustomizationHeaderPreset.None,
|
preset: CustomizationHeaderPreset.None,
|
||||||
links: [],
|
links: [],
|
||||||
},
|
},
|
||||||
|
themes: {
|
||||||
|
default: theme,
|
||||||
|
toggeable: false,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
run: waitForCookiesDialog,
|
run: waitForCookiesDialog,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'With duotone icons',
|
name: `With duotone icons - Theme ${theme}`,
|
||||||
url:
|
url:
|
||||||
'page-options/page-with-icon' +
|
'page-options/page-with-icon' +
|
||||||
getCustomizationURL({
|
getCustomizationURL({
|
||||||
styling: {
|
styling: {
|
||||||
icons: CustomizationIconsStyle.Duotone,
|
icons: CustomizationIconsStyle.Duotone,
|
||||||
},
|
},
|
||||||
|
themes: {
|
||||||
|
default: theme,
|
||||||
|
toggeable: false,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
run: waitForCookiesDialog,
|
run: waitForCookiesDialog,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'With header buttons',
|
name: `With header buttons - Theme ${theme}`,
|
||||||
url: getCustomizationURL({
|
url: getCustomizationURL({
|
||||||
header: {
|
header: {
|
||||||
preset: CustomizationHeaderPreset.Default,
|
preset: CustomizationHeaderPreset.Default,
|
||||||
@@ -475,10 +513,101 @@ const testCases: TestsCase[] = [
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
themes: {
|
||||||
|
default: theme,
|
||||||
|
toggeable: false,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
run: waitForCookiesDialog,
|
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',
|
name: 'Ads',
|
||||||
@@ -747,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',
|
name: 'Languages',
|
||||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||||
@@ -814,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) {
|
for (const testCase of testCases) {
|
||||||
test.describe(testCase.name, () => {
|
test.describe(testCase.name, () => {
|
||||||
for (const testEntry of testCase.tests) {
|
for (const testEntry of testCase.tests) {
|
||||||
const testFn = testEntry.only ? test.only : test;
|
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 contentUrl = new URL(testEntry.url, testCase.baseUrl);
|
||||||
const url = getContentTestURL(contentUrl.toString(), 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);
|
await page.goto(url);
|
||||||
if (testEntry.run) {
|
if (testEntry.run) {
|
||||||
await testEntry.run(page);
|
await testEntry.run(page);
|
||||||
@@ -848,7 +1355,66 @@ for (const testCase of testCases) {
|
|||||||
* Create a URL with customization settings.
|
* Create a URL with customization settings.
|
||||||
*/
|
*/
|
||||||
function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): string {
|
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();
|
const searchParams = new URLSearchParams();
|
||||||
searchParams.set('customization', encoded);
|
searchParams.set('customization', encoded);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "gitbook",
|
"name": "gitbook",
|
||||||
"version": "0.4.0",
|
"version": "0.5.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "env-cmd --silent -f ../../.env.local next dev",
|
"dev": "env-cmd --silent -f ../../.env.local next dev",
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@gitbook/api": "^0.78.0",
|
"@gitbook/api": "^0.85.0",
|
||||||
"@gitbook/cache-do": "workspace:*",
|
"@gitbook/cache-do": "workspace:*",
|
||||||
"@gitbook/emoji-codepoints": "workspace:*",
|
"@gitbook/emoji-codepoints": "workspace:*",
|
||||||
"@gitbook/icons": "workspace:*",
|
"@gitbook/icons": "workspace:*",
|
||||||
@@ -43,14 +43,14 @@
|
|||||||
"memoizee": "^0.4.15",
|
"memoizee": "^0.4.15",
|
||||||
"next": "14.2.15",
|
"next": "14.2.15",
|
||||||
"next-themes": "^0.2.1",
|
"next-themes": "^0.2.1",
|
||||||
"nuqs": "^1.17.4",
|
"nuqs": "^2.2.3",
|
||||||
"object-hash": "^3.0.0",
|
"object-hash": "^3.0.0",
|
||||||
"openapi-types": "^12.1.3",
|
"openapi-types": "^12.1.3",
|
||||||
"p-map": "^7.0.0",
|
"p-map": "^7.0.0",
|
||||||
"parse-cache-control": "^1.0.1",
|
"parse-cache-control": "^1.0.1",
|
||||||
"postcss-color-contrast": "^1.1.0",
|
"postcss-color-contrast": "^1.1.0",
|
||||||
"react": "^18",
|
"react": "18.3.1",
|
||||||
"react-dom": "^18",
|
"react-dom": "18.3.1",
|
||||||
"react-hotkeys-hook": "^4.4.1",
|
"react-hotkeys-hook": "^4.4.1",
|
||||||
"recoil": "^0.7.7",
|
"recoil": "^0.7.7",
|
||||||
"rehype-sanitize": "^6.0.0",
|
"rehype-sanitize": "^6.0.0",
|
||||||
@@ -64,13 +64,14 @@
|
|||||||
"tailwind-merge": "^2.2.0",
|
"tailwind-merge": "^2.2.0",
|
||||||
"tailwind-shades": "^1.1.2",
|
"tailwind-shades": "^1.1.2",
|
||||||
"unified": "^11.0.4",
|
"unified": "^11.0.4",
|
||||||
"url-join": "^5.0.0"
|
"url-join": "^5.0.0",
|
||||||
|
"usehooks-ts": "^3.1.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@argos-ci/playwright": "^2.0.0",
|
"@argos-ci/playwright": "^2.0.0",
|
||||||
"@playwright/test": "^1.42.1",
|
|
||||||
"@cloudflare/next-on-pages": "^1.13.5",
|
"@cloudflare/next-on-pages": "^1.13.5",
|
||||||
"@cloudflare/workers-types": "^4.20240725.0",
|
"@cloudflare/workers-types": "^4.20240725.0",
|
||||||
|
"@playwright/test": "^1.42.1",
|
||||||
"@types/js-cookie": "^3.0.6",
|
"@types/js-cookie": "^3.0.6",
|
||||||
"@types/jsontoxml": "^1.0.5",
|
"@types/jsontoxml": "^1.0.5",
|
||||||
"@types/jsonwebtoken": "^9.0.6",
|
"@types/jsonwebtoken": "^9.0.6",
|
||||||
@@ -78,10 +79,12 @@
|
|||||||
"@types/object-hash": "^3.0.6",
|
"@types/object-hash": "^3.0.6",
|
||||||
"@types/parse-cache-control": "^1.0.4",
|
"@types/parse-cache-control": "^1.0.4",
|
||||||
"@types/psi": "^4.1.6",
|
"@types/psi": "^4.1.6",
|
||||||
"@types/react": "^18.3.3",
|
"@types/react": "18.3.13",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "18.3.1",
|
||||||
"@types/rison": "^0.0.9",
|
"@types/rison": "^0.0.9",
|
||||||
"autoprefixer": "^10",
|
"autoprefixer": "^10",
|
||||||
|
"deepmerge": "^4.3.1",
|
||||||
|
"env-cmd": "^10.1.0",
|
||||||
"eslint": "^8",
|
"eslint": "^8",
|
||||||
"eslint-config-next": "^14.2.5",
|
"eslint-config-next": "^14.2.5",
|
||||||
"eslint-plugin-import": "^2.29.1",
|
"eslint-plugin-import": "^2.29.1",
|
||||||
@@ -89,8 +92,7 @@
|
|||||||
"postcss": "^8",
|
"postcss": "^8",
|
||||||
"psi": "^4.1.0",
|
"psi": "^4.1.0",
|
||||||
"tailwindcss": "^3.4.0",
|
"tailwindcss": "^3.4.0",
|
||||||
"typescript": "^5.5.3",
|
"ts-essentials": "^10.0.1",
|
||||||
"env-cmd": "^10.1.0",
|
"typescript": "^5.5.3"
|
||||||
"ts-essentials": "^10.0.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
|
import { TrackPageViewEvent } from '@/components/Insights';
|
||||||
import { getSpaceLanguage, t } from '@/intl/server';
|
import { getSpaceLanguage, t } from '@/intl/server';
|
||||||
import { getSiteData } from '@/lib/api';
|
import { getSiteData, getSpaceContentData } from '@/lib/api';
|
||||||
import { getSiteContentPointer } from '@/lib/pointer';
|
import { getSiteContentPointer } from '@/lib/pointer';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
export default async function NotFound() {
|
export default async function NotFound() {
|
||||||
const pointer = getSiteContentPointer();
|
const pointer = getSiteContentPointer();
|
||||||
const { customization } = await getSiteData(pointer);
|
const [{ space }, { customization }] = await Promise.all([
|
||||||
|
getSpaceContentData(pointer, pointer.siteShareKey),
|
||||||
|
getSiteData(pointer),
|
||||||
|
]);
|
||||||
|
|
||||||
const language = getSpaceLanguage(customization);
|
const language = getSpaceLanguage(customization);
|
||||||
|
|
||||||
@@ -19,6 +23,9 @@ export default async function NotFound() {
|
|||||||
</h2>
|
</h2>
|
||||||
<p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p>
|
<p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Track the page not found as a page view */}
|
||||||
|
<TrackPageViewEvent pageId={null} revisionId={space.revision} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
|
|||||||
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
|
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
|
||||||
import { ContentRefContext } from '@/lib/references';
|
import { ContentRefContext } from '@/lib/references';
|
||||||
import { isSpaceIndexable, isPageIndexable } from '@/lib/seo';
|
import { isSpaceIndexable, isPageIndexable } from '@/lib/seo';
|
||||||
import { tcls } from '@/lib/tailwind';
|
|
||||||
import { getContentTitle } from '@/lib/utils';
|
import { getContentTitle } from '@/lib/utils';
|
||||||
|
|
||||||
import { PageClientLayout } from './PageClientLayout';
|
import { PageClientLayout } from './PageClientLayout';
|
||||||
@@ -35,6 +34,7 @@ export default async function Page(props: {
|
|||||||
customization,
|
customization,
|
||||||
pages,
|
pages,
|
||||||
page,
|
page,
|
||||||
|
ancestors,
|
||||||
document,
|
document,
|
||||||
} = await getPageDataWithFallback({
|
} = await getPageDataWithFallback({
|
||||||
pagePathParams: params,
|
pagePathParams: params,
|
||||||
@@ -103,6 +103,7 @@ export default async function Page(props: {
|
|||||||
customization={customization}
|
customization={customization}
|
||||||
context={contentRefContext}
|
context={contentRefContext}
|
||||||
page={page}
|
page={page}
|
||||||
|
ancestors={ancestors}
|
||||||
document={document}
|
document={document}
|
||||||
withPageFeedback={
|
withPageFeedback={
|
||||||
// Display the page feedback in the page footer if the aside is not visible
|
// Display the page feedback in the page footer if the aside is not visible
|
||||||
@@ -150,7 +151,8 @@ export async function generateMetadata({
|
|||||||
.join(' | '),
|
.join(' | '),
|
||||||
description: page.description ?? '',
|
description: page.description ?? '',
|
||||||
alternates: {
|
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: {
|
openGraph: {
|
||||||
images: [
|
images: [
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { CustomizationThemeMode } from '@gitbook/api';
|
import { CustomizationThemeMode } from '@gitbook/api';
|
||||||
import { Metadata, Viewport } from 'next';
|
import { Metadata, Viewport } from 'next';
|
||||||
import { headers } from 'next/headers';
|
import { headers } from 'next/headers';
|
||||||
|
import { NuqsAdapter } from 'nuqs/adapters/next/app';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import * as ReactDOM from 'react-dom';
|
import * as ReactDOM from 'react-dom';
|
||||||
|
|
||||||
@@ -42,7 +43,7 @@ export default async function ContentLayout(props: { children: React.ReactNode }
|
|||||||
sections,
|
sections,
|
||||||
} = await fetchContentData();
|
} = await fetchContentData();
|
||||||
|
|
||||||
ReactDOM.preconnect(api().endpoint);
|
ReactDOM.preconnect(api().client.endpoint);
|
||||||
if (assetsDomain) {
|
if (assetsDomain) {
|
||||||
ReactDOM.preconnect(assetsDomain);
|
ReactDOM.preconnect(assetsDomain);
|
||||||
}
|
}
|
||||||
@@ -55,46 +56,48 @@ export default async function ContentLayout(props: { children: React.ReactNode }
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ClientContexts
|
<NuqsAdapter>
|
||||||
nonce={nonce}
|
<ClientContexts
|
||||||
forcedTheme={
|
nonce={nonce}
|
||||||
getQueryStringTheme() ??
|
forcedTheme={
|
||||||
(customization.themes.toggeable ? undefined : customization.themes.default)
|
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}
|
|
||||||
>
|
>
|
||||||
{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 ? (
|
{scripts.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
<LoadIntegrations />
|
<LoadIntegrations />
|
||||||
{scripts.map(({ script }) => (
|
{scripts.map(({ script }) => (
|
||||||
<script key={script} async src={script} nonce={nonce} />
|
<script key={script} async src={script} nonce={nonce} />
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
|
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
|
||||||
<React.Suspense fallback={null}>
|
<React.Suspense fallback={null}>
|
||||||
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
|
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
|
||||||
</React.Suspense>
|
</React.Suspense>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<RocketLoaderDetector nonce={nonce} />
|
<RocketLoaderDetector nonce={nonce} />
|
||||||
|
|
||||||
<AdminToolbar space={space} content={content} />
|
<AdminToolbar space={space} content={content} />
|
||||||
</ClientContexts>
|
</ClientContexts>
|
||||||
|
</NuqsAdapter>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,23 +11,24 @@ import { Metadata } from 'next';
|
|||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
|
|
||||||
import { DocumentView } from '@/components/DocumentView';
|
import { DocumentView } from '../../../../components/DocumentView';
|
||||||
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
|
import { TrademarkLink } from '../../../../components/TableOfContents/Trademark';
|
||||||
import { PolymorphicComponentProp } from '@/components/utils/types';
|
import { PolymorphicComponentProp } from '../../../../components/utils/types';
|
||||||
import { getSpaceLanguage } from '@/intl/server';
|
import { getSpaceLanguage } from '../../../../intl/server';
|
||||||
import { tString } from '@/intl/translate';
|
import { tString } from '../../../../intl/translate';
|
||||||
import {
|
import {
|
||||||
getDocument,
|
getDocument,
|
||||||
getSpace,
|
getSpace,
|
||||||
getSpaceCustomization,
|
getSpaceCustomization,
|
||||||
getSpaceContentData,
|
getSpaceContentData,
|
||||||
getSiteData,
|
getSiteData,
|
||||||
} from '@/lib/api';
|
} from '../../../../lib/api';
|
||||||
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links';
|
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '../../../../lib/links';
|
||||||
import { resolvePageId } from '@/lib/pages';
|
import { resolvePageId } from '../../../../lib/pages';
|
||||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
import { ContentRefContext, resolveContentRef } from '../../../../lib/references';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '../../../../lib/tailwind';
|
||||||
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
|
import { SiteContentPointer, SpaceContentPointer } from '../../../../lib/api';
|
||||||
|
import { PDFSearchParams, getPDFSearchParams } from '../../../../lib/urls';
|
||||||
|
|
||||||
import './pdf.css';
|
import './pdf.css';
|
||||||
import { PageControlButtons } from './PageControlButtons';
|
import { PageControlButtons } from './PageControlButtons';
|
||||||
@@ -55,7 +56,9 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
* Render a space as a standalone HTML page that can be printed as a PDF.
|
* 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 } }) {
|
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 searchParams = new URLSearchParams(props.searchParams);
|
||||||
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
|
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
const { renderToPipeableStream } = require('react-dom/server');
|
||||||
|
const PDFHTMLOutput = require('./page');
|
||||||
|
//import { renderToPipeableStream, renderToStaticNodeStream } from 'react-dom/server';
|
||||||
|
//import PDFHTMLOutput from './page';
|
||||||
|
//import fs from 'fs';
|
||||||
|
//import React from 'react';
|
||||||
|
const fs = require('fs');
|
||||||
|
const React = require('react');
|
||||||
|
|
||||||
|
|
||||||
|
// Create a writable stream to save the HTML to a file
|
||||||
|
const writeStream = fs.createWriteStream('output.html');
|
||||||
|
|
||||||
|
// Start the server-side rendering with renderToPipeableStream
|
||||||
|
const { pipe } = renderToPipeableStream(React.createElement(PDFHTMLOutput, {searchParams : {'a': 'b'}}) as any);
|
||||||
|
|
||||||
|
// Pipe the render stream to the writable file stream
|
||||||
|
pipe(writeStream);
|
||||||
|
|
||||||
|
// Optionally, you can handle errors and closure
|
||||||
|
writeStream.on('finish', () => {
|
||||||
|
console.log('HTML has been written to output.html');
|
||||||
|
});
|
||||||
|
|
||||||
|
writeStream.on('error', (err: any) => {
|
||||||
|
console.error('Error writinsg to file:', err);
|
||||||
|
});
|
||||||
@@ -6,9 +6,10 @@ import * as React from 'react';
|
|||||||
import { Button } from '@/components/primitives';
|
import { Button } from '@/components/primitives';
|
||||||
import { useLanguage } from '@/intl/client';
|
import { useLanguage } from '@/intl/client';
|
||||||
import { t, tString } from '@/intl/translate';
|
import { t, tString } from '@/intl/translate';
|
||||||
import { isCookiesTrackingDisabled, setCookiesTracking } from '@/lib/analytics';
|
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
|
import { isCookiesTrackingDisabled, setCookiesTracking } from '../Insights';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Toast to accept or reject the use of cookies.
|
* Toast to accept or reject the use of cookies.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>
|
|||||||
href={resolved.href}
|
href={resolved.href}
|
||||||
title={resolved.text}
|
title={resolved.text}
|
||||||
style={style}
|
style={style}
|
||||||
|
insights={{
|
||||||
|
target: block.data.ref,
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -283,9 +283,9 @@ function CodeHighlightToken(props: {
|
|||||||
return <>{token.content}</>;
|
return <>{token.content}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!token.token.color) {
|
// if (!token.token.color) {
|
||||||
return <>{token.token.content}</>;
|
// return <>{token.token.content}</>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
return <span style={{ color: token.token.color }}>{token.token.content}</span>;
|
// return <span style={{ color: token.token.color }}>{token.token.content}</span>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,105 +1,110 @@
|
|||||||
import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api';
|
import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api';
|
||||||
import {
|
// // @ts-ignore - onigWasm is a Wasm module
|
||||||
createdBundledHighlighter,
|
// import {
|
||||||
ThemedToken,
|
// createdBundledHighlighter,
|
||||||
createCssVariablesTheme,
|
// ThemedToken,
|
||||||
HighlighterGeneric,
|
// createCssVariablesTheme,
|
||||||
} from 'shiki/core';
|
// HighlighterGeneric,
|
||||||
import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma';
|
// } from 'shiki/core';
|
||||||
import { bundledLanguages } from 'shiki/langs';
|
// // @ts-ignore - onigWasm is a Wasm module
|
||||||
// @ts-ignore - onigWasm is a Wasm module
|
// import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma';
|
||||||
import onigWasm from 'shiki/onig.wasm?module';
|
// // @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 { getNodeText } from '@/lib/document';
|
||||||
import { trace } from '@/lib/tracing';
|
// import { trace } from '@/lib/tracing';
|
||||||
|
|
||||||
export type HighlightLine = {
|
export type HighlightLine = {
|
||||||
highlighted: boolean;
|
highlighted: boolean;
|
||||||
tokens: HighlightToken[];
|
tokens: HighlightToken[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type HighlightToken =
|
export type HighlightToken =
|
||||||
| { type: 'plain'; content: string }
|
| { type: 'plain'; content: string }
|
||||||
| { type: 'shiki'; token: ThemedToken }
|
| { type: 'inline'; inline: DocumentInlineAnnotation; children: HighlightToken[] };
|
||||||
| { 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 };
|
||||||
|
|
||||||
/**
|
// type PositionedToken = ThemedToken & { start: number; end: number };
|
||||||
* Highlight a code block while preserving inline elements.
|
|
||||||
*/
|
// /**
|
||||||
|
// * Highlight a code block while preserving inline elements.
|
||||||
|
// */
|
||||||
export async function highlight(block: DocumentBlockCode): Promise<HighlightLine[]> {
|
export async function highlight(block: DocumentBlockCode): Promise<HighlightLine[]> {
|
||||||
const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
|
return plainHighlighting(block);
|
||||||
if (!langName) {
|
// const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
|
||||||
// Language not found, fallback to plain highlighting
|
// if (!langName) {
|
||||||
return plainHighlighting(block);
|
// // Language not found, fallback to plain highlighting
|
||||||
}
|
// return plainHighlighting(block);
|
||||||
|
// }
|
||||||
|
|
||||||
const inlines: InlineIndexed[] = [];
|
// const inlines: InlineIndexed[] = [];
|
||||||
const code = getPlainCodeBlock(block, inlines);
|
// const code = getPlainCodeBlock(block, inlines);
|
||||||
|
|
||||||
inlines.sort((a, b) => {
|
// inlines.sort((a, b) => {
|
||||||
return a.start - b.start;
|
// return a.start - b.start;
|
||||||
});
|
// });
|
||||||
|
|
||||||
const highlighter = await loadHighlighter();
|
// const highlighter = await loadHighlighter();
|
||||||
await loadHighlighterLanguage(highlighter, langName);
|
// await loadHighlighterLanguage(highlighter, langName);
|
||||||
|
|
||||||
const lines = highlighter.codeToTokensBase(code, {
|
// const lines = highlighter.codeToTokensBase(code, {
|
||||||
lang: langName,
|
// lang: langName,
|
||||||
tokenizeMaxLineLength: 120,
|
// tokenizeMaxLineLength: 400,
|
||||||
});
|
// });
|
||||||
|
|
||||||
let currentIndex = 0;
|
// let currentIndex = 0;
|
||||||
return lines.map((tokens, index) => {
|
// return lines.map((tokens, index) => {
|
||||||
const lineBlock = block.nodes[index];
|
// const lineBlock = block.nodes[index];
|
||||||
const result: HighlightToken[] = [];
|
// const result: HighlightToken[] = [];
|
||||||
|
|
||||||
const eatToken = (): PositionedToken | null => {
|
// const eatToken = (): PositionedToken | null => {
|
||||||
const token = tokens.shift();
|
// const token = tokens.shift();
|
||||||
if (token) {
|
// if (token) {
|
||||||
currentIndex += token.content.length;
|
// currentIndex += token.content.length;
|
||||||
}
|
// }
|
||||||
return token
|
// return token
|
||||||
? { ...token, start: currentIndex - token.content.length, end: currentIndex }
|
// ? { ...token, start: currentIndex - token.content.length, end: currentIndex }
|
||||||
: null;
|
// : null;
|
||||||
};
|
// };
|
||||||
|
|
||||||
while (tokens.length > 0) {
|
// while (tokens.length > 0) {
|
||||||
result.push(...matchTokenAndInlines(eatToken, inlines));
|
// result.push(...matchTokenAndInlines(eatToken, inlines));
|
||||||
}
|
// }
|
||||||
|
|
||||||
currentIndex += 1; // for the \n
|
// currentIndex += 1; // for the \n
|
||||||
|
|
||||||
return {
|
// return {
|
||||||
highlighted: !!lineBlock.data.highlighted,
|
// highlighted: !!lineBlock.data.highlighted,
|
||||||
tokens: result,
|
// tokens: result,
|
||||||
};
|
// };
|
||||||
});
|
// });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* Validate a language name.
|
// * Validate a language name.
|
||||||
*/
|
// */
|
||||||
function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null {
|
// function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null {
|
||||||
// @ts-ignore
|
// // @ts-ignore
|
||||||
const lang = bundledLanguages[syntax];
|
// const lang = bundledLanguages[syntax];
|
||||||
if (!lang) {
|
// if (!lang) {
|
||||||
return null;
|
// return null;
|
||||||
}
|
// }
|
||||||
|
|
||||||
// @ts-ignore
|
// // @ts-ignore
|
||||||
return syntax;
|
// return syntax;
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* Parse a code block without highlighting it.
|
// * Parse a code block without highlighting it.
|
||||||
*/
|
// */
|
||||||
export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
||||||
return block.nodes.map((lineBlock) => {
|
return block.nodes.map((lineBlock: any) => {
|
||||||
const tokens: HighlightToken[] = [];
|
const tokens: HighlightToken[] = [];
|
||||||
|
|
||||||
for (const node of lineBlock.nodes) {
|
for (const node of lineBlock.nodes) {
|
||||||
@@ -108,17 +113,6 @@ export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
|
|||||||
type: 'plain',
|
type: 'plain',
|
||||||
content: getNodeText(node),
|
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(
|
// function matchTokenAndInlines(
|
||||||
eat: () => PositionedToken | null,
|
// eat: () => PositionedToken | null,
|
||||||
allInlines: InlineIndexed[],
|
// allInlines: InlineIndexed[],
|
||||||
): HighlightToken[] {
|
// ): HighlightToken[] {
|
||||||
const initialToken = eat();
|
// const initialToken = eat();
|
||||||
if (!initialToken) {
|
// if (!initialToken) {
|
||||||
return [];
|
// return [];
|
||||||
}
|
// }
|
||||||
|
|
||||||
const inlines = allInlines.filter(
|
// const inlines = allInlines.filter(
|
||||||
(inline) => inline.start >= initialToken.start && inline.start < initialToken.end,
|
// (inline) => inline.start >= initialToken.start && inline.start < initialToken.end,
|
||||||
);
|
// );
|
||||||
let token = initialToken;
|
// let token = initialToken;
|
||||||
const result: HighlightToken[] = [];
|
// const result: HighlightToken[] = [];
|
||||||
|
|
||||||
const matchAgainstInline = () => {
|
// const matchAgainstInline = () => {
|
||||||
const inline = inlines.shift();
|
// const inline = inlines.shift();
|
||||||
if (!inline) {
|
// if (!inline) {
|
||||||
result.push({
|
// result.push({
|
||||||
type: 'shiki',
|
// type: 'shiki',
|
||||||
token,
|
// token,
|
||||||
});
|
// });
|
||||||
|
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
|
|
||||||
const [before, afterBefore] = splitPositionedTokenAt(token, inline.start);
|
// const [before, afterBefore] = splitPositionedTokenAt(token, inline.start);
|
||||||
if (before) {
|
// if (before) {
|
||||||
result.push({
|
// result.push({
|
||||||
type: 'shiki',
|
// type: 'shiki',
|
||||||
token: before,
|
// token: before,
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
if (!afterBefore) {
|
// if (!afterBefore) {
|
||||||
throw new Error(`expect afterBefore to not be empty`);
|
// throw new Error(`expect afterBefore to not be empty`);
|
||||||
}
|
// }
|
||||||
|
|
||||||
token = afterBefore;
|
// token = afterBefore;
|
||||||
const children: HighlightToken[] = [];
|
// const children: HighlightToken[] = [];
|
||||||
|
|
||||||
// If shiki token finished before the end of the annotation or the annotation contains multiple tokens
|
// // If shiki token finished before the end of the annotation or the annotation contains multiple tokens
|
||||||
while (token.end < inline.end) {
|
// while (token.end < inline.end) {
|
||||||
children.push({
|
// children.push({
|
||||||
type: 'shiki',
|
// type: 'shiki',
|
||||||
token: token,
|
// token: token,
|
||||||
});
|
// });
|
||||||
|
|
||||||
const next = eat();
|
// const next = eat();
|
||||||
if (!next) {
|
// if (!next) {
|
||||||
throw new Error(`expect token to not be empty`);
|
// throw new Error(`expect token to not be empty`);
|
||||||
}
|
// }
|
||||||
token = next;
|
// token = next;
|
||||||
}
|
// }
|
||||||
|
|
||||||
const [inside, after] = splitPositionedTokenAt(token, inline.end);
|
// const [inside, after] = splitPositionedTokenAt(token, inline.end);
|
||||||
if (!inside) {
|
// if (!inside) {
|
||||||
throw new Error(`expect inside to not be empty`);
|
// throw new Error(`expect inside to not be empty`);
|
||||||
}
|
// }
|
||||||
|
|
||||||
children.push({
|
// children.push({
|
||||||
type: 'shiki',
|
// type: 'shiki',
|
||||||
token: inside,
|
// token: inside,
|
||||||
});
|
// });
|
||||||
|
|
||||||
result.push({
|
// result.push({
|
||||||
type: 'inline',
|
// type: 'inline',
|
||||||
inline: inline.inline,
|
// inline: inline.inline,
|
||||||
children,
|
// children,
|
||||||
});
|
// });
|
||||||
|
|
||||||
if (after) {
|
// if (after) {
|
||||||
token = after;
|
// token = after;
|
||||||
matchAgainstInline();
|
// matchAgainstInline();
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
matchAgainstInline();
|
// matchAgainstInline();
|
||||||
return result;
|
// return result;
|
||||||
}
|
// }
|
||||||
|
|
||||||
function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string {
|
// function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string {
|
||||||
let content = '';
|
// let content = '';
|
||||||
|
|
||||||
code.nodes.forEach((node, index) => {
|
// code.nodes.forEach((node, index) => {
|
||||||
const lineContent = getPlainCodeBlockLine(node, inlines, content.length);
|
// const lineContent = getPlainCodeBlockLine(node, inlines, content.length);
|
||||||
content += lineContent;
|
// content += lineContent;
|
||||||
|
|
||||||
if (index < code.nodes.length - 1) {
|
// if (index < code.nodes.length - 1) {
|
||||||
content += '\n';
|
// content += '\n';
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
|
|
||||||
return content;
|
// return content;
|
||||||
}
|
// }
|
||||||
|
|
||||||
function getPlainCodeBlockLine(
|
// function getPlainCodeBlockLine(
|
||||||
parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
|
// parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
|
||||||
inlines: InlineIndexed[],
|
// inlines: InlineIndexed[],
|
||||||
index: number,
|
// index: number,
|
||||||
): string {
|
// ): string {
|
||||||
let content = '';
|
// let content = '';
|
||||||
|
|
||||||
for (const node of parent.nodes) {
|
// for (const node of parent.nodes) {
|
||||||
if (node.object === 'text') {
|
// if (node.object === 'text') {
|
||||||
content += cleanupLine(node.leaves.map((leaf) => leaf.text).join(''));
|
// content += cleanupLine(node.leaves.map((leaf) => leaf.text).join(''));
|
||||||
} else {
|
// } else {
|
||||||
const start = index + content.length;
|
// const start = index + content.length;
|
||||||
content += getPlainCodeBlockLine(node, inlines, index + content.length);
|
// content += getPlainCodeBlockLine(node, inlines, index + content.length);
|
||||||
const end = index + content.length;
|
// const end = index + content.length;
|
||||||
|
|
||||||
inlines.push({
|
// inlines.push({
|
||||||
inline: node,
|
// inline: node,
|
||||||
start,
|
// start,
|
||||||
end,
|
// end,
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
return content;
|
// return content;
|
||||||
}
|
// }
|
||||||
|
|
||||||
function slicePositionedToken(
|
// function slicePositionedToken(
|
||||||
token: PositionedToken,
|
// token: PositionedToken,
|
||||||
relativeStart: number,
|
// relativeStart: number,
|
||||||
relativeLength: number,
|
// relativeLength: number,
|
||||||
): PositionedToken {
|
// ): PositionedToken {
|
||||||
return {
|
// return {
|
||||||
...token,
|
// ...token,
|
||||||
start: token.start + relativeStart,
|
// start: token.start + relativeStart,
|
||||||
end: token.start + relativeStart + relativeLength,
|
// end: token.start + relativeStart + relativeLength,
|
||||||
content: token.content.slice(relativeStart, relativeStart + relativeLength),
|
// content: token.content.slice(relativeStart, relativeStart + relativeLength),
|
||||||
};
|
// };
|
||||||
}
|
// }
|
||||||
|
|
||||||
function splitPositionedTokenAt(
|
// function splitPositionedTokenAt(
|
||||||
token: PositionedToken,
|
// token: PositionedToken,
|
||||||
absoluteIndex: number,
|
// absoluteIndex: number,
|
||||||
): [PositionedToken | null, PositionedToken | null] {
|
// ): [PositionedToken | null, PositionedToken | null] {
|
||||||
if (absoluteIndex < token.start || absoluteIndex > token.end) {
|
// if (absoluteIndex < token.start || absoluteIndex > token.end) {
|
||||||
throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
|
// throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
|
||||||
}
|
// }
|
||||||
|
|
||||||
const before = slicePositionedToken(token, 0, absoluteIndex - token.start);
|
// const before = slicePositionedToken(token, 0, absoluteIndex - token.start);
|
||||||
const after = slicePositionedToken(
|
// const after = slicePositionedToken(
|
||||||
token,
|
// token,
|
||||||
absoluteIndex - token.start,
|
// absoluteIndex - token.start,
|
||||||
token.end - absoluteIndex,
|
// token.end - absoluteIndex,
|
||||||
);
|
// );
|
||||||
|
|
||||||
return [
|
// return [
|
||||||
isEmptyPositionedToken(before) ? null : before,
|
// isEmptyPositionedToken(before) ? null : before,
|
||||||
isEmptyPositionedToken(after) ? null : after,
|
// isEmptyPositionedToken(after) ? null : after,
|
||||||
];
|
// ];
|
||||||
}
|
// }
|
||||||
|
|
||||||
function isEmptyPositionedToken(token: PositionedToken): boolean {
|
// function isEmptyPositionedToken(token: PositionedToken): boolean {
|
||||||
return token.start === token.end;
|
// return token.start === token.end;
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* Currently it's possible for some lines to contain \r characters, we need to remove them
|
// * 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.
|
// * as they are considered as new lines by shikijs.
|
||||||
*/
|
// */
|
||||||
function cleanupLine(line: string): string {
|
// function cleanupLine(line: string): string {
|
||||||
return line.replace(/\r/g, '');
|
// return line.replace(/\r/g, '');
|
||||||
}
|
// }
|
||||||
|
|
||||||
const createHighlighter = createdBundledHighlighter<any, any>({
|
// const createHighlighter = createdBundledHighlighter<any, any>({
|
||||||
langs: bundledLanguages,
|
// langs: bundledLanguages,
|
||||||
themes: {},
|
// themes: {},
|
||||||
engine: () => createOnigurumaEngine(import('shiki/wasm')),
|
// engine: () => createOnigurumaEngine(import('shiki/wasm')),
|
||||||
});
|
// });
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* Load the highlighter, only once, and reuse it.
|
// * Load the highlighter, only once, and reuse it.
|
||||||
* It makes sure to handle concurrent calls.
|
// * It makes sure to handle concurrent calls.
|
||||||
*/
|
// */
|
||||||
const loadHighlighter = singleton(async () => {
|
// const loadHighlighter = singleton(async () => {
|
||||||
return await trace('highlighting.loadHighlighter', async () => {
|
// return await trace('highlighting.loadHighlighter', async () => {
|
||||||
if (typeof onigWasm !== 'string') {
|
// if (typeof onigWasm !== 'string') {
|
||||||
// When running bun test, the import is a string, we ignore it and let the module
|
// // When running bun test, the import is a string, we ignore it and let the module
|
||||||
// loads it on its own.
|
// // loads it on its own.
|
||||||
//
|
// //
|
||||||
// Otherwise for Vercel/Cloudflare, we need to load it ourselves.
|
// // Otherwise for Vercel/Cloudflare, we need to load it ourselves.
|
||||||
await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj));
|
// await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj));
|
||||||
}
|
// }
|
||||||
|
|
||||||
const highlighter = await createHighlighter({
|
// const highlighter = await createHighlighter({
|
||||||
themes: [createCssVariablesTheme()],
|
// themes: [createCssVariablesTheme()],
|
||||||
langs: [],
|
// langs: [],
|
||||||
});
|
// });
|
||||||
return highlighter;
|
// return highlighter;
|
||||||
});
|
// });
|
||||||
});
|
// });
|
||||||
|
|
||||||
const loadLanguagesMutex = asyncMutexFunction();
|
// const loadLanguagesMutex = asyncMutexFunction();
|
||||||
async function loadHighlighterLanguage(
|
// async function loadHighlighterLanguage(
|
||||||
highlighter: HighlighterGeneric<any, any>,
|
// highlighter: HighlighterGeneric<any, any>,
|
||||||
lang: keyof typeof bundledLanguages,
|
// lang: keyof typeof bundledLanguages,
|
||||||
) {
|
// ) {
|
||||||
await loadLanguagesMutex.runBlocking(async () => {
|
// await loadLanguagesMutex.runBlocking(async () => {
|
||||||
if (highlighter.getLoadedLanguages().includes(lang)) {
|
// if (highlighter.getLoadedLanguages().includes(lang)) {
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
|
|
||||||
await trace(
|
// await trace(
|
||||||
`highlighting.loadLanguage(${lang})`,
|
// `highlighting.loadLanguage(${lang})`,
|
||||||
async () => await highlighter.loadLanguage(lang),
|
// async () => await highlighter.loadLanguage(lang),
|
||||||
);
|
// );
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { tcls } from '@/lib/tailwind';
|
|||||||
import { BlockProps } from './Block';
|
import { BlockProps } from './Block';
|
||||||
import { Caption } from './Caption';
|
import { Caption } from './Caption';
|
||||||
import { FileIcon } from './FileIcon';
|
import { FileIcon } from './FileIcon';
|
||||||
|
import { Link } from '../primitives';
|
||||||
|
|
||||||
export async function File(props: BlockProps<DocumentBlockFile>) {
|
export async function File(props: BlockProps<DocumentBlockFile>) {
|
||||||
const { block, context } = props;
|
const { block, context } = props;
|
||||||
@@ -21,9 +22,13 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Caption {...props} wrapperStyle={[]}>
|
<Caption {...props} wrapperStyle={[]}>
|
||||||
<a
|
<Link
|
||||||
href={file.downloadURL}
|
href={file.downloadURL}
|
||||||
download={file.name}
|
download={file.name}
|
||||||
|
insights={{
|
||||||
|
target: block.data.ref,
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'group/file',
|
'group/file',
|
||||||
'flex',
|
'flex',
|
||||||
@@ -77,7 +82,7 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
|
|||||||
{contentType}
|
{contentType}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</Link>
|
||||||
</Caption>
|
</Caption>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,11 @@ export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
|
|||||||
|
|
||||||
return (
|
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 */
|
/* 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
|
<Image
|
||||||
alt={inline.data.caption ?? ''}
|
alt={inline.data.caption ?? ''}
|
||||||
sizes={await getImageSizes(size, src)}
|
sizes={await getImageSizes(size, src)}
|
||||||
|
|||||||
@@ -25,7 +25,11 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
|
|||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
href={resolved.href}
|
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
|
<Inlines
|
||||||
context={context}
|
context={context}
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ export function ListItem(props: BlockProps<DocumentBlockListItem>) {
|
|||||||
'[&:is(h2)>div]:mt-0',
|
'[&:is(h2)>div]:mt-0',
|
||||||
'[&:is(h3)>div]:mt-0',
|
'[&:is(h3)>div]:mt-0',
|
||||||
'[&:is(h4)>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"
|
style="space-y-2 flex flex-col flex-1"
|
||||||
/>
|
/>
|
||||||
@@ -135,7 +137,7 @@ function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.R
|
|||||||
className={tcls(
|
className={tcls(
|
||||||
textStyle.textSize,
|
textStyle.textSize,
|
||||||
textStyle.lineHeight,
|
textStyle.lineHeight,
|
||||||
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark/6 dark:text-light/5',
|
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark-4 dark:text-light-4',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{props.children}
|
{props.children}
|
||||||
|
|||||||
@@ -15,5 +15,15 @@ export async function Mention(props: InlineProps<DocumentInlineMention>) {
|
|||||||
return null;
|
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 { Icon } from '@gitbook/icons';
|
||||||
import { OpenAPIOperation } from '@gitbook/react-openapi';
|
import { OpenAPIOperation } from '@gitbook/react-openapi';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
@@ -16,7 +16,7 @@ import './scalar.css';
|
|||||||
/**
|
/**
|
||||||
* Render an OpenAPI block.
|
* Render an OpenAPI block.
|
||||||
*/
|
*/
|
||||||
export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
|
export async function OpenAPI(props: BlockProps<DocumentBlockOpenAPI>) {
|
||||||
const { block, style } = props;
|
const { block, style } = props;
|
||||||
return (
|
return (
|
||||||
<div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}>
|
<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 { block, context } = props;
|
||||||
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
|
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
.light .scalar {
|
.light .scalar {
|
||||||
--scalar-color-1: color-mix(
|
--scalar-color-1: color-mix(
|
||||||
in srgb,
|
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%
|
rgb(var(--dark-base, 23 23 23)) 96%
|
||||||
);
|
);
|
||||||
--scalar-color-2: color-mix(
|
--scalar-color-2: color-mix(
|
||||||
@@ -23,12 +23,12 @@
|
|||||||
--scalar-background-1: rgb(var(--light-base, 255 255 255));
|
--scalar-background-1: rgb(var(--light-base, 255 255 255));
|
||||||
--scalar-background-2: color-mix(
|
--scalar-background-2: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
rgb(var(--primary-base-800, 30 30 30)),
|
rgb(var(--tint-color-800, 30 30 30)),
|
||||||
var(--scalar-background-1) 96%
|
var(--scalar-background-1) 96%
|
||||||
);
|
);
|
||||||
--scalar-background-3: color-mix(
|
--scalar-background-3: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
rgb(var(--primary-base-800, 30 30 30)),
|
rgb(var(--tint-color-800, 30 30 30)),
|
||||||
var(--scalar-background-1) 90%
|
var(--scalar-background-1) 90%
|
||||||
);
|
);
|
||||||
--scalar-background-accent: #007d9c1f;
|
--scalar-background-accent: #007d9c1f;
|
||||||
@@ -66,7 +66,7 @@
|
|||||||
.dark .scalar {
|
.dark .scalar {
|
||||||
--scalar-color-1: color-mix(
|
--scalar-color-1: color-mix(
|
||||||
in srgb,
|
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%
|
rgb(var(--light-base, 255 255 255)) 100%
|
||||||
);
|
);
|
||||||
--scalar-color-2: color-mix(
|
--scalar-color-2: color-mix(
|
||||||
@@ -84,12 +84,12 @@
|
|||||||
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
|
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
|
||||||
--scalar-background-2: color-mix(
|
--scalar-background-2: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
rgb(var(--primary-base-200, 200 200 200)),
|
rgb(var(--tint-color-200, 200 200 200)),
|
||||||
var(--scalar-background-1) 92%
|
var(--scalar-background-1) 92%
|
||||||
);
|
);
|
||||||
--scalar-background-3: color-mix(
|
--scalar-background-3: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
rgb(var(--primary-base-200, 200 200 200)),
|
rgb(var(--tint-color-200, 200 200 200)),
|
||||||
var(--scalar-background-1) 88%
|
var(--scalar-background-1) 88%
|
||||||
);
|
);
|
||||||
--scalar-background-accent: #8ab4f81f;
|
--scalar-background-accent: #8ab4f81f;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { ContentRef, DocumentTableViewCards } from '@gitbook/api';
|
import { ContentRef, DocumentTableViewCards } from '@gitbook/api';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
|
import { Link } from '@/components/primitives';
|
||||||
import { Image } from '@/components/utils';
|
import { Image } from '@/components/utils';
|
||||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
@@ -153,17 +154,21 @@ export async function RecordCard(
|
|||||||
'before:dark:ring-light/2',
|
'before:dark:ring-light/2',
|
||||||
] as ClassValue;
|
] as ClassValue;
|
||||||
|
|
||||||
if (target) {
|
if (target && targetRef) {
|
||||||
return (
|
return (
|
||||||
<a
|
<Link
|
||||||
href={target.href}
|
href={target.href}
|
||||||
className={tcls(style, [
|
className={tcls(style, [
|
||||||
'hover:before:ring-dark/4',
|
'hover:before:ring-dark/4',
|
||||||
'dark:hover:before:ring-light/4',
|
'dark:hover:before:ring-light/4',
|
||||||
])}
|
])}
|
||||||
|
insights={{
|
||||||
|
target: targetRef,
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{body}
|
{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 { Icon } from '@gitbook/icons';
|
||||||
import assertNever from 'assert-never';
|
import assertNever from 'assert-never';
|
||||||
|
|
||||||
import { Checkbox, Emoji } from '@/components/primitives';
|
import { Checkbox } from '@/components/primitives';
|
||||||
import { StyledLink } from '@/components/primitives';
|
import { StyledLink } from '@/components/primitives';
|
||||||
import { Image } from '@/components/utils';
|
import { Image } from '@/components/utils';
|
||||||
import { getNodeFragmentByName } from '@/lib/document';
|
import { getNodeFragmentByName } from '@/lib/document';
|
||||||
@@ -148,6 +148,17 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
|
|||||||
href={ref.href}
|
href={ref.href}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
style={['flex', 'flex-row', 'items-center', 'gap-2']}
|
style={['flex', 'flex-row', 'items-center', 'gap-2']}
|
||||||
|
insights={
|
||||||
|
ref.file
|
||||||
|
? {
|
||||||
|
target: {
|
||||||
|
kind: 'file',
|
||||||
|
file: ref.file.id,
|
||||||
|
},
|
||||||
|
position: 'content',
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{contentType === 'image' ? (
|
{contentType === 'image' ? (
|
||||||
<Image
|
<Image
|
||||||
@@ -178,8 +189,9 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
|
|||||||
</Tag>
|
</Tag>
|
||||||
);
|
);
|
||||||
case 'content-ref': {
|
case 'content-ref': {
|
||||||
const resolved = value
|
const contentRef = value ? (value as ContentRef) : null;
|
||||||
? await context.resolveContentRef(value as ContentRef, {
|
const resolved = contentRef
|
||||||
|
? await context.resolveContentRef(contentRef, {
|
||||||
resolveAnchorText: true,
|
resolveAnchorText: true,
|
||||||
iconStyle: ['mr-2', 'text-dark/6', 'dark:text-light/6'],
|
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?.icon ?? null}
|
||||||
{resolved ? (
|
{resolved ? (
|
||||||
<StyledLink href={resolved.href}>{resolved.text}</StyledLink>
|
<StyledLink
|
||||||
|
href={resolved.href}
|
||||||
|
insights={
|
||||||
|
contentRef
|
||||||
|
? {
|
||||||
|
target: contentRef,
|
||||||
|
position: 'content',
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{resolved.text}
|
||||||
|
</StyledLink>
|
||||||
) : null}
|
) : null}
|
||||||
</Tag>
|
</Tag>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
case 'users': {
|
case 'users': {
|
||||||
const resolved = await Promise.all(
|
const resolved = await Promise.all(
|
||||||
(value as string[]).map((userId) =>
|
(value as string[]).map(async (userId) => {
|
||||||
context.resolveContentRef({
|
const contentRef: ContentRefUser = {
|
||||||
kind: 'user',
|
kind: 'user',
|
||||||
user: userId,
|
user: userId,
|
||||||
}),
|
};
|
||||||
),
|
const resolved = await context.resolveContentRef(contentRef);
|
||||||
|
if (!resolved) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [contentRef, resolved] as const;
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
|
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
|
||||||
{resolved.filter(filterOutNullable).map((file, index) => (
|
{resolved.filter(filterOutNullable).map(([contentRef, resolved], index) => (
|
||||||
<StyledLink key={index} href={file.href}>
|
<StyledLink
|
||||||
{file.text}
|
key={index}
|
||||||
|
href={resolved.href}
|
||||||
|
insights={{
|
||||||
|
target: contentRef,
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{resolved.text}
|
||||||
</StyledLink>
|
</StyledLink>
|
||||||
))}
|
))}
|
||||||
</Tag>
|
</Tag>
|
||||||
|
|||||||
@@ -1,44 +1,43 @@
|
|||||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||||
|
import React from 'react';
|
||||||
import { tcls } from '@/lib/tailwind';
|
|
||||||
|
|
||||||
import { RecordColumnValue } from './RecordColumnValue';
|
import { RecordColumnValue } from './RecordColumnValue';
|
||||||
import { TableRecordKV, TableViewProps } from './Table';
|
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> & {
|
props: TableViewProps<DocumentTableViewGrid> & {
|
||||||
record: TableRecordKV;
|
record: TableRecordKV;
|
||||||
|
autoSizedColumns: string[];
|
||||||
|
fixedColumns: string[];
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const { view } = props;
|
const { view, autoSizedColumns, fixedColumns } = props;
|
||||||
const columnsLengthThreshold = view.columns.length >= 7;
|
|
||||||
|
|
||||||
const tableTR = columnsLengthThreshold
|
|
||||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
|
||||||
: ['[&>*+*]:border-l', '[&>*+*]:pl-4'];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr className={tcls(tableTR, 'border-dark/3', 'dark:border-light/2')}>
|
<div className={styles.row} role="row">
|
||||||
{view.columns.map((column) => {
|
{view.columns.map((column) => {
|
||||||
|
const columnWidth = getColumnWidth({
|
||||||
|
column,
|
||||||
|
columnWidths: view.columnWidths,
|
||||||
|
autoSizedColumns,
|
||||||
|
fixedColumns,
|
||||||
|
});
|
||||||
return (
|
return (
|
||||||
<td
|
<div
|
||||||
key={column}
|
key={column}
|
||||||
className={tcls(
|
role="cell"
|
||||||
'align-middle',
|
className={styles.cell}
|
||||||
'min-w-[8rem]',
|
style={{
|
||||||
'border-dark/2',
|
width: columnWidth,
|
||||||
'py-3',
|
minWidth: columnWidth || '100px',
|
||||||
'text-sm',
|
}}
|
||||||
'lg:text-base',
|
|
||||||
'dark:border-light/2',
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
<div className={tcls('pr-4 ', 'text-balance')}>
|
<RecordColumnValue {...props} column={column} />
|
||||||
<RecordColumnValue key={column} {...props} column={column} />
|
</div>
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</tr>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||||
|
import * as React from 'react';
|
||||||
|
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
@@ -7,159 +8,113 @@ import { TableViewProps } from './Table';
|
|||||||
import styles from './table.module.css';
|
import styles from './table.module.css';
|
||||||
import { getColumnAlignment } from './utils';
|
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>) {
|
export function ViewGrid(props: TableViewProps<DocumentTableViewGrid>) {
|
||||||
const { block, view, records, style } = props;
|
const { block, view, records, style } = props;
|
||||||
const columnsOverThreshold = view.columns.length >= 7;
|
|
||||||
|
|
||||||
const tableWrapper = columnsOverThreshold
|
/* Calculate how many columns are auto-sized vs fixed width */
|
||||||
? [
|
const columnWidths = view.columnWidths;
|
||||||
// has over X columns
|
const autoSizedColumns = view.columns.filter((column) => !columnWidths?.[column]);
|
||||||
'overflow-x-auto',
|
const fixedColumns = view.columns.filter((column) => columnWidths?.[column]);
|
||||||
'overflow-y-hidden',
|
|
||||||
'mx-auto',
|
|
||||||
'rounded-md',
|
|
||||||
'border',
|
|
||||||
'border-dark/3',
|
|
||||||
'dark:border-light/2',
|
|
||||||
]
|
|
||||||
: ['overflow-x-auto', 'overflow-y-hidden', 'mx-auto'];
|
|
||||||
|
|
||||||
const tableTR = columnsOverThreshold
|
const tableWidth = autoSizedColumns.length > 0 ? 'w-full' : 'w-fit';
|
||||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
|
||||||
: ['[&>*+*]:border-l', '[&>*+*]:px-4'];
|
|
||||||
|
|
||||||
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 =
|
const withHeader =
|
||||||
!view.hideHeader &&
|
!view.hideHeader &&
|
||||||
view.columns.some((columnId) => block.data.definition[columnId].title.trim().length > 0);
|
view.columns.some((columnId) => block.data.definition[columnId].title.trim().length > 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className={tcls(style, styles.tableWrapper)}>
|
||||||
className={`${tcls(style, 'relative', 'grid', tableWrapper, styles.progressContainer)}`}
|
{/* Table */}
|
||||||
>
|
<div role="table" className={tcls('flex', 'flex-col')}>
|
||||||
{/* ProgressScroller: */}
|
{/* Header */}
|
||||||
<div
|
{withHeader && (
|
||||||
className={`${styles.progressOpacitySharp} ${tcls(
|
<div
|
||||||
'grid',
|
role="rowgroup"
|
||||||
'items-center',
|
className={tcls(
|
||||||
'grid-area-1-1',
|
tableWidth,
|
||||||
'w-[5rem]',
|
styles.rowGroup,
|
||||||
'h-full',
|
'straight-corners:rounded-none',
|
||||||
'top-0',
|
)}
|
||||||
'z-[1]',
|
>
|
||||||
'sticky',
|
<div role="row" className={tcls('flex', 'w-full')}>
|
||||||
'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)}>
|
|
||||||
{view.columns.map((column) => {
|
{view.columns.map((column) => {
|
||||||
const columnWidth = view.columnWidths?.[column];
|
|
||||||
const alignment = getColumnAlignment(block.data.definition[column]);
|
const alignment = getColumnAlignment(block.data.definition[column]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<th
|
<div
|
||||||
key={column}
|
key={column}
|
||||||
|
role="columnheader"
|
||||||
className={tcls(
|
className={tcls(
|
||||||
tableTH,
|
styles.columnHeader,
|
||||||
'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',
|
|
||||||
alignment === 'right' ? 'text-right' : null,
|
alignment === 'right' ? 'text-right' : null,
|
||||||
alignment === 'center' ? 'text-center' : 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}
|
{block.data.definition[column].title}
|
||||||
</th>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</tr>
|
</div>
|
||||||
</thead>
|
</div>
|
||||||
) : null}
|
)}
|
||||||
<tbody className={tcls('[&>*+*]:border-t')}>
|
<div
|
||||||
{records.map((record) => {
|
role="rowgroup"
|
||||||
return <RecordRow key={record[0]} {...props} record={record} />;
|
className={tcls('flex', 'flex-col', tableWidth, '[&>*+*]:border-t')}
|
||||||
})}
|
>
|
||||||
</tbody>
|
{records.map((record) => (
|
||||||
</table>
|
<RecordRow
|
||||||
|
key={record[0]}
|
||||||
|
record={record}
|
||||||
|
autoSizedColumns={autoSizedColumns}
|
||||||
|
fixedColumns={fixedColumns}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</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 */
|
/* Detect whether a scrollbar exists on the table */
|
||||||
.progressOpacitySharp {
|
@keyframes detect-scroll {
|
||||||
display: none;
|
from,
|
||||||
}
|
to {
|
||||||
|
--can-scroll: ;
|
||||||
@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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
|
|||||||
'dark:text-light/8',
|
'dark:text-light/8',
|
||||||
'dark:hover:text-light/9',
|
'dark:hover:text-light/9',
|
||||||
)}
|
)}
|
||||||
|
insights={{
|
||||||
|
target: link.to,
|
||||||
|
position: 'footer',
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{link.title}
|
{link.title}
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { DetailedHTMLProps, HTMLAttributes, useId } from 'react';
|
|||||||
|
|
||||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { Link } from '../primitives';
|
import { Link, LinkInsightsProps } from '../primitives';
|
||||||
|
|
||||||
export type DropdownButtonProps<E extends HTMLElement = HTMLElement> = Omit<
|
export type DropdownButtonProps<E extends HTMLElement = HTMLElement> = Omit<
|
||||||
Partial<DetailedHTMLProps<HTMLAttributes<E>, E>>,
|
Partial<DetailedHTMLProps<HTMLAttributes<E>, E>>,
|
||||||
@@ -25,7 +25,7 @@ export function Dropdown<E extends HTMLElement>(props: {
|
|||||||
const dropdownId = useId();
|
const dropdownId = useId();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={tcls('group/dropdown', 'relative flex')}>
|
<div className={tcls('group/dropdown', 'relative flex shrink min-w-0')}>
|
||||||
{button({
|
{button({
|
||||||
id: dropdownId,
|
id: dropdownId,
|
||||||
tabIndex: 0,
|
tabIndex: 0,
|
||||||
@@ -39,7 +39,7 @@ export function Dropdown<E extends HTMLElement>(props: {
|
|||||||
aria-labelledby={dropdownId}
|
aria-labelledby={dropdownId}
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'w-52',
|
'w-52',
|
||||||
'max-h-56',
|
'max-h-80',
|
||||||
'flex',
|
'flex',
|
||||||
'absolute',
|
'absolute',
|
||||||
'top-full',
|
'top-full',
|
||||||
@@ -110,32 +110,42 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
|
|||||||
/**
|
/**
|
||||||
* Menu item in a dropdown.
|
* Menu item in a dropdown.
|
||||||
*/
|
*/
|
||||||
export function DropdownMenuItem(props: {
|
export function DropdownMenuItem(
|
||||||
href: string;
|
props: {
|
||||||
active?: boolean;
|
href: string | null;
|
||||||
children: React.ReactNode;
|
active?: boolean;
|
||||||
}) {
|
className?: ClassValue;
|
||||||
const { children, active = false, href } = props;
|
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 (
|
return (
|
||||||
<Link
|
<div
|
||||||
href={href}
|
|
||||||
prefetch={false}
|
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'flex',
|
'text-xs px-3 py-1 font-medium text-dark/8 dark:text-light/8',
|
||||||
'flex-row',
|
className,
|
||||||
'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'],
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</Link>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { HeaderLogo } from './HeaderLogo';
|
|||||||
import { SpacesDropdown } from './SpacesDropdown';
|
import { SpacesDropdown } from './SpacesDropdown';
|
||||||
import { SearchButton } from '../Search';
|
import { SearchButton } from '../Search';
|
||||||
import { SiteSectionTabs } from '../SiteSectionTabs';
|
import { SiteSectionTabs } from '../SiteSectionTabs';
|
||||||
|
import { HeaderMobileMenu } from './HeaderMobileMenu';
|
||||||
/**
|
/**
|
||||||
* Render the header for the space.
|
* Render the header for the space.
|
||||||
*/
|
*/
|
||||||
@@ -45,104 +46,174 @@ export function Header(props: {
|
|||||||
'w-full',
|
'w-full',
|
||||||
'flex-none',
|
'flex-none',
|
||||||
'shadow-thinbottom',
|
'shadow-thinbottom',
|
||||||
|
'dark:shadow-light/2',
|
||||||
|
'bg-light',
|
||||||
|
'dark:bg-dark',
|
||||||
withTopHeader ? null : 'lg:hidden',
|
withTopHeader ? null : 'lg:hidden',
|
||||||
'lg:z-10',
|
'text-sm',
|
||||||
'dark:shadow-light/1',
|
'bg-opacity-9',
|
||||||
`${isCustomizationDefault || !withTopHeader ? 'bg-light' : 'bg-header-background'}`,
|
'dark:bg-opacity-9',
|
||||||
`${
|
'backdrop-blur-lg',
|
||||||
isCustomizationDefault || !withTopHeader
|
'contrast-more:bg-opacity-11',
|
||||||
? 'dark:bg-dark'
|
'contrast-more:dark:bg-opacity-11',
|
||||||
: 'bg-header-background'
|
|
||||||
}`,
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className={tcls('scroll-nojump')}>
|
<div
|
||||||
<div
|
className={tcls(
|
||||||
className={tcls(
|
!isCustomizationDefault &&
|
||||||
'gap-4',
|
withTopHeader && [
|
||||||
'grid',
|
'bg-header-background',
|
||||||
'grid-flow-col',
|
'shadow-thinbottom',
|
||||||
'auto-cols-[auto_auto_1fr_auto]',
|
'dark:shadow-light/2',
|
||||||
'h-16',
|
],
|
||||||
'items-center',
|
)}
|
||||||
'align-center',
|
>
|
||||||
'justify-between',
|
<div className={tcls('scroll-nojump')}>
|
||||||
'w-full',
|
<div
|
||||||
CONTAINER_STYLE,
|
className={tcls(
|
||||||
)}
|
'gap-4',
|
||||||
>
|
'lg:gap-8',
|
||||||
<HeaderLogo site={site} space={space} customization={customization} />
|
'flex',
|
||||||
<div className="z-20">
|
'h-16',
|
||||||
{!hasSiteSections && isMultiVariants ? (
|
'items-center',
|
||||||
<SpacesDropdown space={space} spaces={spaces} />
|
'justify-between',
|
||||||
) : null}
|
'w-full',
|
||||||
</div>
|
CONTAINER_STYLE,
|
||||||
<HeaderLinks>
|
)}
|
||||||
{customization.header.links.map((link, index) => {
|
>
|
||||||
return (
|
<div className="flex max-w-full shrink min-w-0 gap-2 lg:gap-4 justify-start items-center">
|
||||||
<HeaderLink
|
<HeaderMobileMenu
|
||||||
key={index}
|
className={tcls(
|
||||||
link={link}
|
'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}
|
context={context}
|
||||||
customization={customization}
|
customization={customization}
|
||||||
/>
|
/>
|
||||||
);
|
</HeaderLinks>
|
||||||
})}
|
|
||||||
<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',
|
|
||||||
)}
|
)}
|
||||||
>
|
<div
|
||||||
<Suspense fallback={null}>
|
className={tcls(
|
||||||
<SearchButton
|
'flex',
|
||||||
style={
|
'md:min-w-56',
|
||||||
!isCustomizationDefault && withTopHeader
|
'grow-0',
|
||||||
? [
|
'shrink-0',
|
||||||
'bg-header-link/3',
|
'justify-self-end',
|
||||||
'shadow-sm',
|
)}
|
||||||
'ring-header-link/3',
|
>
|
||||||
'[&>span]:!text-header-link/7',
|
<Suspense fallback={null}>
|
||||||
'[&_svg]:text-header-link',
|
<SearchButton
|
||||||
'contrast-more:bg-transparent',
|
style={
|
||||||
'contrast-more:ring-header-link',
|
!isCustomizationDefault && withTopHeader
|
||||||
'contrast-more:[&>span]:!text-header-link',
|
? [
|
||||||
'dark:bg-header-link/3',
|
'bg-header-link/2',
|
||||||
'dark:ring-header-link/3',
|
'dark:bg-header-link/2',
|
||||||
'[&>span]:!text-header-link/7',
|
'hover:bg-header-link/3',
|
||||||
'dark:[&_svg]:text-header-link',
|
'dark:hover:bg-header-link/3',
|
||||||
'dark:contrast-more:bg-transparent',
|
|
||||||
'dark:contrast-more:ring-header-link',
|
'text-header-link/8',
|
||||||
'dark:contrast-more:[&>span]:!text-header-link',
|
'dark:text-header-link/8',
|
||||||
]
|
'hover:text-header-link',
|
||||||
: null
|
'dark:hover:text-header-link',
|
||||||
}
|
|
||||||
>
|
'ring-header-link/4',
|
||||||
<span className={tcls('flex-1')}>
|
'dark:ring-header-link/4',
|
||||||
{t(
|
'hover:ring-header-link/5',
|
||||||
getSpaceLanguage(customization),
|
'dark:hover:ring-header-link/5',
|
||||||
customization.aiSearch.enabled ? 'search_or_ask' : 'search',
|
|
||||||
)}
|
'[&_svg]:text-header-link/10',
|
||||||
</span>
|
'dark:[&_svg]:text-header-link/10',
|
||||||
</SearchButton>
|
'[&_.shortcut]:text-header-link/8',
|
||||||
</Suspense>
|
'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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{sections ? (
|
{sections ? (
|
||||||
<div
|
<div
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark mt-0.5',
|
'scroll-nojump',
|
||||||
|
'w-full',
|
||||||
// Handle long section tabs, particularly on smaller screens.
|
// Handle long section tabs, particularly on smaller screens.
|
||||||
'overflow-x-auto hide-scroll',
|
'overflow-x-auto hide-scroll',
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -3,18 +3,14 @@ import {
|
|||||||
CustomizationSettings,
|
CustomizationSettings,
|
||||||
CustomizationHeaderPreset,
|
CustomizationHeaderPreset,
|
||||||
SiteCustomizationSettings,
|
SiteCustomizationSettings,
|
||||||
CustomizationHeaderLink,
|
CustomizationHeaderItem,
|
||||||
|
ContentRef,
|
||||||
} from '@gitbook/api';
|
} from '@gitbook/api';
|
||||||
import assertNever from 'assert-never';
|
import assertNever from 'assert-never';
|
||||||
|
|
||||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
// @TODO replace by api.CustomizationHeaderItem when available
|
|
||||||
type CustomizationHeaderItem = Omit<CustomizationHeaderLink, 'to'> & {
|
|
||||||
to: CustomizationHeaderLink['to'] | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Dropdown,
|
Dropdown,
|
||||||
DropdownButtonProps,
|
DropdownButtonProps,
|
||||||
@@ -38,8 +34,9 @@ export async function HeaderLink(props: {
|
|||||||
if (link.links && link.links.length > 0) {
|
if (link.links && link.links.length > 0) {
|
||||||
return (
|
return (
|
||||||
<Dropdown
|
<Dropdown
|
||||||
|
className="shrink"
|
||||||
button={(buttonProps) => {
|
button={(buttonProps) => {
|
||||||
if (!target) {
|
if (!target || !link.to) {
|
||||||
return (
|
return (
|
||||||
<HeaderItemDropdown
|
<HeaderItemDropdown
|
||||||
{...buttonProps}
|
{...buttonProps}
|
||||||
@@ -51,6 +48,7 @@ export async function HeaderLink(props: {
|
|||||||
return (
|
return (
|
||||||
<HeaderLinkNavItem
|
<HeaderLinkNavItem
|
||||||
{...buttonProps}
|
{...buttonProps}
|
||||||
|
linkTarget={link.to}
|
||||||
linkStyle={linkStyle}
|
linkStyle={linkStyle}
|
||||||
headerPreset={headerPreset}
|
headerPreset={headerPreset}
|
||||||
title={link.title}
|
title={link.title}
|
||||||
@@ -69,12 +67,13 @@ export async function HeaderLink(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!target) {
|
if (!target || !link.to) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HeaderLinkNavItem
|
<HeaderLinkNavItem
|
||||||
|
linkTarget={link.to}
|
||||||
linkStyle={linkStyle}
|
linkStyle={linkStyle}
|
||||||
headerPreset={headerPreset}
|
headerPreset={headerPreset}
|
||||||
title={link.title}
|
title={link.title}
|
||||||
@@ -85,7 +84,8 @@ export async function HeaderLink(props: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type HeaderLinkNavItemProps = {
|
export type HeaderLinkNavItemProps = {
|
||||||
linkStyle: NonNullable<CustomizationHeaderLink['style']>;
|
linkTarget: ContentRef;
|
||||||
|
linkStyle: NonNullable<CustomizationHeaderItem['style']>;
|
||||||
headerPreset: CustomizationHeaderPreset;
|
headerPreset: CustomizationHeaderPreset;
|
||||||
title: string;
|
title: string;
|
||||||
href: string;
|
href: string;
|
||||||
@@ -93,14 +93,15 @@ export type HeaderLinkNavItemProps = {
|
|||||||
} & DropdownButtonProps<HTMLElement>;
|
} & DropdownButtonProps<HTMLElement>;
|
||||||
|
|
||||||
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
|
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
|
||||||
switch (props.linkStyle) {
|
const { linkStyle, ...rest } = props;
|
||||||
|
switch (linkStyle) {
|
||||||
case 'button-secondary':
|
case 'button-secondary':
|
||||||
case 'button-primary':
|
case 'button-primary':
|
||||||
return <HeaderItemButton {...props} linkStyle={props.linkStyle} />;
|
return <HeaderItemButton {...rest} linkStyle={linkStyle} />;
|
||||||
case 'link':
|
case 'link':
|
||||||
return <HeaderItemLink {...props} />;
|
return <HeaderItemLink {...rest} />;
|
||||||
default:
|
default:
|
||||||
assertNever(props.linkStyle);
|
assertNever(linkStyle);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +110,7 @@ function HeaderItemButton(
|
|||||||
linkStyle: 'button-secondary' | 'button-primary';
|
linkStyle: 'button-secondary' | 'button-primary';
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const { linkStyle, headerPreset, title, href, ...rest } = props;
|
const { linkTarget, linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
|
||||||
const variant = (() => {
|
const variant = (() => {
|
||||||
switch (linkStyle) {
|
switch (linkStyle) {
|
||||||
case 'button-secondary':
|
case 'button-secondary':
|
||||||
@@ -143,6 +144,10 @@ function HeaderItemButton(
|
|||||||
),
|
),
|
||||||
}[linkStyle],
|
}[linkStyle],
|
||||||
)}
|
)}
|
||||||
|
insights={{
|
||||||
|
target: linkTarget,
|
||||||
|
position: 'header',
|
||||||
|
}}
|
||||||
{...rest}
|
{...rest}
|
||||||
>
|
>
|
||||||
{title}
|
{title}
|
||||||
@@ -152,12 +157,9 @@ function HeaderItemButton(
|
|||||||
|
|
||||||
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
|
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
|
||||||
return tcls(
|
return tcls(
|
||||||
'overflow-hidden',
|
'flex items-center shrink',
|
||||||
'text-sm lg:text-base',
|
|
||||||
'flex flex-row items-center',
|
|
||||||
'whitespace-nowrap',
|
|
||||||
'hover:text-header-link-400 dark:hover:text-light',
|
'hover:text-header-link-400 dark:hover:text-light',
|
||||||
'truncate',
|
'min-w-0',
|
||||||
|
|
||||||
props.headerPreset === CustomizationHeaderPreset.Default
|
props.headerPreset === CustomizationHeaderPreset.Default
|
||||||
? ['text-dark/8', 'dark:text-light/8']
|
? ['text-dark/8', 'dark:text-light/8']
|
||||||
@@ -165,11 +167,19 @@ function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function HeaderItemLink(props: HeaderLinkNavItemProps) {
|
function HeaderItemLink(props: Omit<HeaderLinkNavItemProps, 'linkStyle'>) {
|
||||||
const { headerPreset, title, isDropdown, href, ...rest } = props;
|
const { linkTarget, headerPreset, title, isDropdown, href, ...rest } = props;
|
||||||
return (
|
return (
|
||||||
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
|
<Link
|
||||||
{title}
|
href={href}
|
||||||
|
className={getHeaderLinkClassName({ headerPreset })}
|
||||||
|
insights={{
|
||||||
|
target: linkTarget,
|
||||||
|
position: 'header',
|
||||||
|
}}
|
||||||
|
{...rest}
|
||||||
|
>
|
||||||
|
<span className="truncate min-w-0">{title}</span>
|
||||||
{isDropdown ? <DropdownChevron /> : null}
|
{isDropdown ? <DropdownChevron /> : null}
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
@@ -205,5 +215,9 @@ async function SubHeaderLink(props: {
|
|||||||
return null;
|
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 {
|
import {
|
||||||
CustomizationHeaderLink,
|
CustomizationContentLink,
|
||||||
|
CustomizationHeaderItem,
|
||||||
CustomizationHeaderPreset,
|
CustomizationHeaderPreset,
|
||||||
CustomizationSettings,
|
CustomizationSettings,
|
||||||
SiteCustomizationSettings,
|
SiteCustomizationSettings,
|
||||||
@@ -10,14 +11,9 @@ import React from 'react';
|
|||||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
import { Dropdown, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||||
import styles from './headerLinks.module.css';
|
import styles from './headerLinks.module.css';
|
||||||
|
|
||||||
// @TODO replace by api.CustomizationHeaderItem when available
|
|
||||||
type CustomizationHeaderItem = Omit<CustomizationHeaderLink, 'to'> & {
|
|
||||||
to: CustomizationHeaderLink['to'] | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dropdown menu for header links hidden at small screen size.
|
* Dropdown menu for header links hidden at small screen size.
|
||||||
*/
|
*/
|
||||||
@@ -35,15 +31,22 @@ export function HeaderLinkMore(props: {
|
|||||||
const renderButton = () => (
|
const renderButton = () => (
|
||||||
<button
|
<button
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'px-1',
|
isCustomizationDefault
|
||||||
!isCustomizationDefault
|
? [
|
||||||
? ['text-header-link-500']
|
'text-dark/8',
|
||||||
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
|
'dark:text-light/8',
|
||||||
'hover:text-header-link-400',
|
'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>
|
<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>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -60,14 +63,37 @@ export function HeaderLinkMore(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderItem }) {
|
async function MoreMenuLink(props: {
|
||||||
|
context: ContentRefContext;
|
||||||
|
link: CustomizationHeaderItem | CustomizationContentLink;
|
||||||
|
}) {
|
||||||
const { context, link } = props;
|
const { context, link } = props;
|
||||||
|
|
||||||
const target = link.to ? await resolveContentRef(link.to, context) : null;
|
const target = link.to ? await resolveContentRef(link.to, context) : null;
|
||||||
|
|
||||||
if (!target) {
|
return (
|
||||||
return null;
|
<>
|
||||||
}
|
{'links' in link && link.links.length > 0 && (
|
||||||
|
<hr className="first:hidden border-t border-light-3 dark:border-dark-3 my-1 -mx-2" />
|
||||||
return <DropdownMenuItem href={target.href}>{link.title}</DropdownMenuItem>;
|
)}
|
||||||
|
<DropdownMenuItem
|
||||||
|
href={target?.href ?? null}
|
||||||
|
insights={
|
||||||
|
link.to
|
||||||
|
? {
|
||||||
|
target: link.to,
|
||||||
|
position: 'header',
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{link.title}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{'links' in link
|
||||||
|
? link.links.map((subLink, index) => (
|
||||||
|
<MoreMenuLink key={index} {...props} link={subLink} />
|
||||||
|
))
|
||||||
|
: null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export async function HeaderLinks({ children }: HeaderLinksProps) {
|
|||||||
<div
|
<div
|
||||||
className={tcls(
|
className={tcls(
|
||||||
styles.containerHeaderlinks,
|
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 z-20',
|
'grow shrink flex justify-end items-center gap-x-6 lg:gap-x-8 min-w-9 z-20',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -30,65 +30,51 @@ export function HeaderLogo(props: HeaderLogoProps) {
|
|||||||
const { customization } = props;
|
const { customization } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={tcls('flex', 'flex-row', 'gap-2')}>
|
<Link
|
||||||
<HeaderMobileMenu
|
href={absoluteHref('')}
|
||||||
className={tcls(
|
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')}
|
||||||
'lg:hidden',
|
>
|
||||||
customization.header.preset === CustomizationHeaderPreset.Default
|
{customization.header.logo ? (
|
||||||
? ['text-dark', 'dark:text-light']
|
<Image
|
||||||
: 'text-header-link',
|
alt="Logo"
|
||||||
)}
|
sources={{
|
||||||
/>
|
light: {
|
||||||
<Link
|
src: customization.header.logo.light,
|
||||||
href={absoluteHref('')}
|
},
|
||||||
className={tcls(
|
dark: customization.header.logo.dark
|
||||||
'group/headerlogo',
|
? {
|
||||||
'flex-1',
|
src: customization.header.logo.dark,
|
||||||
'flex',
|
}
|
||||||
'flex-row',
|
: null,
|
||||||
'items-center',
|
}}
|
||||||
'shrink-0',
|
sizes={[
|
||||||
)}
|
{
|
||||||
>
|
media: '(max-width: 1024px)',
|
||||||
{customization.header.logo ? (
|
width: 160,
|
||||||
<Image
|
},
|
||||||
alt="Logo"
|
{
|
||||||
sources={{
|
width: 260,
|
||||||
light: {
|
},
|
||||||
src: customization.header.logo.light,
|
]}
|
||||||
},
|
priority="high"
|
||||||
dark: customization.header.logo.dark
|
style={tcls(
|
||||||
? {
|
'rounded',
|
||||||
src: customization.header.logo.dark,
|
'straight-corners:rounded-sm',
|
||||||
}
|
'overflow-hidden',
|
||||||
: null,
|
'shrink',
|
||||||
}}
|
'min-w-0',
|
||||||
sizes={[
|
'max-w-40',
|
||||||
{
|
'lg:max-w-64',
|
||||||
media: '(max-width: 1024px)',
|
'max-h-10',
|
||||||
width: 128,
|
'lg:max-h-12',
|
||||||
},
|
'h-full',
|
||||||
{
|
'w-auto',
|
||||||
width: 192,
|
)}
|
||||||
},
|
/>
|
||||||
]}
|
) : (
|
||||||
priority="high"
|
<LogoFallback {...props} />
|
||||||
style={tcls(
|
)}
|
||||||
'max-w-[8rem]',
|
</Link>
|
||||||
'lg:max-w-[12rem]',
|
|
||||||
'max-h-[3rem]',
|
|
||||||
'rounded',
|
|
||||||
'straight-corners:rounded-sm',
|
|
||||||
'overflow-hidden',
|
|
||||||
'object-contain',
|
|
||||||
'object-left',
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<LogoFallback {...props} />
|
|
||||||
)}
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,13 +97,13 @@ function LogoFallback(props: HeaderLogoProps) {
|
|||||||
className={tcls(
|
className={tcls(
|
||||||
'text-pretty',
|
'text-pretty',
|
||||||
'line-clamp-3',
|
'line-clamp-3',
|
||||||
'leading-[1.1]',
|
|
||||||
'tracking-tight',
|
'tracking-tight',
|
||||||
'max-w-[18ch]',
|
'max-w-[18ch]',
|
||||||
'lg:max-w-[24ch]',
|
'lg:max-w-[24ch]',
|
||||||
'lg:text-lg/tight',
|
|
||||||
'font-semibold',
|
'font-semibold',
|
||||||
'ms-3',
|
'ms-3',
|
||||||
|
'text-base/tight',
|
||||||
|
'lg:text-lg/tight',
|
||||||
customization.header.preset === CustomizationHeaderPreset.Default ||
|
customization.header.preset === CustomizationHeaderPreset.Default ||
|
||||||
customization.header.preset === CustomizationHeaderPreset.None
|
customization.header.preset === CustomizationHeaderPreset.None
|
||||||
? ['text-dark', 'dark:text-light']
|
? ['text-dark', 'dark:text-light']
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import { tcls } from '@/lib/tailwind';
|
|||||||
import { Dropdown, DropdownChevron, DropdownMenu } from './Dropdown';
|
import { Dropdown, DropdownChevron, DropdownMenu } from './Dropdown';
|
||||||
import { SpacesDropdownMenuItem } from './SpacesDropdownMenuItem';
|
import { SpacesDropdownMenuItem } from './SpacesDropdownMenuItem';
|
||||||
|
|
||||||
export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
export function SpacesDropdown(props: { space: Space; spaces: Space[]; className?: string }) {
|
||||||
const { space, spaces } = props;
|
const { space, spaces, className } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dropdown
|
<Dropdown
|
||||||
@@ -20,25 +20,27 @@ export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
|||||||
'items-center',
|
'items-center',
|
||||||
'rounded-2xl',
|
'rounded-2xl',
|
||||||
'straight-corners:rounded-none',
|
'straight-corners:rounded-none',
|
||||||
'bg-light-2',
|
|
||||||
'border',
|
'hover:cursor-pointer',
|
||||||
'border-light-3',
|
'bg-dark/1',
|
||||||
'text-dark-4',
|
'dark:bg-light/1',
|
||||||
|
|
||||||
'text-sm',
|
'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',
|
'px-3',
|
||||||
'py-1',
|
'py-1',
|
||||||
'contrast-more:border-dark',
|
className,
|
||||||
'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',
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{space.title}
|
<span className="line-clamp-2">{space.title}</span>
|
||||||
<DropdownChevron />
|
<DropdownChevron />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -60,12 +60,12 @@
|
|||||||
}
|
}
|
||||||
.containerHeaderlinks > :nth-child(n + 5) ~ .linkEllipsis {
|
.containerHeaderlinks > :nth-child(n + 5) ~ .linkEllipsis {
|
||||||
display: flex;
|
display: flex;
|
||||||
& div > :nth-child(n + 5) {
|
& div > a:nth-of-type(n + 5) {
|
||||||
display: flex;
|
display: flex;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@container headerlinks ( width < 900px ) {
|
@container headerlinks ( width < 850px ) {
|
||||||
.containerHeaderlinks > :nth-child(n + 6) {
|
.containerHeaderlinks > :nth-child(n + 6) {
|
||||||
display: none;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,17 +11,17 @@ import { getSpaceLanguage } from '@/intl/server';
|
|||||||
import { t } from '@/intl/translate';
|
import { t } from '@/intl/translate';
|
||||||
import { ContentTarget, SiteContentPointer, api } from '@/lib/api';
|
import { ContentTarget, SiteContentPointer, api } from '@/lib/api';
|
||||||
import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
|
import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
|
||||||
|
import { AncestorRevisionPage } from '@/lib/pages';
|
||||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
import { shouldTrackPageViews } from '@/lib/tracking';
|
|
||||||
|
|
||||||
import { PageBodyBlankslate } from './PageBodyBlankslate';
|
import { PageBodyBlankslate } from './PageBodyBlankslate';
|
||||||
import { PageCover } from './PageCover';
|
import { PageCover } from './PageCover';
|
||||||
import { PageFooterNavigation } from './PageFooterNavigation';
|
import { PageFooterNavigation } from './PageFooterNavigation';
|
||||||
import { PageHeader } from './PageHeader';
|
import { PageHeader } from './PageHeader';
|
||||||
import { PreservePageLayout } from './PreservePageLayout';
|
import { PreservePageLayout } from './PreservePageLayout';
|
||||||
import { TrackPageView } from './TrackPageView';
|
|
||||||
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
|
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
|
||||||
|
import { TrackPageViewEvent } from '../Insights';
|
||||||
import { PageFeedbackForm } from '../PageFeedback';
|
import { PageFeedbackForm } from '../PageFeedback';
|
||||||
import { DateRelative } from '../primitives';
|
import { DateRelative } from '../primitives';
|
||||||
|
|
||||||
@@ -31,17 +31,18 @@ export function PageBody(props: {
|
|||||||
contentTarget: ContentTarget;
|
contentTarget: ContentTarget;
|
||||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||||
page: RevisionPageDocument;
|
page: RevisionPageDocument;
|
||||||
|
ancestors: AncestorRevisionPage[];
|
||||||
document: JSONDocument | null;
|
document: JSONDocument | null;
|
||||||
context: ContentRefContext;
|
context: ContentRefContext;
|
||||||
withPageFeedback: boolean;
|
withPageFeedback: boolean;
|
||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
space,
|
space,
|
||||||
pointer,
|
|
||||||
contentTarget,
|
contentTarget,
|
||||||
customization,
|
customization,
|
||||||
context,
|
context,
|
||||||
page,
|
page,
|
||||||
|
ancestors,
|
||||||
document,
|
document,
|
||||||
withPageFeedback,
|
withPageFeedback,
|
||||||
} = props;
|
} = props;
|
||||||
@@ -79,7 +80,7 @@ export function PageBody(props: {
|
|||||||
<PageCover as="hero" page={page} cover={page.cover} context={context} />
|
<PageCover as="hero" page={page} cover={page.cover} context={context} />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<PageHeader page={page} />
|
<PageHeader page={page} ancestors={ancestors} pages={context.pages} />
|
||||||
{document && !isNodeEmpty(document) ? (
|
{document && !isNodeEmpty(document) ? (
|
||||||
<React.Suspense
|
<React.Suspense
|
||||||
fallback={
|
fallback={
|
||||||
@@ -143,14 +144,8 @@ export function PageBody(props: {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
{shouldTrackPageViews() ? (
|
|
||||||
<TrackPageView
|
<TrackPageViewEvent pageId={page.id} revisionId={space.revision} />
|
||||||
sitePointer={pointer}
|
|
||||||
spaceId={space.id}
|
|
||||||
pageId={page.id}
|
|
||||||
apiHost={api().endpoint}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,6 +61,10 @@ export async function PageBodyBlankslate(props: {
|
|||||||
leadingIcon={icon}
|
leadingIcon={icon}
|
||||||
title={child.title}
|
title={child.title}
|
||||||
href={resolved.href}
|
href={resolved.href}
|
||||||
|
insights={{
|
||||||
|
target: child.target,
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { pageHref } from '@/lib/links';
|
|||||||
import { resolvePrevNextPages } from '@/lib/pages';
|
import { resolvePrevNextPages } from '@/lib/pages';
|
||||||
import { tcls } from '@/lib/tailwind';
|
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.
|
* Show cards to go to previous/next pages at the bottom.
|
||||||
@@ -47,6 +47,13 @@ export function PageFooterNavigation(props: {
|
|||||||
label={t(language, 'previous_page')}
|
label={t(language, 'previous_page')}
|
||||||
title={previous.title}
|
title={previous.title}
|
||||||
href={pageHref(pages, previous)}
|
href={pageHref(pages, previous)}
|
||||||
|
insights={{
|
||||||
|
target: {
|
||||||
|
kind: 'page',
|
||||||
|
page: previous.id,
|
||||||
|
},
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
reversed
|
reversed
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -56,24 +63,34 @@ export function PageFooterNavigation(props: {
|
|||||||
label={t(language, 'next_page')}
|
label={t(language, 'next_page')}
|
||||||
title={next.title}
|
title={next.title}
|
||||||
href={pageHref(pages, next)}
|
href={pageHref(pages, next)}
|
||||||
|
insights={{
|
||||||
|
target: {
|
||||||
|
kind: 'page',
|
||||||
|
page: next.id,
|
||||||
|
},
|
||||||
|
position: 'content',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function NavigationCard(props: {
|
function NavigationCard(
|
||||||
icon: IconName;
|
props: {
|
||||||
label: React.ReactNode;
|
icon: IconName;
|
||||||
title: string;
|
label: React.ReactNode;
|
||||||
href: string;
|
title: string;
|
||||||
reversed?: boolean;
|
href: string;
|
||||||
}) {
|
reversed?: boolean;
|
||||||
const { icon, label, title, href, reversed } = props;
|
} & LinkInsightsProps,
|
||||||
|
) {
|
||||||
|
const { icon, label, title, href, reversed, insights } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
href={href}
|
href={href}
|
||||||
|
insights={insights}
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'group',
|
'group',
|
||||||
'text-sm',
|
'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 { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { PageIcon } from '../PageIcon';
|
import { PageIcon } from '../PageIcon';
|
||||||
|
import { StyledLink } from '../primitives';
|
||||||
|
|
||||||
export function PageHeader(props: { page: RevisionPageDocument }) {
|
export function PageHeader(props: {
|
||||||
const { page } = props;
|
page: RevisionPageDocument;
|
||||||
|
ancestors: AncestorRevisionPage[];
|
||||||
|
pages: RevisionPage[];
|
||||||
|
}) {
|
||||||
|
const { page, ancestors, pages } = props;
|
||||||
|
|
||||||
if (!page.layout.title && !page.layout.description) {
|
if (!page.layout.title && !page.layout.description) {
|
||||||
return null;
|
return null;
|
||||||
@@ -15,6 +23,48 @@ export function PageHeader(props: { page: RevisionPageDocument }) {
|
|||||||
<header
|
<header
|
||||||
className={tcls('max-w-3xl', 'mx-auto', 'mb-6', 'space-y-3', 'page-api-block:ml-0')}
|
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 ? (
|
{page.layout.title ? (
|
||||||
<h1 className={tcls('text-4xl', 'font-bold', 'flex', 'items-center', 'gap-4')}>
|
<h1 className={tcls('text-4xl', 'font-bold', 'flex', 'items-center', 'gap-4')}>
|
||||||
<PageIcon page={page} style={['text-dark/6', 'dark:text-light/6']} />
|
<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 { useLanguage } from '@/intl/client';
|
||||||
import { t, tString } from '@/intl/translate';
|
import { t, tString } from '@/intl/translate';
|
||||||
import { getVisitorId } from '@/lib/analytics';
|
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
|
import { getVisitorId, useTrackEvent } from '../Insights';
|
||||||
import { postPageFeedback } from './server-actions';
|
import { postPageFeedback } from './server-actions';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,12 +20,20 @@ export function PageFeedbackForm(props: {
|
|||||||
}) {
|
}) {
|
||||||
const { orientation = 'vertical', pageId, className } = props;
|
const { orientation = 'vertical', pageId, className } = props;
|
||||||
const languages = useLanguage();
|
const languages = useLanguage();
|
||||||
|
// const trackEvent = useTrackEvent();
|
||||||
const [submitted, setSubmitted] = React.useState(false);
|
const [submitted, setSubmitted] = React.useState(false);
|
||||||
|
|
||||||
const onSubmit = async (rating: PageFeedbackRating) => {
|
const onSubmit = async (rating: PageFeedbackRating) => {
|
||||||
setSubmitted(true);
|
setSubmitted(true);
|
||||||
const visitorId = await getVisitorId();
|
const visitorId = await getVisitorId();
|
||||||
await postPageFeedback({ pageId, visitorId, rating });
|
await postPageFeedback({ pageId, visitorId, rating });
|
||||||
|
|
||||||
|
// trackEvent({
|
||||||
|
// type: 'page_post_feedback',
|
||||||
|
// feedback: {
|
||||||
|
// rating,
|
||||||
|
// },
|
||||||
|
// });
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export async function postPageFeedback(args: {
|
|||||||
`No siteSpaceId in pointer. organizationId: ${organizationId}, siteId: ${siteId}, pageId: ${args.pageId}`,
|
`No siteSpaceId in pointer. organizationId: ${organizationId}, siteId: ${siteId}, pageId: ${args.pageId}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
await api().orgs.createSitesPageFeedback(
|
await api().client.orgs.createSitesPageFeedback(
|
||||||
organizationId,
|
organizationId,
|
||||||
siteId,
|
siteId,
|
||||||
siteSpaceId,
|
siteSpaceId,
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {
|
import {
|
||||||
CustomizationBackground,
|
|
||||||
CustomizationCorners,
|
CustomizationCorners,
|
||||||
CustomizationHeaderPreset,
|
CustomizationHeaderPreset,
|
||||||
CustomizationIconsStyle,
|
CustomizationIconsStyle,
|
||||||
CustomizationSettings,
|
CustomizationSettings,
|
||||||
|
CustomizationTint,
|
||||||
SiteCustomizationSettings,
|
SiteCustomizationSettings,
|
||||||
} from '@gitbook/api';
|
} from '@gitbook/api';
|
||||||
import { IconsProvider, IconStyle } from '@gitbook/icons';
|
import { IconsProvider, IconStyle } from '@gitbook/icons';
|
||||||
@@ -11,17 +11,18 @@ import assertNever from 'assert-never';
|
|||||||
import colorContrast from 'postcss-color-contrast/js';
|
import colorContrast from 'postcss-color-contrast/js';
|
||||||
import colors from 'tailwindcss/colors';
|
import colors from 'tailwindcss/colors';
|
||||||
|
|
||||||
import { fonts, ibmPlexMono } from '@/fonts';
|
import { fontNotoColorEmoji, fonts, ibmPlexMono } from '@/fonts';
|
||||||
import { getSpaceLanguage } from '@/intl/server';
|
import { getSpaceLanguage } from '@/intl/server';
|
||||||
import { getStaticFileURL } from '@/lib/assets';
|
import { getStaticFileURL } from '@/lib/assets';
|
||||||
import { hexToRgb, shadesOfColor } from '@/lib/colors';
|
import { hexToRgb, shadesOfColor } from '@/lib/colors';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { ClientContexts } from './ClientContexts';
|
import { ClientContexts } from './ClientContexts';
|
||||||
import { emojiFontClassName } from '../primitives';
|
|
||||||
|
|
||||||
import './globals.css';
|
|
||||||
import '@gitbook/icons/style.css';
|
import '@gitbook/icons/style.css';
|
||||||
|
import './globals.css';
|
||||||
|
|
||||||
|
const DEFAULT_TINT_COLOR = '#787878';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Layout shared between the content and the PDF renderer.
|
* Layout shared between the content and the PDF renderer.
|
||||||
@@ -36,26 +37,21 @@ export async function CustomizationRootLayout(props: {
|
|||||||
const headerTheme = generateHeaderTheme(customization);
|
const headerTheme = generateHeaderTheme(customization);
|
||||||
const language = getSpaceLanguage(customization);
|
const language = getSpaceLanguage(customization);
|
||||||
|
|
||||||
|
const tintColor = getTintColor(customization);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html
|
<html
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
lang={customization.internationalization.locale}
|
lang={customization.internationalization.locale}
|
||||||
className={
|
className={tcls(
|
||||||
tcls(
|
customization.header.preset === CustomizationHeaderPreset.None
|
||||||
customization.header.preset === CustomizationHeaderPreset.None
|
? null
|
||||||
? null
|
: 'scroll-pt-[76px]', // Take the sticky header in consideration for the scrolling
|
||||||
: [
|
customization.styling.corners === CustomizationCorners.Straight
|
||||||
// Take the sticky header in consideration for the scrolling
|
|
||||||
`scroll-pt-[76px]`,
|
|
||||||
],
|
|
||||||
) +
|
|
||||||
(customization.styling.corners === CustomizationCorners.Straight
|
|
||||||
? ' straight-corners'
|
? ' straight-corners'
|
||||||
: '') +
|
: '',
|
||||||
(customization.styling.background === CustomizationBackground.Plain
|
tintColor ? ' tint' : 'no-tint',
|
||||||
? ' plain-background'
|
)}
|
||||||
: '')
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<head>
|
<head>
|
||||||
{customization.privacyPolicy.url ? (
|
{customization.privacyPolicy.url ? (
|
||||||
@@ -87,10 +83,22 @@ export async function CustomizationRootLayout(props: {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
${generateColorVariable(
|
${generateColorVariable('tint-color', tintColor?.light ?? DEFAULT_TINT_COLOR)}
|
||||||
'primary-base',
|
${
|
||||||
customization.styling.primaryColor.light,
|
// Generate the right contrast color for each shade of tint-color
|
||||||
)}
|
generateColorVariable(
|
||||||
|
'contrast-tint',
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.entries(
|
||||||
|
shadesOfColor(tintColor?.light || DEFAULT_TINT_COLOR),
|
||||||
|
).map(([index, color]) => [
|
||||||
|
index,
|
||||||
|
colorContrast(color, ['#000', '#fff']),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
${generateColorVariable(
|
${generateColorVariable(
|
||||||
'header-background',
|
'header-background',
|
||||||
headerTheme.backgroundColor.light,
|
headerTheme.backgroundColor.light,
|
||||||
@@ -103,10 +111,6 @@ export async function CustomizationRootLayout(props: {
|
|||||||
'primary-color',
|
'primary-color',
|
||||||
customization.styling.primaryColor.dark,
|
customization.styling.primaryColor.dark,
|
||||||
)}
|
)}
|
||||||
${generateColorVariable(
|
|
||||||
'primary-base',
|
|
||||||
customization.styling.primaryColor.dark,
|
|
||||||
)}
|
|
||||||
${
|
${
|
||||||
// Generate the right contrast color for each shade of primary-color
|
// Generate the right contrast color for each shade of primary-color
|
||||||
generateColorVariable(
|
generateColorVariable(
|
||||||
@@ -121,6 +125,23 @@ export async function CustomizationRootLayout(props: {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
${generateColorVariable('tint-color', tintColor?.dark ?? DEFAULT_TINT_COLOR)}
|
||||||
|
${
|
||||||
|
// Generate the right contrast color for each shade of tint-color
|
||||||
|
generateColorVariable(
|
||||||
|
'contrast-tint',
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.entries(
|
||||||
|
shadesOfColor(tintColor?.dark || DEFAULT_TINT_COLOR),
|
||||||
|
).map(([index, color]) => [
|
||||||
|
index,
|
||||||
|
colorContrast(color, ['#000', '#fff']),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
${generateColorVariable(
|
${generateColorVariable(
|
||||||
'header-background',
|
'header-background',
|
||||||
headerTheme.backgroundColor.dark,
|
headerTheme.backgroundColor.dark,
|
||||||
@@ -132,7 +153,7 @@ export async function CustomizationRootLayout(props: {
|
|||||||
</head>
|
</head>
|
||||||
<body
|
<body
|
||||||
className={tcls(
|
className={tcls(
|
||||||
emojiFontClassName,
|
fontNotoColorEmoji.className,
|
||||||
`${fonts[customization.styling.font].className}`,
|
`${fonts[customization.styling.font].className}`,
|
||||||
`${ibmPlexMono.variable}`,
|
`${ibmPlexMono.variable}`,
|
||||||
'bg-light',
|
'bg-light',
|
||||||
@@ -160,6 +181,21 @@ export async function CustomizationRootLayout(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the tint color from the customization settings.
|
||||||
|
* If the tint color is not set or it is a space customization, it will return the default color.
|
||||||
|
*/
|
||||||
|
export function getTintColor(
|
||||||
|
customization: CustomizationSettings | SiteCustomizationSettings,
|
||||||
|
): CustomizationTint['color'] | undefined {
|
||||||
|
if ('tint' in customization.styling && customization.styling.tint) {
|
||||||
|
return {
|
||||||
|
light: customization.styling.tint?.color.light ?? DEFAULT_TINT_COLOR,
|
||||||
|
dark: customization.styling.tint?.color.dark ?? DEFAULT_TINT_COLOR,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type ColorInput = string | Record<string, string>;
|
type ColorInput = string | Record<string, string>;
|
||||||
function generateColorVariable(name: string, color: ColorInput) {
|
function generateColorVariable(name: string, color: ColorInput) {
|
||||||
const shades: Record<string, string> = typeof color === 'string' ? shadesOfColor(color) : color;
|
const shades: Record<string, string> = typeof color === 'string' ? shadesOfColor(color) : color;
|
||||||
@@ -177,6 +213,8 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
|||||||
backgroundColor: { light: ColorInput; dark: ColorInput };
|
backgroundColor: { light: ColorInput; dark: ColorInput };
|
||||||
linkColor: { light: ColorInput; dark: ColorInput };
|
linkColor: { light: ColorInput; dark: ColorInput };
|
||||||
} {
|
} {
|
||||||
|
const tintColor = getTintColor(customization);
|
||||||
|
|
||||||
switch (customization.header.preset) {
|
switch (customization.header.preset) {
|
||||||
case CustomizationHeaderPreset.None:
|
case CustomizationHeaderPreset.None:
|
||||||
case CustomizationHeaderPreset.Default: {
|
case CustomizationHeaderPreset.Default: {
|
||||||
@@ -194,17 +232,17 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
|||||||
case CustomizationHeaderPreset.Bold: {
|
case CustomizationHeaderPreset.Bold: {
|
||||||
return {
|
return {
|
||||||
backgroundColor: {
|
backgroundColor: {
|
||||||
light: customization.styling.primaryColor.light,
|
light: tintColor?.light ?? customization.styling.primaryColor.light,
|
||||||
dark: customization.styling.primaryColor.dark,
|
dark: tintColor?.dark ?? customization.styling.primaryColor.dark,
|
||||||
},
|
},
|
||||||
linkColor: {
|
linkColor: {
|
||||||
light: colorContrast(
|
light: colorContrast(
|
||||||
customization.styling.primaryColor.light,
|
tintColor?.light ?? customization.styling.primaryColor.light,
|
||||||
[colors.white, colors.black],
|
[colors.white, colors.black],
|
||||||
'aaa',
|
'aaa',
|
||||||
),
|
),
|
||||||
dark: colorContrast(
|
dark: colorContrast(
|
||||||
customization.styling.primaryColor.dark,
|
tintColor?.dark ?? customization.styling.primaryColor.dark,
|
||||||
[colors.white, colors.black],
|
[colors.white, colors.black],
|
||||||
'aaa',
|
'aaa',
|
||||||
),
|
),
|
||||||
@@ -226,15 +264,25 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
|||||||
case CustomizationHeaderPreset.Custom: {
|
case CustomizationHeaderPreset.Custom: {
|
||||||
return {
|
return {
|
||||||
backgroundColor: {
|
backgroundColor: {
|
||||||
light: customization.header.backgroundColor?.light ?? colors.white,
|
light:
|
||||||
dark: customization.header.backgroundColor?.dark ?? colors.black,
|
customization.header.backgroundColor?.light ??
|
||||||
|
tintColor?.light ??
|
||||||
|
colors.white,
|
||||||
|
dark:
|
||||||
|
customization.header.backgroundColor?.dark ??
|
||||||
|
tintColor?.dark ??
|
||||||
|
colors.black,
|
||||||
},
|
},
|
||||||
linkColor: {
|
linkColor: {
|
||||||
light:
|
light:
|
||||||
customization.header.linkColor?.light ??
|
customization.header.linkColor?.light ??
|
||||||
|
(tintColor?.light &&
|
||||||
|
colorContrast(tintColor.light, [colors.white, colors.black], 'aaa')) ??
|
||||||
customization.styling.primaryColor.light,
|
customization.styling.primaryColor.light,
|
||||||
dark:
|
dark:
|
||||||
customization.header.linkColor?.dark ??
|
customization.header.linkColor?.dark ??
|
||||||
|
(tintColor?.dark &&
|
||||||
|
colorContrast(tintColor.dark, [colors.white, colors.black], 'aaa')) ??
|
||||||
customization.styling.primaryColor.dark,
|
customization.styling.primaryColor.dark,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,30 +4,24 @@
|
|||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
:root {
|
:root {
|
||||||
|
/* See packages/gitbook/src/fonts/index.ts */
|
||||||
|
--font-emoji: 'Apple Color Emoji', var(--font-noto-color-emoji);
|
||||||
--scrollbar-width: calc(100vw - 100%);
|
--scrollbar-width: calc(100vw - 100%);
|
||||||
|
|
||||||
--dark-base: 20 20 20;
|
--dark-base: 20 20 20;
|
||||||
--light-base: 251 252 252;
|
--light-base: 251 251 251;
|
||||||
|
|
||||||
--light-1: color-mix(in srgb, rgb(var(--primary-base-600)), rgb(var(--light-base)) 99%);
|
--light-1: color-mix(in srgb, rgb(var(--tint-color-600)), rgb(var(--light-base)) 99%);
|
||||||
--light-DEFAULT: color-mix(
|
--light-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 96%);
|
||||||
in srgb,
|
--light-2: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 94%);
|
||||||
rgb(var(--primary-base-700)),
|
--light-3: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 88%);
|
||||||
rgb(var(--light-base)) 96%
|
--light-4: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 72%);
|
||||||
);
|
|
||||||
--light-2: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 92%);
|
|
||||||
--light-3: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 88%);
|
|
||||||
--light-4: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 72%);
|
|
||||||
|
|
||||||
--dark-1: color-mix(in srgb, rgb(var(--primary-base-100)), rgb(1 1 1) 96%);
|
--dark-1: color-mix(in srgb, rgb(var(--tint-color-400)), rgb(var(--dark-base)) 96%);
|
||||||
--dark-DEFAULT: color-mix(
|
--dark-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 94%);
|
||||||
in srgb,
|
--dark-2: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 92%);
|
||||||
rgb(var(--primary-base-300)),
|
--dark-3: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 91%);
|
||||||
rgb(var(--dark-base)) 94.5%
|
--dark-4: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 64%);
|
||||||
);
|
|
||||||
--dark-2: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(var(--dark-base)) 92%);
|
|
||||||
--dark-3: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(25 25 25) 91%);
|
|
||||||
--dark-4: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(var(--dark-base)) 64%);
|
|
||||||
@apply leading-relaxed;
|
@apply leading-relaxed;
|
||||||
}
|
}
|
||||||
body {
|
body {
|
||||||
@@ -36,29 +30,13 @@
|
|||||||
html {
|
html {
|
||||||
@apply gutter-stable;
|
@apply gutter-stable;
|
||||||
}
|
}
|
||||||
html:is(.plain-background) {
|
html:is(.no-tint) {
|
||||||
--dark-base: 22 22 22;
|
|
||||||
--light-base: 255 255 255;
|
--light-base: 255 255 255;
|
||||||
/* reset primaries as greys */
|
|
||||||
--primary-base-50: 239 239 239;
|
|
||||||
--primary-base-100: 222 222 222;
|
|
||||||
--primary-base-200: 200 200 200;
|
|
||||||
--primary-base-300: 180 180 180;
|
|
||||||
--primary-base-400: 150 150 150;
|
|
||||||
--primary-base-500: 120 120 120;
|
|
||||||
--primary-base-600: 90 90 90;
|
|
||||||
--primary-base-700: 70 70 70;
|
|
||||||
--primary-base-800: 30 30 30;
|
|
||||||
--primary-base-900: 19 19 19;
|
|
||||||
|
|
||||||
--light-DEFAULT: color-mix(
|
--light-DEFAULT: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
rgb(var(--primary-base-700)),
|
rgb(var(--tint-color-500)),
|
||||||
rgb(var(--light-base)) 100%
|
rgb(var(--light-base)) 100%
|
||||||
);
|
);
|
||||||
--light-2: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 96%);
|
|
||||||
--light-3: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 90%);
|
|
||||||
--light-4: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 76%);
|
|
||||||
}
|
}
|
||||||
h1 {
|
h1 {
|
||||||
@apply tracking-[-0.025em] text-dark dark:text-light text-balance;
|
@apply tracking-[-0.025em] text-dark dark:text-light text-balance;
|
||||||
@@ -216,3 +194,9 @@ html {
|
|||||||
html.dark {
|
html.dark {
|
||||||
color-scheme: dark light;
|
color-scheme: dark light;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Emojis */
|
||||||
|
|
||||||
|
[class*='emoji'] {
|
||||||
|
font-family: var(--font-emoji);
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,18 +25,22 @@ export function HighlightQuery(props: {
|
|||||||
'py-0.5',
|
'py-0.5',
|
||||||
'rounded',
|
'rounded',
|
||||||
'straight-corners:rounded-sm',
|
'straight-corners:rounded-sm',
|
||||||
|
'group-[.is-active]:bg-primary-200',
|
||||||
|
'group-[.is-active]:text-contrast-primary-200',
|
||||||
|
'dark:group-[.is-active]:bg-primary-700',
|
||||||
|
'dark:group-[.is-active]:text-contrast-primary-700',
|
||||||
],
|
],
|
||||||
} = props;
|
} = props;
|
||||||
const matches = matchString(text, query);
|
const matches = matchString(text, query);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={tcls('whitespace-break-spaces')}>
|
<span className={tcls('whitespace-break-spaces')}>
|
||||||
{matches.map((entry, index) => (
|
{matches.map((entry, index) => (
|
||||||
<span key={index} className={tcls(entry.match ? highlight : null)}>
|
<span key={index} className={tcls(entry.match ? highlight : null)}>
|
||||||
{entry.text}
|
{entry.text}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
import { Icon } from '@gitbook/icons';
|
import { Icon } from '@gitbook/icons';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { atom, useRecoilState } from 'recoil';
|
import { atom, useRecoilState } from 'recoil';
|
||||||
@@ -7,29 +9,31 @@ import { useLanguage } from '@/intl/client';
|
|||||||
import { t } from '@/intl/translate';
|
import { t } from '@/intl/translate';
|
||||||
import { TranslationLanguage } from '@/intl/translations';
|
import { TranslationLanguage } from '@/intl/translations';
|
||||||
import { iterateStreamResponse } from '@/lib/actions';
|
import { iterateStreamResponse } from '@/lib/actions';
|
||||||
|
import { SiteContentPointer } from '@/lib/api';
|
||||||
import { tcls } from '@/lib/tailwind';
|
import { tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
|
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
|
||||||
import { useSearch, useSearchLink } from './useSearch';
|
import { useSearch, useSearchLink } from './useSearch';
|
||||||
|
import { useTrackEvent } from '../Insights';
|
||||||
import { Link } from '../primitives';
|
import { Link } from '../primitives';
|
||||||
|
|
||||||
/**
|
type SearchState =
|
||||||
* Store the state of the answer in a global state so that it can be
|
|
||||||
* accessed from anywhere to show a loading indicator.
|
|
||||||
*/
|
|
||||||
export const searchAskState = atom<
|
|
||||||
| {
|
| {
|
||||||
type: 'answer';
|
type: 'answer';
|
||||||
answer: AskAnswerResult | null;
|
answer: AskAnswerResult;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: 'error';
|
type: 'error';
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: 'loading';
|
type: 'loading';
|
||||||
}
|
};
|
||||||
| null
|
|
||||||
>({
|
/**
|
||||||
|
- * Store the state of the answer in a global state so that it can be
|
||||||
|
- * accessed from anywhere to show a loading indicator.
|
||||||
|
- */
|
||||||
|
export const searchAskState = atom<SearchState | null>({
|
||||||
key: 'searchAskState',
|
key: 'searchAskState',
|
||||||
default: null,
|
default: null,
|
||||||
});
|
});
|
||||||
@@ -37,51 +41,46 @@ export const searchAskState = atom<
|
|||||||
/**
|
/**
|
||||||
* Fetch and render the answers to a question.
|
* Fetch and render the answers to a question.
|
||||||
*/
|
*/
|
||||||
export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: string }) {
|
||||||
const { spaceId, query } = props;
|
const { pointer, query } = props;
|
||||||
|
|
||||||
const language = useLanguage();
|
const language = useLanguage();
|
||||||
|
// const trackEvent = useTrackEvent();
|
||||||
const [, setSearchState] = useSearch();
|
const [, setSearchState] = useSearch();
|
||||||
const [state, setState] = useRecoilState(searchAskState);
|
const [state, setState] = useRecoilState(searchAskState);
|
||||||
|
const { organizationId, siteId, siteSpaceId } = pointer;
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
setState({
|
setState({ type: 'loading' });
|
||||||
type: 'loading',
|
|
||||||
});
|
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const stream = iterateStreamResponse(streamAskQuestion(spaceId, query));
|
// trackEvent({
|
||||||
|
// type: 'ask_question',
|
||||||
|
// query,
|
||||||
|
// });
|
||||||
|
|
||||||
setSearchState((prev) =>
|
const response = streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query);
|
||||||
prev
|
const stream = iterateStreamResponse(response);
|
||||||
? {
|
|
||||||
...prev,
|
// When we pass in "ask" mode, the query could still be updated by the client
|
||||||
ask: true,
|
// we ensure that the query is up-to-date before starting the stream.
|
||||||
query,
|
setSearchState((prev) => (prev ? { ...prev, query, ask: true } : null));
|
||||||
}
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
|
|
||||||
for await (const chunk of stream) {
|
for await (const chunk of stream) {
|
||||||
if (cancelled) {
|
if (cancelled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setState({
|
setState({ type: 'answer', answer: chunk });
|
||||||
type: 'answer',
|
|
||||||
answer: chunk,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
})().catch((error) => {
|
})().catch(() => {
|
||||||
if (cancelled) {
|
if (cancelled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setState({
|
setState({ type: 'error' });
|
||||||
type: 'error',
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -91,7 +90,7 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
|||||||
cancelled = true;
|
cancelled = true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [spaceId, query, setSearchState, setState]);
|
}, [organizationId, siteId, siteSpaceId, query, setState, setSearchState]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -108,15 +107,9 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
|||||||
return (
|
return (
|
||||||
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
|
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
|
||||||
{state?.type === 'answer' ? (
|
{state?.type === 'answer' ? (
|
||||||
<>
|
<React.Suspense fallback={loading}>
|
||||||
{state.answer ? (
|
<TransitionAnswerBody answer={state.answer} placeholder={loading} />
|
||||||
<React.Suspense fallback={loading}>
|
</React.Suspense>
|
||||||
<TransitionAnswerBody answer={state.answer} placeholder={loading} />
|
|
||||||
</React.Suspense>
|
|
||||||
) : (
|
|
||||||
<div className={tcls('p-4')}>{t(language, 'search_ask_no_answer')}</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : null}
|
) : null}
|
||||||
{state?.type === 'error' ? (
|
{state?.type === 'error' ? (
|
||||||
<div className={tcls('p-4')}>{t(language, 'search_ask_error')}</div>
|
<div className={tcls('p-4')}>{t(language, 'search_ask_error')}</div>
|
||||||
@@ -159,7 +152,7 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
|
|||||||
<div
|
<div
|
||||||
data-test="search-ask-answer"
|
data-test="search-ask-answer"
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'mt-4',
|
'my-4',
|
||||||
'sm:mt-6',
|
'sm:mt-6',
|
||||||
'px-4',
|
'px-4',
|
||||||
'sm:px-12',
|
'sm:px-12',
|
||||||
@@ -167,16 +160,16 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
|
|||||||
'dark:text-light/8',
|
'dark:text-light/8',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{answer.hasAnswer ? answer.body : t(language, 'search_ask_no_answer')}
|
{answer.body ?? t(language, 'search_ask_no_answer')}
|
||||||
{answer.followupQuestions.length > 0 ? (
|
{answer.followupQuestions.length > 0 ? (
|
||||||
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
|
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{answer.sources.length > 0 ? (
|
{answer.sources.length > 0 ? (
|
||||||
<AnswerSources
|
<AnswerSources
|
||||||
hasAnswer={answer.hasAnswer}
|
|
||||||
sources={answer.sources}
|
sources={answer.sources}
|
||||||
language={language}
|
language={language}
|
||||||
|
hasAnswer={Boolean(answer.body)}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
@@ -233,7 +226,7 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
|
|||||||
function AnswerSources(props: {
|
function AnswerSources(props: {
|
||||||
sources: AskAnswerSource[];
|
sources: AskAnswerSource[];
|
||||||
language: TranslationLanguage;
|
language: TranslationLanguage;
|
||||||
hasAnswer?: boolean;
|
hasAnswer: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { sources, language, hasAnswer } = props;
|
const { sources, language, hasAnswer } = props;
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { Icon } from '@gitbook/icons';
|
import { Icon } from '@gitbook/icons';
|
||||||
|
import { motion } from 'framer-motion';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { useLanguage, tString } from '@/intl/client';
|
import { useLanguage, tString } from '@/intl/client';
|
||||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||||
|
|
||||||
import { useSearch } from './useSearch';
|
import { useSearch } from './useSearch';
|
||||||
|
import { useTrackEvent } from '../Insights';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Button to open the search modal.
|
* Button to open the search modal.
|
||||||
@@ -16,6 +18,7 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
|||||||
|
|
||||||
const language = useLanguage();
|
const language = useLanguage();
|
||||||
const [, setSearchState] = useSearch();
|
const [, setSearchState] = useSearch();
|
||||||
|
// const trackEvent = useTrackEvent();
|
||||||
|
|
||||||
const onClick = () => {
|
const onClick = () => {
|
||||||
setSearchState({
|
setSearchState({
|
||||||
@@ -23,6 +26,10 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
|||||||
global: false,
|
global: false,
|
||||||
query: '',
|
query: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// trackEvent({
|
||||||
|
// type: 'search_open',
|
||||||
|
// });
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -35,45 +42,69 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
|||||||
'flex-row',
|
'flex-row',
|
||||||
'justify-center',
|
'justify-center',
|
||||||
'items-center',
|
'items-center',
|
||||||
'px-2',
|
'w-full',
|
||||||
'gap-3',
|
'px-3',
|
||||||
'text-dark/7',
|
'py-2',
|
||||||
'min-h-[2.5rem]',
|
'gap-2',
|
||||||
'w-[2.5rem]',
|
|
||||||
'rounded-lg',
|
'bg-light',
|
||||||
'straight-corners:rounded-none',
|
'dark:bg-dark',
|
||||||
'bg-dark/2',
|
|
||||||
'transition-colors',
|
|
||||||
'transition-opacity',
|
|
||||||
'ease-out',
|
|
||||||
'hover:opacity-8',
|
|
||||||
'ring-1',
|
'ring-1',
|
||||||
'ring-inset',
|
|
||||||
'ring-dark/1',
|
'ring-dark/1',
|
||||||
|
'dark:ring-light/2',
|
||||||
|
|
||||||
|
'shadow-sm',
|
||||||
|
'shadow-dark/4',
|
||||||
|
'dark:shadow-none',
|
||||||
|
|
||||||
|
'text-dark/7',
|
||||||
|
'dark:text-light-4/7',
|
||||||
|
|
||||||
|
'rounded-lg',
|
||||||
|
'straight-corners:rounded-sm',
|
||||||
|
|
||||||
'contrast-more:ring-dark',
|
'contrast-more:ring-dark',
|
||||||
'contrast-more:bg-light',
|
|
||||||
'contrast-more:text-dark',
|
'contrast-more:text-dark',
|
||||||
'dark:bg-light/1',
|
|
||||||
'dark:ring-light/1',
|
|
||||||
'dark:text-light/7',
|
|
||||||
'contrast-more:dark:ring-light',
|
'contrast-more:dark:ring-light',
|
||||||
'contrast-more:dark:bg-dark',
|
|
||||||
'contrast-more:dark:text-light',
|
'contrast-more:dark:text-light',
|
||||||
'[&>p]:hidden',
|
|
||||||
'[&>span]:hidden',
|
'transition-all',
|
||||||
|
'hover:shadow-md',
|
||||||
|
'hover:scale-102',
|
||||||
|
'hover:ring-dark/2',
|
||||||
|
'hover:text-dark/10',
|
||||||
|
'focus:shadow-md',
|
||||||
|
'focus:scale-102',
|
||||||
|
'focus:ring-dark/2',
|
||||||
|
'focus:text-dark/10',
|
||||||
|
'dark:hover:bg-dark-3',
|
||||||
|
'dark:hover:ring-light/4',
|
||||||
|
'dark:hover:text-light',
|
||||||
|
'dark:focus:bg-dark-3',
|
||||||
|
'dark:focus:ring-light/4',
|
||||||
|
'dark:focus:text-light',
|
||||||
|
|
||||||
|
'contrast-more:hover:ring-2',
|
||||||
|
'contrast-more:hover:ring-dark',
|
||||||
|
'dark:contrast-more:hover:ring-light',
|
||||||
|
'contrast-more:focus:ring-2',
|
||||||
|
'contrast-more:focus:ring-dark',
|
||||||
|
'dark:contrast-more:focus:ring-light',
|
||||||
|
|
||||||
|
'active:shadow-sm',
|
||||||
|
'active:scale-98',
|
||||||
|
|
||||||
'md:justify-start',
|
'md:justify-start',
|
||||||
'md:[&>p]:flex',
|
|
||||||
'md:[&>span]:flex',
|
|
||||||
'md:w-full',
|
'md:w-full',
|
||||||
'md:px-3.5',
|
|
||||||
'text-base',
|
|
||||||
style,
|
style,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className={tcls('text-dark/7', 'pt-1.5', 'pb-2', 'dark:text-light/7')}>
|
<Icon
|
||||||
<Icon icon="magnifying-glass" className={tcls('shrink-0', 'size-4')} />
|
icon="magnifying-glass"
|
||||||
</div>
|
className={tcls('text-dark/8', 'dark:text-light/8', 'shrink-0', 'size-4')}
|
||||||
{children}
|
/>
|
||||||
|
<div className={tcls('w-full', 'hidden', 'md:block', 'text-left')}>{children}</div>
|
||||||
<Shortcut />
|
<Shortcut />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@@ -96,20 +127,22 @@ const Shortcut = () => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span
|
<div
|
||||||
className={tcls(
|
className={tcls(
|
||||||
|
'shortcut',
|
||||||
'hidden',
|
'hidden',
|
||||||
'md:inline',
|
'md:inline',
|
||||||
'justify-end',
|
'justify-end',
|
||||||
'text-xs',
|
'text-xs',
|
||||||
'text-dark/5',
|
'text-dark/7',
|
||||||
'contrast-more:text-dark',
|
'contrast-more:text-dark',
|
||||||
'dark:text-light/5',
|
'dark:text-light-4/7',
|
||||||
'contrast-more:dark:text-light',
|
'contrast-more:dark:text-light',
|
||||||
|
'whitespace-nowrap',
|
||||||
`[font-feature-settings:"calt",_"case"]`,
|
`[font-feature-settings:"calt",_"case"]`,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{operatingSystem === 'mac' ? '⌘' : 'Ctrl +'} K
|
{operatingSystem === 'mac' ? '⌘' : 'Ctrl +'} K
|
||||||
</span>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { Collection, Site } from '@gitbook/api';
|
|
||||||
import { Icon } from '@gitbook/icons';
|
import { Icon } from '@gitbook/icons';
|
||||||
import { AnimatePresence, motion } from 'framer-motion';
|
import { AnimatePresence, motion } from 'framer-motion';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
@@ -15,7 +14,7 @@ import { tcls } from '@/lib/tailwind';
|
|||||||
import { SearchAskAnswer, searchAskState } from './SearchAskAnswer';
|
import { SearchAskAnswer, searchAskState } from './SearchAskAnswer';
|
||||||
import { SearchResults, SearchResultsRef } from './SearchResults';
|
import { SearchResults, SearchResultsRef } from './SearchResults';
|
||||||
import { SearchScopeToggle } from './SearchScopeToggle';
|
import { SearchScopeToggle } from './SearchScopeToggle';
|
||||||
import { SearchState, useSearch } from './useSearch';
|
import { SearchState, UpdateSearchState, useSearch } from './useSearch';
|
||||||
import { LoadingPane } from '../primitives/LoadingPane';
|
import { LoadingPane } from '../primitives/LoadingPane';
|
||||||
|
|
||||||
interface SearchModalProps {
|
interface SearchModalProps {
|
||||||
@@ -56,14 +55,6 @@ export function SearchModal(props: SearchModalProps) {
|
|||||||
};
|
};
|
||||||
}, [isSearchOpened]);
|
}, [isSearchOpened]);
|
||||||
|
|
||||||
if (state === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const onChangeQuery = (newQuery: SearchState) => {
|
|
||||||
setSearchState(newQuery);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onClose = async (to?: string) => {
|
const onClose = async (to?: string) => {
|
||||||
await setSearchState(null);
|
await setSearchState(null);
|
||||||
if (to) {
|
if (to) {
|
||||||
@@ -72,69 +63,82 @@ export function SearchModal(props: SearchModalProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<AnimatePresence>
|
||||||
<div
|
{state !== null ? (
|
||||||
role="dialog"
|
<motion.div
|
||||||
className={tcls(
|
initial={{
|
||||||
'flex',
|
opacity: 0,
|
||||||
'items-start',
|
}}
|
||||||
'justify-center',
|
animate={{
|
||||||
'fixed',
|
opacity: 1,
|
||||||
'inset-0',
|
}}
|
||||||
'bg-dark/4',
|
exit={{
|
||||||
'backdrop-blur-2xl',
|
opacity: 0,
|
||||||
'opacity-[1]',
|
}}
|
||||||
'z-30',
|
transition={{
|
||||||
'px-4',
|
duration: 0.2,
|
||||||
'pt-4',
|
delay: 0.1,
|
||||||
'dark:bg-dark/8',
|
}}
|
||||||
'md:pt-[min(8vw,_6rem)]',
|
role="dialog"
|
||||||
)}
|
className={tcls(
|
||||||
onClick={() => {
|
'fixed',
|
||||||
onClose();
|
'inset-0',
|
||||||
}}
|
'bg-dark/4',
|
||||||
>
|
'backdrop-blur-2xl',
|
||||||
<AnimatePresence>
|
'z-30',
|
||||||
{askState?.type === 'loading' ? (
|
'px-4',
|
||||||
<motion.div
|
'pt-4',
|
||||||
key="loading"
|
'dark:bg-dark/8',
|
||||||
initial={{ opacity: 0 }}
|
'md:pt-[min(8vh,6rem)]',
|
||||||
animate={{ opacity: 1 }}
|
)}
|
||||||
exit={{ opacity: 0 }}
|
onClick={() => {
|
||||||
transition={{ duration: 1 }}
|
onClose();
|
||||||
className={tcls(
|
}}
|
||||||
'w-[100vw]',
|
>
|
||||||
'h-[100vh]',
|
<div className="scroll-nojump">
|
||||||
'fixed',
|
<AnimatePresence>
|
||||||
'inset-0',
|
{askState?.type === 'loading' ? (
|
||||||
'z-10',
|
<motion.div
|
||||||
'pointer-events-none',
|
key="loading"
|
||||||
)}
|
initial={{ opacity: 0 }}
|
||||||
>
|
animate={{ opacity: 1 }}
|
||||||
<LoadingPane
|
exit={{ opacity: 0 }}
|
||||||
gridStyle={['h-[100vh]', 'aspect-auto', 'top-[-30%]']}
|
transition={{ duration: 1 }}
|
||||||
pulse
|
className={tcls(
|
||||||
tile={96}
|
'w-screen',
|
||||||
style={['grid']}
|
'h-screen',
|
||||||
/>
|
'fixed',
|
||||||
</motion.div>
|
'inset-0',
|
||||||
) : null}
|
'z-10',
|
||||||
</AnimatePresence>
|
'pointer-events-none',
|
||||||
<SearchModalBody
|
)}
|
||||||
{...props}
|
>
|
||||||
state={state}
|
<LoadingPane
|
||||||
onChangeQuery={onChangeQuery}
|
gridStyle={['h-screen', 'aspect-auto', 'top-[-30%]']}
|
||||||
onClose={onClose}
|
pulse
|
||||||
/>
|
tile={96}
|
||||||
</div>
|
style={['grid']}
|
||||||
</>
|
/>
|
||||||
|
</motion.div>
|
||||||
|
) : null}
|
||||||
|
</AnimatePresence>
|
||||||
|
<SearchModalBody
|
||||||
|
{...props}
|
||||||
|
state={state}
|
||||||
|
setSearchState={setSearchState}
|
||||||
|
onClose={onClose}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
) : null}
|
||||||
|
</AnimatePresence>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SearchModalBody(
|
function SearchModalBody(
|
||||||
props: SearchModalProps & {
|
props: SearchModalProps & {
|
||||||
state: SearchState;
|
state: SearchState;
|
||||||
onChangeQuery: (newQuery: SearchState) => void;
|
setSearchState: UpdateSearchState;
|
||||||
onClose: (to?: string) => void;
|
onClose: (to?: string) => void;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
@@ -146,7 +150,7 @@ function SearchModalBody(
|
|||||||
withAsk,
|
withAsk,
|
||||||
isMultiVariants,
|
isMultiVariants,
|
||||||
state,
|
state,
|
||||||
onChangeQuery,
|
setSearchState,
|
||||||
onClose,
|
onClose,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
@@ -158,10 +162,21 @@ function SearchModalBody(
|
|||||||
inputRef.current?.focus();
|
inputRef.current?.focus();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('keydown', handleKeyDown);
|
||||||
|
};
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
if (event.key === 'Escape') {
|
if (event.key === 'ArrowUp') {
|
||||||
onClose();
|
|
||||||
} else if (event.key === 'ArrowUp') {
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
resultsRef.current?.moveUp();
|
resultsRef.current?.moveUp();
|
||||||
} else if (event.key === 'ArrowDown') {
|
} else if (event.key === 'ArrowDown') {
|
||||||
@@ -174,24 +189,47 @@ function SearchModalBody(
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
onChangeQuery({
|
setSearchState({
|
||||||
ask: false, // When typing, we go back to the default search mode
|
ask: false, // When typing, we go back to the default search mode
|
||||||
query: event.target.value,
|
query: event.target.value,
|
||||||
global: state.global,
|
global: state.global,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onSwitchToAsk = () => {
|
||||||
|
setSearchState((state) => (state ? { ...state, ask: true } : null));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<motion.div
|
<motion.div
|
||||||
|
transition={{
|
||||||
|
duration: 0.2,
|
||||||
|
delay: 0.1,
|
||||||
|
ease: 'easeOut',
|
||||||
|
}}
|
||||||
|
initial={{
|
||||||
|
scale: 0.95,
|
||||||
|
opacity: 0,
|
||||||
|
}}
|
||||||
|
animate={{
|
||||||
|
scale: 1,
|
||||||
|
opacity: 1,
|
||||||
|
}}
|
||||||
|
exit={{
|
||||||
|
scale: 0.95,
|
||||||
|
opacity: 0,
|
||||||
|
}}
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-label={tString(language, 'search')}
|
aria-label={tString(language, 'search')}
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'z-40',
|
'z-40',
|
||||||
|
'relative',
|
||||||
'flex',
|
'flex',
|
||||||
'flex-col',
|
'flex-col',
|
||||||
'bg-white',
|
'bg-white',
|
||||||
'max-w-[768px]',
|
'max-w-prose',
|
||||||
'mt-[-1px]',
|
'mx-auto',
|
||||||
|
'max-h-[70dvh]',
|
||||||
'w-full',
|
'w-full',
|
||||||
'rounded-lg',
|
'rounded-lg',
|
||||||
'straight-corners:rounded-sm',
|
'straight-corners:rounded-sm',
|
||||||
@@ -203,14 +241,6 @@ function SearchModalBody(
|
|||||||
'dark:bg-dark-3',
|
'dark:bg-dark-3',
|
||||||
'dark:ring-light/2',
|
'dark:ring-light/2',
|
||||||
)}
|
)}
|
||||||
initial={{
|
|
||||||
scale: 0.95,
|
|
||||||
opacity: 0,
|
|
||||||
}}
|
|
||||||
animate={{
|
|
||||||
scale: 1,
|
|
||||||
opacity: 1,
|
|
||||||
}}
|
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
}}
|
}}
|
||||||
@@ -281,17 +311,11 @@ function SearchModalBody(
|
|||||||
global={isMultiVariants && state.global}
|
global={isMultiVariants && state.global}
|
||||||
query={state.query}
|
query={state.query}
|
||||||
withAsk={withAsk}
|
withAsk={withAsk}
|
||||||
onSwitchToAsk={() => {
|
onSwitchToAsk={onSwitchToAsk}
|
||||||
onChangeQuery({
|
|
||||||
ask: true,
|
|
||||||
query: state.query,
|
|
||||||
global: state.global,
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
></SearchResults>
|
></SearchResults>
|
||||||
) : null}
|
) : null}
|
||||||
{state.query && state.ask && withAsk ? (
|
{state.query && state.ask && withAsk ? (
|
||||||
<SearchAskAnswer spaceId={spaceId} query={state.query} />
|
<SearchAskAnswer pointer={pointer} query={state.query} />
|
||||||
) : null}
|
) : null}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -23,26 +23,38 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
|||||||
href={item.href}
|
href={item.href}
|
||||||
className={tcls(
|
className={tcls(
|
||||||
'flex',
|
'flex',
|
||||||
|
'gap-4',
|
||||||
'flex-row',
|
'flex-row',
|
||||||
'items-center',
|
'items-center',
|
||||||
'px-4',
|
'p-4',
|
||||||
'sm:px-12',
|
|
||||||
'py-4',
|
|
||||||
'sm:py-6',
|
|
||||||
'border-t',
|
'border-t',
|
||||||
'first:border-t-0',
|
|
||||||
'border-dark/2',
|
'border-dark/2',
|
||||||
'dark:border-light/2',
|
'dark:border-light/1',
|
||||||
'hover:bg-dark-4/2',
|
'first:border-none',
|
||||||
'text-base',
|
'text-base',
|
||||||
'text-dark',
|
|
||||||
'font-medium',
|
'font-medium',
|
||||||
'first:mt-0',
|
'hover:bg-dark/1',
|
||||||
'dark:text-light',
|
'dark:hover:bg-light/1',
|
||||||
'dark:hover:bg-light-4/2',
|
'group',
|
||||||
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
|
active
|
||||||
|
? [
|
||||||
|
'is-active',
|
||||||
|
'bg-primary-50',
|
||||||
|
'text-contrast-primary-50',
|
||||||
|
'dark:bg-primary-800',
|
||||||
|
'dark:text-contrast-primary-800',
|
||||||
|
'hover:bg-primary-100/8',
|
||||||
|
'dark:hover:bg-primary-700/7',
|
||||||
|
]
|
||||||
|
: null,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
<div className="size-4">
|
||||||
|
<Icon
|
||||||
|
icon="file-lines"
|
||||||
|
className={tcls('size-4', active ? 'text-primary' : 'opacity-5')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className={tcls('flex', 'flex-col', 'w-full')}>
|
<div className={tcls('flex', 'flex-col', 'w-full')}>
|
||||||
{item.spaceTitle ? (
|
{item.spaceTitle ? (
|
||||||
<div
|
<div
|
||||||
@@ -60,10 +72,19 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
|||||||
) : null}
|
) : null}
|
||||||
<HighlightQuery query={query} text={item.title} />
|
<HighlightQuery query={query} text={item.title} />
|
||||||
</div>
|
</div>
|
||||||
<Icon
|
<div
|
||||||
icon="chevron-right"
|
className={tcls(
|
||||||
className={tcls('size-4', 'text-dark', 'dark:text-light', 'opacity-6')}
|
'p-2',
|
||||||
/>
|
'rounded',
|
||||||
|
'straight-corners:rounded-none',
|
||||||
|
active ? ['bg-primary', 'text-contrast-primary'] : ['opacity-6'],
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon={active ? 'arrow-turn-down-left' : 'chevron-right'}
|
||||||
|
className={tcls('size-4')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user