Compare commits

...

71 Commits

Author SHA1 Message Date
Samy Pessé f64d5073d4 Version Packages (#2557)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-18 10:25:08 +01:00
Samy Pessé 53b9f10ac8 Prepare @gitbook/proxy to support serving under sub-directory (#2641) 2024-12-18 10:05:31 +01:00
Samy Pessé 75606e4df7 Fix missing env GITBOOK_ASSETS_PREFIX passed to build (#2642) 2024-12-17 21:46:04 +01:00
Claire Chabas 0643b7f351 Improve ask/search Enter key press UX (#2624)
Co-authored-by: Zeno Kapitein <admin@zeno.zone>
2024-12-17 18:08:29 +01:00
Claire Chabas 5b3b4e0614 Fix closing search modal on Escape key press (#2637) 2024-12-17 15:33:36 +01:00
Samy Pessé 8d039d1348 Pass down ancestors instead of computing them (#2635) 2024-12-16 21:11:46 +01:00
Zeno Kapitein 87eea73081 Fix margin and image resolution of header logo (#2633) 2024-12-16 14:34:00 +01:00
Zeno Kapitein 67a6fb4c87 Fix localised search string from wrapping search box (#2630) 2024-12-13 16:48:06 +01:00
Zeno Kapitein 23584c9862 Update header styling (#2613)
Co-authored-by: Valentino Hudhra <v.hudhra@gmail.com>
Co-authored-by: Valentino Hudhra <2587839+valentin0h@users.noreply.github.com>
2024-12-13 15:51:23 +01:00
Zeno Kapitein 2f767125c4 Add breadcrumbs to page header (#2628) 2024-12-13 15:20:07 +01:00
Greg Bergé c73e07d42d Increase token max length to fix code not highlighted (#2629) 2024-12-13 13:16:55 +01:00
Viktor Renkema 6b5d7e6057 Improve styles of Tables (#2623) 2024-12-13 08:15:52 +01:00
Greg Bergé 076dc48e89 Fix expandable block anchor resolution (#2625) 2024-12-12 23:25:29 +01:00
Greg Bergé bb208ab36a Update JoyPixels (#2619) 2024-12-12 09:05:12 +01:00
Viktor Renkema 60e35001b6 Refactor Table to use flex layouts (#2622) 2024-12-11 21:34:37 +01:00
Greg Bergé 29a0d7ea02 Fix sublinks display on mobile (#2620) 2024-12-11 18:57:55 +01:00
Greg Bergé 1f2b7f7acf Prevent resizing AVIF (not supported by Cloudflare) (#2621) 2024-12-11 15:17:25 +01:00
spastorelli 39e5cb63ef Fix context Id not returned by lookupSpaceByAPI (#2618) 2024-12-11 10:54:17 +01:00
spastorelli 5b5928fb8d Fix VA e2e tests when ran locally (#2617) 2024-12-11 08:34:05 +01:00
Greg Bergé 08068743a5 Remove Next.js cache on CI (#2616) 2024-12-10 18:53:47 +01:00
Greg Bergé 35eae1adcf Fix canonical in a safe way (#2589) 2024-12-10 17:47:57 +01:00
Greg Bergé e85d357abd Fix React DOM warning (#2615) 2024-12-10 17:39:22 +01:00
spastorelli 31396d8109 Adapt GBO cache logic to support users sessions info (#2606) 2024-12-10 14:11:59 +01:00
Zeno Kapitein 664debc0bc Add tint color (#2605)
Co-authored-by: Valentino Hudhra <v.hudhra@gmail.com>
Co-authored-by: Valentino Hudhra <2587839+valentin0h@users.noreply.github.com>
2024-12-09 17:19:44 +01:00
Viktor Renkema 56c31c76b3 Center-align inline images (#2609) 2024-12-09 13:21:43 +01:00
Viktor Renkema 2d1a71f3d1 Allow cells in tables to use more available space (#2611) 2024-12-09 13:11:05 +01:00
Valentino Hudhra c67cd73058 Add visual tests for tint (#2601) 2024-12-09 12:29:03 +01:00
Greg Bergé 2572cb4352 Pin React versions (#2610) 2024-12-09 11:14:02 +01:00
Steven H c9f6c7ccac Fix an issue where Ask AI answers with too many sources could crash the Worker. (#2608) 2024-12-07 15:23:10 +00:00
Steven Hall b6520b0dbc hotfix: Fix an issue where Ask AI was crashing on some requests. 2024-12-06 22:26:41 +00:00
Steven H 9fe8142117 Fix an issue where Ask AI was erroring due to an object being passed as a param. (#2607) 2024-12-06 21:55:59 +00:00
Steven H 57cdd25b5f Ask AI now goes through the site API instead of spaces. (#2598) 2024-12-06 20:06:49 +00:00
Samy Pessé 1005ee5d52 Prevent resizing the url of an image already resized (#2600) 2024-12-05 16:34:31 +01:00
Valentino Hudhra d9bb9f9a07 Fix cookie banner button being non responsive (#2599) 2024-12-05 14:04:03 +01:00
Greg Bergé 75a6fabe61 Support dropdown without link (#2596) 2024-12-04 12:05:17 +01:00
Greg Bergé 75e29b69cc Allow to work locally (#2597) 2024-12-03 14:49:13 +01:00
Samy Pessé ffd3937538 Fix security issue with images resizing (#2595) 2024-12-03 08:51:46 +01:00
Valentino Hudhra 575587e4c5 Improve footer link styling (#2591) 2024-12-01 07:54:45 +01:00
Brett Jephson 2ce59d7c92 Fix whitespace added with image (#2594) 2024-11-29 17:10:29 +00:00
Brett Jephson 3b3d6e2a73 Add an icon to site sections (#2593) 2024-11-29 16:09:06 +00:00
Zeno Kapitein f2a467fdbf Fix hint block decoration color (#2590) 2024-11-29 16:40:10 +01:00
vibhanshub 867481c66d Support Integers in Response sample (#2592) 2024-11-28 14:19:37 +00:00
spastorelli fc8065b7a8 Revert "Fix canonical URL ending with "/" (#2586)" (#2588) 2024-11-27 13:05:34 +01:00
Greg Bergé 28f1ed9205 Fix canonical URL ending with "/" (#2586) 2024-11-26 21:57:15 +01:00
Viktor Renkema 568266bc9a Add transitions to Sections bg and line (#2491) 2024-11-26 19:59:07 +01:00
Samy Pessé 7739f341b8 Revert "Serve the correct status code for not found and redirects 👌" (#2587) 2024-11-26 18:36:00 +01:00
Greg Bergé 2b501f191c Serve the correct status code for not found and redirects 👌 (#2582) 2024-11-26 18:05:47 +01:00
Zeno Kapitein aa2ed0fda1 Restyle hint block (#2579) 2024-11-26 12:41:47 +01:00
Greg Bergé 51cba074d7 Update shiki (#2583) 2024-11-26 11:50:08 +01:00
Taran Vohra 2c945c663c Get the best possible target space for content refs (#2580) 2024-11-26 10:53:37 +05:30
Viktor Renkema d9a18ecabb Improve contrast ratio for text color on image captions (#2584) 2024-11-25 14:01:09 +01:00
Greg Bergé eab7931afb Parallelize and remove useless Promise.all (#2581) 2024-11-22 15:54:56 +01:00
Taran Vohra 99b6c92377 Resolve site level redirects (#2577) 2024-11-22 12:04:15 +05:30
Zeno Kapitein 4d56f1163b Improve styling of search & ask AI box (#2576) 2024-11-20 16:59:15 +01:00
Brett Jephson 07cf835551 Add a scroll margin to the top when layout has sections (#2574) 2024-11-19 16:34:27 +00:00
Steven H 061c0c1a90 Fix a regression in variant drop-down caused by missing z-index. (#2575) 2024-11-19 17:23:44 +01:00
Anthony Lio 1ed18c05ef Adds missing css variables (#2558)
Co-authored-by: Steven H <steven@gitbook.io>
2024-11-19 16:08:07 +01:00
Steven H ca134c8a60 Fix an issue where the active site section indicator appeared above any dropdowns. (#2568) 2024-11-19 15:16:47 +01:00
Amrit Kahlon 7ba67fd852 chore: scalar bump (#2571)
Co-authored-by: Steven Hall <steven@gitbook.io>
2024-11-19 13:54:35 +01:00
Taran Vohra 7675c2c411 use getPublishedContentSite API (#2570)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-11-15 09:21:08 +01:00
Brett Jephson 7c71363af8 Set adjustFallbackFont to false for mono font (#2569) 2024-11-12 13:03:25 +00:00
Steven H d48926eb2a Fix an issue where the space dropdown was shown under the site sections in Safari. (#2567) 2024-11-05 11:49:33 +00:00
Steven H d843e5e06f Fix an issue where the space dropdown could appear behind the header. (#2566) 2024-11-05 09:47:32 +00:00
Steven H a2e564738e Fix the styling of site section tabs on smaller screens. (#2565) 2024-11-04 17:36:10 +00:00
Greg Bergé 54a797a0b1 Nested list support (#2562) 2024-10-31 14:02:42 +01:00
Amrit Kahlon a78c1ecb4d Bump scalar api client package (#2563) 2024-10-30 11:45:56 -07:00
Amrit Kahlon 4771c78001 Fix Scalar ApiClient routing (#2561) 2024-10-28 12:38:18 -07:00
Samy Pessé b7a5106f36 Disable logs for cache-do (#2560) 2024-10-27 08:16:56 -04:00
Samy Pessé 4bcbdc50ff Output caching headers on RSC/prefetch responses (#2559) 2024-10-26 10:57:52 +02:00
Brett Jephson 5d72b35c7f Improve animation of section tabs (#2553) 2024-10-25 14:00:27 +01:00
Amrit Kahlon ff50ac215c Bump @scalar/api-client-react version (#2555)
Co-authored-by: taranvohra <taranvohra@outlook.com>
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-10-25 12:06:49 +05:30
123 changed files with 3498 additions and 2154 deletions
+1 -1
View File
@@ -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'
+7 -17
View File
@@ -18,7 +18,7 @@ jobs:
checks: write checks: write
statuses: write statuses: write
outputs: outputs:
deployment_url: ${{ steps.deploy.outputs.url }} deployment_url: ${{ steps.deploy.outputs.deployment-url }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -30,16 +30,6 @@ jobs:
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
@@ -58,7 +48,7 @@ jobs:
SENTRY_DSN: ${{ vars.SENTRY_DSN }} SENTRY_DSN: ${{ vars.SENTRY_DSN }}
- id: deploy - id: deploy
name: Deploy to Cloudflare name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3 uses: cloudflare/wrangler-action@v3.11.0
with: with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
@@ -67,7 +57,7 @@ jobs:
command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }} command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
- name: Outputs - name: Outputs
run: | run: |
echo "URL: ${{ steps.deploy.outputs.url }}" echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}" echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}"
- name: Archive build output - name: Archive build output
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
@@ -77,12 +67,12 @@ jobs:
# Until https://github.com/cloudflare/wrangler-action/issues/301 is done # Until https://github.com/cloudflare/wrangler-action/issues/301 is done
- name: Update Deployment Status to Success - name: Update Deployment Status to Success
env: env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }} DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
run: | run: |
curl -X POST \ curl -X POST \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github.v3+json" \ -H "Accept: application/vnd.github.v3+json" \
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \ -d '{"state": "success", "target_url": "${{ steps.deploy.outputs.deployment-url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.sha }} https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.sha }}
- name: Find GitHub Comment - name: Find GitHub Comment
@@ -102,8 +92,8 @@ jobs:
issue-number: ${{ github.event.pull_request.number }} issue-number: ${{ github.event.pull_request.number }}
body: | body: |
**GitBook Preview** **GitBook Preview**
Latest commit: [${{ steps.deploy.outputs.url }}](${{ steps.deploy.outputs.url }}) Latest commit: [${{ steps.deploy.outputs.deployment-url }}](${{ steps.deploy.outputs.deployment-url }})
PR: [${{ steps.deploy.outputs.alias }}](${{ steps.deploy.outputs.alias }}) PR: [${{ steps.deploy.outputs.deployment-alias-url }}](${{ steps.deploy.outputs.deployment-alias-url }})
edit-mode: replace edit-mode: replace
visual-testing: visual-testing:
runs-on: ubuntu-latest runs-on: ubuntu-latest
BIN
View File
Binary file not shown.
+2 -1
View File
@@ -8,7 +8,8 @@
}, },
"packageManager": "bun@1.1.18", "packageManager": "bun@1.1.18",
"patchedDependencies": { "patchedDependencies": {
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.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, "private": true,
"scripts": { "scripts": {
+6
View File
@@ -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
+1 -1
View File
@@ -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"
+2 -3
View File
@@ -11,8 +11,7 @@ migrations = [
] ]
[observability] [observability]
enabled = true enabled = false
head_sampling_rate = 0.01
[env.preview] [env.preview]
name = "gitbook-open-cache-preview" name = "gitbook-open-cache-preview"
@@ -25,4 +24,4 @@ migrations = [
[env.preview.observability] [env.preview.observability]
enabled = true enabled = true
head_sampling_rate = 1 head_sampling_rate = 0.1
+40
View File
@@ -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
+413 -17
View File
@@ -1,11 +1,16 @@
import { argosScreenshot } from '@argos-ci/playwright'; import { argosScreenshot } from '@argos-ci/playwright';
import { import {
CustomizationBackground,
CustomizationCorners,
CustomizationFont,
CustomizationHeaderPreset, CustomizationHeaderPreset,
CustomizationIconsStyle, CustomizationIconsStyle,
CustomizationLocale, CustomizationLocale,
CustomizationThemeMode,
SiteCustomizationSettings, SiteCustomizationSettings,
} from '@gitbook/api'; } from '@gitbook/api';
import { test, expect, Page } from '@playwright/test'; import { test, expect, Page } 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';
@@ -34,6 +39,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 +112,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 +130,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 +164,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 +187,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 +222,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 +456,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 +504,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',
@@ -491,6 +611,55 @@ const testCases: TestsCase[] = [
}, },
], ],
}, },
{
name: 'Shared space navigation (first site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
tests: [
{
name: 'Navigation to shared space',
url: '',
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
const url = page.url();
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
},
],
},
{
name: 'Shared space navigation (second site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
tests: [
{
name: 'Navigation to shared space',
url: '',
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
const url = page.url();
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
},
],
},
{
name: 'Site Redirects',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [
{
name: 'Redirect to SSO page',
url: 'a/redirect/to/sso',
run: async (page) => {
await expect(page.locator('h1')).toHaveText('SSO');
},
},
],
},
{ {
name: 'Share links', name: 'Share links',
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/', baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
@@ -765,6 +934,178 @@ 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: '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) {
@@ -799,7 +1140,62 @@ 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,
},
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);
+13 -12
View File
@@ -1,11 +1,11 @@
{ {
"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",
"build": "next build", "build": "next build",
"build:cloudflare": "next-on-pages", "build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
@@ -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.73.0", "@gitbook/api": "^0.81.0",
"@gitbook/cache-do": "workspace:*", "@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*", "@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*", "@gitbook/icons": "workspace:*",
@@ -49,8 +49,8 @@
"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",
@@ -60,7 +60,7 @@
"remark-rehype": "^11.1.0", "remark-rehype": "^11.1.0",
"rison": "^0.1.1", "rison": "^0.1.1",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"shiki": "^1.22.0", "shiki": "^1.23.1",
"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",
@@ -68,9 +68,9 @@
}, },
"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 +78,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 +91,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"
} }
} }
@@ -4,6 +4,7 @@ import {
verifyImageSignature, verifyImageSignature,
resizeImage, resizeImage,
CloudflareImageOptions, CloudflareImageOptions,
imagesResizingSignVersion,
checkIsSizableImageURL, checkIsSizableImageURL,
} from '@/lib/images'; } from '@/lib/images';
import { parseImageAPIURL } from '@/lib/urls'; import { parseImageAPIURL } from '@/lib/urls';
@@ -18,28 +19,29 @@ export const runtime = 'edge';
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
let urlParam = request.nextUrl.searchParams.get('url'); let urlParam = request.nextUrl.searchParams.get('url');
const signature = request.nextUrl.searchParams.get('sign'); const signature = request.nextUrl.searchParams.get('sign');
// The current signature algorithm sets version as 1, but we need to support the older version as well
// for previously generated content. In this case, we default to version 0. // The current signature algorithm sets version as 2, but we need to support the older version as well
const signatureVersion = (request.nextUrl.searchParams.get('sv') as '1') || '0'; const signatureVersion = request.nextUrl.searchParams.get('sv') as string | undefined;
if (!urlParam || !signature) { if (!urlParam || !signature) {
return new Response('Missing url/sign parameters', { status: 400 }); return new Response('Missing url/sign parameters', { status: 400 });
} }
const url = parseImageAPIURL(urlParam); const url = parseImageAPIURL(urlParam);
// Prevent infinite loops
if (url.includes('/~gitbook/image')) {
return new Response('Invalid url parameter', { status: 400 });
}
// Check again if the image can be sized, even though we checked when rendering the Image component // Check again if the image can be sized, even though we checked when rendering the Image component
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain // Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
// Also prevent infinite redirects.
if (!checkIsSizableImageURL(url)) { if (!checkIsSizableImageURL(url)) {
return new Response('Invalid url parameter', { status: 400 }); return new Response('Invalid url parameter', { status: 400 });
} }
// For older signatures, we redirect to the url.
if (signatureVersion !== imagesResizingSignVersion) {
return Response.redirect(url, 302);
}
// Verify the signature // Verify the signature
const verified = await verifyImageSignature(url, { signature, version: signatureVersion }); const verified = await verifyImageSignature(url, { signature });
if (!verified) { if (!verified) {
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 }); return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
} }
@@ -8,10 +8,10 @@ import { useScrollPage } from '@/components/hooks';
/** /**
* Client component to initialize interactivity for a page. * Client component to initialize interactivity for a page.
*/ */
export function PageClientLayout(props: {}) { export function PageClientLayout(props: { withSections?: boolean }) {
// We use this hook in the page layout to ensure the elements for the blocks // We use this hook in the page layout to ensure the elements for the blocks
// are rendered before we scroll to a hash or to the top of the page // are rendered before we scroll to a hash or to the top of the page
useScrollPage(); useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
useStripFallbackQueryParam(); useStripFallbackQueryParam();
return null; return null;
@@ -1,11 +1,11 @@
import { getSpaceLanguage, t } from '@/intl/server'; import { getSpaceLanguage, t } from '@/intl/server';
import { getSiteLayoutData } from '@/lib/api'; import { getSiteData } 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 getSiteLayoutData(pointer); const { customization } = await getSiteData(pointer);
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
@@ -35,6 +35,7 @@ export default async function Page(props: {
customization, customization,
pages, pages,
page, page,
ancestors,
document, document,
} = await getPageDataWithFallback({ } = await getPageDataWithFallback({
pagePathParams: params, pagePathParams: params,
@@ -73,7 +74,7 @@ export default async function Page(props: {
page, page,
}; };
const withSections = Boolean(sections && sections.length > 0); const withSections = Boolean(sections && sections.list.length > 0);
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader }; const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
return ( return (
@@ -103,6 +104,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
@@ -111,7 +113,7 @@ export default async function Page(props: {
/> />
</div> </div>
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<PageClientLayout /> <PageClientLayout withSections={withSections} />
</React.Suspense> </React.Suspense>
</> </>
); );
@@ -150,7 +152,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: [
@@ -42,7 +42,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);
} }
@@ -1,7 +1,6 @@
import { ContentVisibility } from '@gitbook/api';
import { NextRequest } from 'next/server'; import { NextRequest } from 'next/server';
import { getCollection, getSite, getSpace } from '@/lib/api'; import { getSpace, getSite } from '@/lib/api';
import { absoluteHref } from '@/lib/links'; import { absoluteHref } from '@/lib/links';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { isSpaceIndexable } from '@/lib/seo'; import { isSpaceIndexable } from '@/lib/seo';
@@ -3,7 +3,7 @@ import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server'; import { NextRequest } from 'next/server';
import React from 'react'; import React from 'react';
import { getCurrentSiteCustomization, getSite, getSpace } from '@/lib/api'; import { getSite, getSiteData, getSpace } from '@/lib/api';
import { getEmojiForCode } from '@/lib/emojis'; import { getEmojiForCode } from '@/lib/emojis';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -38,9 +38,9 @@ export async function GET(req: NextRequest) {
const pointer = getSiteContentPointer(); const pointer = getSiteContentPointer();
const spaceId = pointer.spaceId; const spaceId = pointer.spaceId;
const [space, customization] = await Promise.all([ const [space, { customization }] = await Promise.all([
getSpace(spaceId, pointer.siteShareKey), getSpace(spaceId, pointer.siteShareKey),
getCurrentSiteCustomization(pointer), getSiteData(pointer),
]); ]);
const site = await getSite(pointer.organizationId, pointer.siteId); const site = await getSite(pointer.organizationId, pointer.siteId);
const contentTitle = getContentTitle(space, customization, site); const contentTitle = getContentTitle(space, customization, site);
+48 -122
View File
@@ -1,14 +1,12 @@
import { RevisionPage, SiteSection, SiteSpace, Space } from '@gitbook/api'; import { RevisionPage } from '@gitbook/api';
import { assert } from 'ts-essentials'; import { redirect } from 'next/navigation';
import { import {
getRevisionPageByPath, getRevisionPageByPath,
getDocument, getDocument,
ContentTarget, getSpaceContentData,
getSiteData, getSiteData,
getSite, getSiteRedirectBySource,
getCurrentSiteCustomization,
getSiteStructure,
} from '@/lib/api'; } from '@/lib/api';
import { resolvePagePath, resolvePageId } from '@/lib/pages'; import { resolvePagePath, resolvePageId } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
@@ -21,35 +19,18 @@ export interface PageIdParams {
pageId: string; pageId: string;
} }
type SectionsList = { list: SiteSection[]; section: SiteSection };
/** /**
* Fetch all the data needed to render the content layout. * Fetch all the data needed to render the content layout.
*/ */
export async function fetchContentData() { export async function fetchContentData() {
const content = getSiteContentPointer(); const content = getSiteContentPointer();
const [{ space, contentTarget, pages, customization, scripts }, siteStructure] = const [{ space, contentTarget, pages }, { customization, site, sections, spaces, scripts }] =
await Promise.all([ await Promise.all([
getSpaceContentData(content, content.siteShareKey),
getSiteData(content), getSiteData(content),
fetchSiteStructure({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
}),
]); ]);
const site = siteStructure.site;
const siteSections =
content.siteSectionId && siteStructure.sections
? parseSiteSectionsList(content.siteSectionId, siteStructure.sections)
: null;
const spaces =
siteStructure.spaces ??
(siteSections ? parseSpacesFromSiteSpaces(siteSections.section.siteSpaces) : []);
// we grab the space attached to the parent as it contains overriden customizations // we grab the space attached to the parent as it contains overriden customizations
const spaceRelativeToParent = spaces?.find((space) => space.id === content.spaceId); const spaceRelativeToParent = spaces?.find((space) => space.id === content.spaceId);
@@ -58,53 +39,39 @@ export async function fetchContentData() {
contentTarget, contentTarget,
space: spaceRelativeToParent ?? space, space: spaceRelativeToParent ?? space,
pages, pages,
sections: siteSections,
site, site,
sections,
spaces, spaces,
shareKey: content.siteShareKey,
customization, customization,
scripts, scripts,
ancestors: [], ancestors: [],
}; };
} }
function parseSiteSectionsList(siteSectionId: string, sections: SiteSection[]) {
const section = sections.find((section) => section.id === siteSectionId);
assert(sectionIsDefined(section), 'A section must be defined when there are multiple sections');
return { list: sections, section } satisfies SectionsList;
}
function sectionIsDefined(section?: SiteSection): section is NonNullable<SiteSection> {
return typeof section !== 'undefined' && section !== null;
}
/** /**
* Fetch all the data needed to render the content. * Fetch all the data needed to render the content.
* Optimized to fetch in parallel as much as possible. * Optimized to fetch in parallel as much as possible.
*/ */
export async function fetchPageData(params: PagePathParams | PageIdParams) { export async function fetchPageData(params: PagePathParams | PageIdParams) {
const content = getSiteContentPointer(); const contentData = await fetchContentData();
const { space, contentTarget, pages, customization, scripts } = await getSiteData(content); const page = await resolvePage({
const page = await resolvePage(contentTarget, pages, params); organizationId: contentData.space.organization,
const [siteStructure, document] = await Promise.all([ siteId: contentData.site.id,
fetchSiteStructure({ spaceId: contentData.contentTarget.spaceId,
organizationId: content.organizationId, revisionId: contentData.contentTarget.revisionId,
siteId: content.siteId, pages: contentData.pages,
siteShareKey: content.siteShareKey, shareKey: contentData.shareKey,
}), params,
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null, });
]); const document = page?.page.documentId
? await getDocument(contentData.space.id, page.page.documentId)
: null;
return { return {
content, ...contentData,
contentTarget,
space,
pages,
customization,
scripts,
ancestors: [],
...page, ...page,
...siteStructure,
document, document,
}; };
} }
@@ -113,11 +80,17 @@ export async function fetchPageData(params: PagePathParams | PageIdParams) {
* Resolve a page from the params. * Resolve a page from the params.
* If the path can't be found, we try to resolve it from the API to handle redirects. * If the path can't be found, we try to resolve it from the API to handle redirects.
*/ */
async function resolvePage( async function resolvePage(input: {
contentTarget: ContentTarget, organizationId: string;
pages: RevisionPage[], siteId: string;
params: PagePathParams | PageIdParams, spaceId: string;
) { revisionId: string;
shareKey: string | undefined;
pages: RevisionPage[];
params: PagePathParams | PageIdParams;
}) {
const { organizationId, siteId, spaceId, revisionId, pages, shareKey, params } = input;
if ('pageId' in params) { if ('pageId' in params) {
return resolvePageId(pages, params.pageId); return resolvePageId(pages, params.pageId);
} }
@@ -131,78 +104,31 @@ async function resolvePage(
return page; return page;
} }
// If page can't be found, we try with the API, in case we have a redirect
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
// The page rendering will take care of redirecting to a normalized pathname.
//
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway. // We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
if (rawPathname.length <= 512) { if (rawPathname.length <= 512) {
const resolved = await getRevisionPageByPath( // If page can't be found, we try with the API, in case we have a redirect at space level.
contentTarget.spaceId, // We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
contentTarget.revisionId, // The page rendering will take care of redirecting to a normalized pathname.
rawPathname, const resolved = await getRevisionPageByPath(spaceId, revisionId, rawPathname);
);
if (resolved) { if (resolved) {
return resolvePageId(pages, resolved.id); return resolvePageId(pages, resolved.id);
} }
// If a page still can't be found, we try with the API, in case we have a redirect at site level.
const resolvedSiteRedirect = await getSiteRedirectBySource({
organizationId,
siteId,
source: rawPathname.startsWith('/') ? rawPathname : `/${rawPathname}`,
siteShareKey: input.shareKey,
});
if (resolvedSiteRedirect) {
return redirect(resolvedSiteRedirect.target);
}
} }
return undefined; return undefined;
} }
/**
* Fetch the structure of an organization site.
* This includes the site and its sections or spaces.
*/
async function fetchSiteStructure(args: {
organizationId: string;
siteId: string;
siteShareKey: string | undefined;
}) {
const { organizationId, siteId, siteShareKey } = args;
const [orgSite, siteStructure, siteParentCustomizations] = await Promise.all([
getSite(organizationId, siteId),
getSiteStructure({ organizationId, siteId, siteShareKey }),
getCurrentSiteCustomization({ organizationId, siteId, siteSpaceId: undefined }),
]);
const siteSections =
siteStructure.type === 'sections' && siteStructure.structure
? siteStructure.structure
: null;
const siteSpaces =
siteStructure.type === 'siteSpaces' && siteStructure.structure
? parseSpacesFromSiteSpaces(siteStructure.structure)
: null;
// override the title with the customization title
const site = {
...orgSite,
...(siteParentCustomizations?.title ? { title: siteParentCustomizations.title } : {}),
};
return {
site,
spaces: siteSpaces,
sections: siteSections,
};
}
function parseSpacesFromSiteSpaces(siteSpaces: SiteSpace[]) {
const spaces: Record<string, Space> = {};
siteSpaces.forEach((siteSpace) => {
spaces[siteSpace.space.id] = {
...siteSpace.space,
title: siteSpace.title ?? siteSpace.space.title,
urls: {
...siteSpace.space.urls,
published: siteSpace.urls.published,
},
};
});
return Object.values(spaces);
}
/** /**
* Get the page path from the params. * Get the page path from the params.
*/ */
+2 -2
View File
@@ -1,5 +1,5 @@
import { CustomizationRootLayout } from '@/components/RootLayout'; import { CustomizationRootLayout } from '@/components/RootLayout';
import { getSiteLayoutData } from '@/lib/api'; import { getSiteData } from '@/lib/api';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
/** /**
@@ -10,7 +10,7 @@ export default async function SiteRootLayout(props: { children: React.ReactNode
const { children } = props; const { children } = props;
const pointer = getSiteContentPointer(); const pointer = getSiteContentPointer();
const { customization } = await getSiteLayoutData(pointer); const { customization } = await getSiteData(pointer);
return ( return (
<CustomizationRootLayout customization={customization}>{children}</CustomizationRootLayout> <CustomizationRootLayout customization={customization}>{children}</CustomizationRootLayout>
@@ -1,7 +1,7 @@
import { SpaceIntegrationScript } from '@gitbook/api'; import { SpaceIntegrationScript } from '@gitbook/api';
import { CustomizationRootLayout } from '@/components/RootLayout'; import { CustomizationRootLayout } from '@/components/RootLayout';
import { getSiteLayoutData, getSpaceCustomization } from '@/lib/api'; import { getSiteData, getSpaceCustomization } from '@/lib/api';
import { getSiteOrSpacePointerForPDF } from './pointer'; import { getSiteOrSpacePointerForPDF } from './pointer';
@@ -14,7 +14,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
const pointer = getSiteOrSpacePointerForPDF(); const pointer = getSiteOrSpacePointerForPDF();
const { customization } = await ('siteId' in pointer const { customization } = await ('siteId' in pointer
? getSiteLayoutData(pointer) ? getSiteData(pointer)
: getSpaceLayoutData(pointer.spaceId)); : getSpaceLayoutData(pointer.spaceId));
return ( return (
@@ -26,7 +26,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
* Fetch all the layout data about a space at once. * Fetch all the layout data about a space at once.
*/ */
async function getSpaceLayoutData(spaceId: string) { async function getSpaceLayoutData(spaceId: string) {
const [customization, scripts] = await Promise.all([ const [{ customization }, scripts] = await Promise.all([
getSpaceCustomization(spaceId), getSpaceCustomization(spaceId),
[] as SpaceIntegrationScript[], [] as SpaceIntegrationScript[],
]); ]);
@@ -11,7 +11,7 @@ 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, createHighlightingContext } 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';
@@ -21,7 +21,7 @@ import {
getSpace, getSpace,
getSpaceCustomization, getSpaceCustomization,
getSpaceContentData, getSpaceContentData,
getCurrentSiteCustomization, 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';
@@ -40,11 +40,9 @@ export const runtime = 'edge';
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata(): Promise<Metadata> {
const pointer = getSiteOrSpacePointerForPDF(); const pointer = getSiteOrSpacePointerForPDF();
const [space, customization] = await Promise.all([ const [space, { customization }] = await Promise.all([
getSpace(pointer.spaceId, 'siteId' in pointer ? pointer.siteShareKey : undefined), getSpace(pointer.spaceId, 'siteId' in pointer ? pointer.siteShareKey : undefined),
'siteId' in pointer 'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
]); ]);
return { return {
@@ -67,10 +65,8 @@ export default async function PDFHTMLOutput(props: { searchParams: { [key: strin
currentPDFUrl += '?' + searchParams.toString(); currentPDFUrl += '?' + searchParams.toString();
// Load the content, // Load the content,
const [customization, { space, contentTarget, pages: rootPages }] = await Promise.all([ const [{ customization }, { space, contentTarget, pages: rootPages }] = await Promise.all([
'siteId' in pointer 'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
getSpaceContentData(pointer, 'siteId' in pointer ? pointer.siteShareKey : undefined), getSpaceContentData(pointer, 'siteId' in pointer ? pointer.siteShareKey : undefined),
]); ]);
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
@@ -231,7 +227,6 @@ async function PDFPageDocument(props: {
const { space, page, refContext } = props; const { space, page, refContext } = props;
const document = page.documentId ? await getDocument(space.id, page.documentId) : null; const document = page.documentId ? await getDocument(space.id, page.documentId) : null;
const shouldHighlightCode = createHighlightingContext();
return ( return (
<PrintPage id={pagePDFContainerId(page)}> <PrintPage id={pagePDFContainerId(page)}>
@@ -254,7 +249,6 @@ async function PDFPageDocument(props: {
contentRefContext: refContext, contentRefContext: refContext,
resolveContentRef: (ref) => resolveContentRef(ref, refContext), resolveContentRef: (ref) => resolveContentRef(ref, refContext),
getId: (id) => pagePDFContainerId(page, id), getId: (id) => pagePDFContainerId(page, id),
shouldHighlightCode,
}} }}
/> />
) : null} ) : null}
@@ -0,0 +1,18 @@
// @ts-ignore
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
import { withMiddlewareHeadersStorage } from './lib/middleware';
/**
* We use a custom entrypoint until we can move to opennext (https://github.com/opennextjs/opennextjs-cloudflare/issues/92).
* There is a bug in next-on-pages where headers can't be set on the response in the middleware for RSC requests (https://github.com/cloudflare/next-on-pages/issues/897).
*/
export default {
async fetch(request, env, ctx) {
const response = await withMiddlewareHeadersStorage(() =>
nextOnPagesHandler.fetch(request, env, ctx),
);
return response;
},
} as ExportedHandler<{ ASSETS: Fetcher }>;
@@ -22,10 +22,8 @@ import { Heading } from './Heading';
import { Hint } from './Hint'; import { Hint } from './Hint';
import { Images } from './Images'; import { Images } from './Images';
import { IntegrationBlock } from './Integration'; import { IntegrationBlock } from './Integration';
import { List } from './List';
import { ListItem } from './ListItem'; import { ListItem } from './ListItem';
import { ListOrdered } from './ListOrdered';
import { ListTasks } from './ListTasks';
import { ListUnordered } from './ListUnordered';
import { BlockMath } from './Math'; import { BlockMath } from './Math';
import { OpenAPI } from './OpenAPI'; import { OpenAPI } from './OpenAPI';
import { Paragraph } from './Paragraph'; import { Paragraph } from './Paragraph';
@@ -65,11 +63,9 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
case 'heading-3': case 'heading-3':
return <Heading {...props} block={block} />; return <Heading {...props} block={block} />;
case 'list-ordered': case 'list-ordered':
return <ListOrdered {...props} block={block} />;
case 'list-unordered': case 'list-unordered':
return <ListUnordered {...props} block={block} />;
case 'list-tasks': case 'list-tasks':
return <ListTasks {...props} block={block} />; return <List {...props} block={block} />;
case 'list-item': case 'list-item':
return <ListItem {...props} block={block} />; return <ListItem {...props} block={block} />;
case 'code': case 'code':
@@ -48,7 +48,7 @@ async function SpaceRefCard(
return null; return null;
} }
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId)); const { customization: spaceCustomization } = getSpaceCustomization(spaceId);
const customFavicon = spaceCustomization?.favicon; const customFavicon = spaceCustomization?.favicon;
const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined; const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined;
const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined; const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined;
@@ -71,7 +71,7 @@ export function Caption(
'text-center', 'text-center',
'mt-2', 'mt-2',
'text-dark/7', 'text-dark/7',
'dark:text-light/6', 'dark:text-light/7',
)} )}
> >
<Inlines <Inlines
@@ -15,8 +15,7 @@ import './theme.css';
*/ */
export async function CodeBlock(props: BlockProps<DocumentBlockCode>) { export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
const { block, document, style, context } = props; const { block, document, style, context } = props;
const withHighlighting = context.shouldHighlightCode(context.content?.spaceId); const lines = await highlight(block);
const lines = withHighlighting ? await highlight(block) : plainHighlighting(block);
const id = block.key!; const id = block.key!;
@@ -99,6 +98,8 @@ export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
'overflow-auto', 'overflow-auto',
'bg-light-2', 'bg-light-2',
'dark:bg-dark-2', 'dark:bg-dark-2',
'border-light-4',
'dark:border-dark-4',
'hide-scroll', 'hide-scroll',
titleRoundingStyle, titleRoundingStyle,
)} )}
@@ -50,7 +50,6 @@ export function PlainCodeBlock(props: { code: string; syntax: string }) {
mode: 'default', mode: 'default',
contentRefContext: null, contentRefContext: null,
resolveContentRef: async () => null, resolveContentRef: async () => null,
shouldHighlightCode: () => true,
}} }}
block={block} block={block}
ancestorBlocks={[]} ancestorBlocks={[]}
@@ -1,30 +0,0 @@
const CODE_HIGHLIGHT_BLOCK_LIMIT = 50;
/**
* Spaces where we'll always use plain highlighting.
*/
const PLAIN_HIGHLIGHTING_SPACES: string[] = [
'V9geAO9ITPi8WOYK5o0r',
'puRmcwVxGFtHph8IjXaf',
'e3jwbMOrr4RhKtZ9C0XL',
'ryjzVNizLfd6pYogN3dm',
];
/**
* Protect against memory issues when highlighting a large number of code blocks.
* This context only allows 50 code blocks per render to be highlighted.
* Once highlighting can scale up to a large number of code blocks, it can be removed.
*
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
*/
export function createHighlightingContext() {
let count = 0;
return (spaceId?: string | undefined) => {
if (!spaceId || PLAIN_HIGHLIGHTING_SPACES.includes(spaceId)) {
return false;
}
count += 1;
return count < CODE_HIGHLIGHT_BLOCK_LIMIT;
};
}
@@ -50,7 +50,7 @@ export async function highlight(block: DocumentBlockCode): Promise<HighlightLine
const lines = highlighter.codeToTokensBase(code, { const lines = highlighter.codeToTokensBase(code, {
lang: langName, lang: langName,
tokenizeMaxLineLength: 120, tokenizeMaxLineLength: 400,
}); });
let currentIndex = 0; let currentIndex = 0;
@@ -1,3 +1,2 @@
export * from './CodeBlock'; export * from './CodeBlock';
export * from './PlainCodeBlock'; export * from './PlainCodeBlock';
export * from './createHighlightingContext';
@@ -38,16 +38,6 @@ export interface DocumentContext {
*/ */
getId?: (id: string) => string; getId?: (id: string) => string;
/**
* Returns true if the given code block should be highlighted.
* This function was added to protect against memory issues when highlighting
* a large number of code blocks.
* Once highlighting can scale up to a large number of code blocks, it can be removed.
*
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
*/
shouldHighlightCode: (spaceId: string | undefined) => boolean;
/** /**
* True if the blocks should be wrapped in suspense boundary for isolated loading skeletons. * True if the blocks should be wrapped in suspense boundary for isolated loading skeletons.
* @default true * @default true
@@ -16,8 +16,8 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
return ( return (
<div <div
className={tcls( className={tcls(
'px-4', 'hint',
'py-4', 'p-4',
'transition-colors', 'transition-colors',
'rounded-md', 'rounded-md',
'straight-corners:rounded-none', 'straight-corners:rounded-none',
@@ -26,19 +26,16 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
)} )}
> >
<div className={tcls('flex', 'flex-row')}> <div className={tcls('flex', 'flex-row')}>
<div <Icon
icon={hintStyle.icon}
className={tcls( className={tcls(
'flex', 'size-5',
'items-start', 'mr-4',
'justify-center',
'pr-3',
'mt-0.5', 'mt-0.5',
firstLine.lineHeight, firstLine.lineHeight,
hintStyle.iconColor, hintStyle.iconColor,
)} )}
> />
<Icon icon={hintStyle.icon} className={tcls('size-4')} />
</div>
<Blocks <Blocks
{...contextProps} {...contextProps}
ancestorBlocks={[...ancestorBlocks, block]} ancestorBlocks={[...ancestorBlocks, block]}
@@ -48,7 +45,7 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
// render hash icon on the other side of the heading // render hash icon on the other side of the heading
'flip-heading-hash', 'flip-heading-hash',
)} )}
style={['flex-1', 'space-y-4', '[&>p]:text-sm', '[&>p]:leading-relaxed']} style={['flex-1', 'space-y-4', '[&_.hint]:border', '[&_pre]:border']}
/> />
</div> </div>
</div> </div>
@@ -65,130 +62,69 @@ const HINT_STYLES: {
} = { } = {
info: { info: {
icon: 'circle-info', icon: 'circle-info',
iconColor: ['text-periwinkle-700', 'dark:text-periwinkle-400'], iconColor: ['text-primary-500', 'dark:text-primary-400'],
bodyColor: [ bodyColor: [
'[&>a]:text-periwinkle-700', '[&_a]:text-primary-500',
'[&>a:hover]:text-periwinkle-800', '[&_a:hover]:text-primary-600',
'[&>code]:bg-periwinkle-700/4', 'dark:[&_a]:text-primary-400',
'[&>code]:text-inherit', 'dark:[&_a:hover]:text-primary-300',
'[&>code]:shadow-none',
'text-periwinkle-900',
'dark:text-periwinkle-200',
'dark:[&>a]:text-periwinkle',
'dark:[&>a:hover]:text-periwinkle-600',
'dark:[&>code]:bg-periwinkle-200/2',
'dark:[&>code]:text-inherit',
'decoration-periwinkle-700/6',
'dark:decoration-periwinkle/6',
], ],
style: [ style: [
'bg-gradient-to-b', 'bg-dark-1/1',
'from-periwinkle/6', 'border-dark/3',
'to-periwinkle/5', 'dark:bg-light/1',
'ring-1', 'dark:border-light/3',
'ring-inset', '[&_.can-override-bg]:bg-dark-1/2',
'ring-dark/1', '[&_.can-override-text]:text-dark',
'dark:ring-periwinkle/1', 'dark:[&_.can-override-bg]:bg-light/2',
'dark:from-periwinkle/2', 'dark:[&_.can-override-text]:text-light',
'dark:to-periwinkle/[0.1]',
], ],
}, },
warning: { warning: {
icon: 'circle-exclamation', icon: 'circle-exclamation',
iconColor: ['text-yellow-800', 'dark:text-yellow'], iconColor: ['text-amber-500', 'dark:text-orange-400'], // Darker shades of orange-* mismatch with lighter shades, so in light mode we use amber text on top of orange bg.
bodyColor: [ bodyColor: [
'[&>a]:text-yellow-700', '[&_a]:text-orange-800',
'[&>a:hover]:text-yellow-800', '[&_a:hover]:text-orange-900',
'[&>code]:bg-yellow-600/5', 'dark:[&_a]:text-orange-400',
'[&>code]:text-inherit', 'dark:[&_a:hover]:text-orange-300',
'[&>code]:shadow-none', '[&_.can-override-bg]:bg-orange-500/3',
'[&_.can-override-text]:text-orange-800',
'text-yellow-900', 'dark:[&_.can-override-text]:text-orange-400',
'decoration-orange-800/6',
'dark:text-yellow-200', 'dark:decoration-orange-400/6',
'dark:[&>a]:text-yellow',
'dark:[&>a:hover]:text-yellow-600',
'dark:[&>code]:bg-yellow-200/2',
'dark:[&>code]:text-inherit',
'decoration-yellow-700/6',
'dark:decoration-yellow/6',
],
style: [
'bg-gradient-to-b',
'from-yellow/6',
'to-yellow/5',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-yellow/[0.02]',
'dark:from-yellow/[0.06]',
'dark:to-yellow/2',
], ],
style: ['bg-orange-500/2', 'border-orange-500/4'],
}, },
danger: { danger: {
icon: 'triangle-exclamation', icon: 'triangle-exclamation',
iconColor: ['text-pomegranate-700', 'dark:text-pomegranate-400'], iconColor: ['text-red-500', 'dark:text-red-400'],
bodyColor: [ bodyColor: [
'[&>a]:text-pomegranate-600/9', '[&_a]:text-red-800',
'[&>a:hover]:text-pomegranate-800', '[&_a:hover]:text-red-900',
'[&>code]:bg-pomegranate-600/4', 'dark:[&_a]:text-red-400',
'[&>code]:text-inherit', 'dark:[&_a:hover]:text-red-300',
'[&>code]:shadow-none', '[&_.can-override-bg]:bg-red-500/3',
'[&_.can-override-text]:text-red-400',
'text-pomegranate-900', 'decoration-red-800/6',
'dark:decoration-red-400/6',
'dark:text-pomegranate-100',
'dark:[&>a]:text-pomegranate',
'dark:[&>a:hover]:text-pomegranate-600',
'dark:[&>code]:bg-pomegranate-200/2',
'dark:[&>code]:text-inherit',
'decoration-pomegranate-600/6',
'dark:decoration-pomegranate/6',
],
style: [
'bg-gradient-to-b',
'from-pomegranate/4',
'to-pomegranate/3',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-pomegranate/1',
'dark:from-pomegranate/2',
'dark:to-pomegranate/3',
], ],
style: ['bg-red-500/2', 'border-red-500/4'],
}, },
success: { success: {
icon: 'circle-check', icon: 'circle-check',
iconColor: ['text-teal-700', 'dark:text-teal-400'], iconColor: ['text-green-500', 'dark:text-green-400'],
bodyColor: [ bodyColor: [
'[&>a]:text-teal-600', '[&_a]:text-green-800',
'[&>a:hover]:text-teal-800', '[&_a:hover]:text-green-900',
'[&>code]:bg-teal-600/4', 'dark:[&_a]:text-green-400',
'[&>code]:text-inherit', 'dark:[&_a:hover]:text-green-300',
'[&>code]:shadow-none', '[&_.can-override-bg]:bg-green-500/3',
'[&_.can-override-text]:text-green-800',
'text-teal-800', 'dark:[&_.can-override-text]:text-green-400',
'decoration-green-800/6',
'dark:text-teal-100', 'dark:decoration-green-400/6',
'dark:[&>a]:text-teal-400',
'dark:[&>a:hover]:text-teal-500',
'dark:[&>code]:bg-teal-200/2',
'dark:[&>code]:text-inherit',
'decoration-teal/6',
'dark:decoration-teal/6',
],
style: [
'bg-gradient-to-b',
'from-teal/4',
'to-teal/3',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-teal/1',
'dark:from-teal/2',
'dark:to-teal/3',
], ],
style: ['bg-green-500/2', 'border-green-500/4'],
}, },
}; };
@@ -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)}
@@ -0,0 +1,44 @@
import {
DocumentBlockListOrdered,
DocumentBlockListTasks,
DocumentBlockListUnordered,
} from '@gitbook/api';
import assertNever from 'assert-never';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function List(
props: BlockProps<
DocumentBlockListUnordered | DocumentBlockListOrdered | DocumentBlockListTasks
>,
) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag={getListTag(block.type)}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={['space-y-2', style]}
/>
);
}
function getListTag(
type:
| DocumentBlockListUnordered['type']
| DocumentBlockListOrdered['type']
| DocumentBlockListTasks['type'],
) {
switch (type) {
case 'list-ordered':
return 'ol';
case 'list-unordered':
case 'list-tasks':
return 'ul';
default:
assertNever(type);
}
}
@@ -1,13 +0,0 @@
.olListItemBullet {
/* Align the bullet container with the first line of text */
line-height: inherit;
height: 1lh;
/* Align the bullet content with the middle of the text */
display: flex;
align-items: center;
}
.olListItemBullet::before {
@apply text-base;
--tw-content: attr(data-value) '. ';
content: var(--tw-content);
}
@@ -1,114 +1,231 @@
import { import {
DocumentBlock,
DocumentBlockListItem, DocumentBlockListItem,
DocumentBlockListOrdered, DocumentBlockListOrdered,
DocumentBlockListTasks,
DocumentBlockListUnordered, DocumentBlockListUnordered,
} from '@gitbook/api'; } from '@gitbook/api';
import classNames from 'classnames'; import assertNever from 'assert-never';
import { assert } from 'ts-essentials';
import { Checkbox } from '@/components/primitives'; import { Checkbox } from '@/components/primitives';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block'; import { BlockProps } from './Block';
import { Blocks } from './Blocks'; import { Blocks } from './Blocks';
import styles from './ListItem.module.css';
import { getBlockTextStyle } from './spacing'; import { getBlockTextStyle } from './spacing';
export function ListItem(props: BlockProps<DocumentBlockListItem>) { export function ListItem(props: BlockProps<DocumentBlockListItem>) {
const { block, ancestorBlocks, ...contextProps } = props; const { block, ancestorBlocks, ...contextProps } = props;
const textStyle = getBlockTextStyle(block); const parent = ancestorBlocks[ancestorBlocks.length - 1];
assert(
(parent && parent.type === 'list-ordered') ||
parent.type === 'list-unordered' ||
parent.type === 'list-tasks',
'Invalid parent list type',
);
const parent = ancestorBlocks[ancestorBlocks.length - 1] as const blocksElement = (
| DocumentBlockListOrdered <Blocks
| DocumentBlockListUnordered {...contextProps}
| DocumentBlockListTasks nodes={block.nodes}
| undefined; ancestorBlocks={[...ancestorBlocks, block]}
blockStyle={tcls(
'min-h-[1lh]',
// flip heading hash icon if list item is a heading
'flip-heading-hash',
// remove margin-top for the first heading in a list
'[&:is(h2)>div]:mt-0',
'[&:is(h3)>div]:mt-0',
'[&:is(h4)>div]:mt-0',
)}
style="space-y-2 flex flex-col flex-1"
/>
);
const ListItemType = () => { switch (parent.type) {
switch (parent?.type) { case 'list-tasks':
case 'list-tasks': return (
return ( <ListItemLI block={block}>
<li> <ListItemPrefix block={block}>
<div className={tcls('flex', 'flex-row')}> <Checkbox
<div id={block.key!}
className={tcls( disabled
textStyle.textSize, checked={block.data?.checked}
'flex', className="relative"
'flex-col', size="small"
'justify-center',
'h-[1lh]',
)}
>
<Checkbox
id={block.key!}
disabled
checked={block.data?.checked}
className={tcls('relative')}
/>
</div>
<label htmlFor={block.key} className={tcls('flex-1')}>
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
blockStyle={tcls('flip-heading-hash')}
style={tcls('ml-2', 'space-y-2')}
/>
</label>
</div>
</li>
);
case 'list-ordered':
const start = parent.data.start ?? 1;
const indexInParent = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
const index = indexInParent + start;
return (
<li value={index} className={tcls(textStyle.lineHeight)}>
<div
data-value={index}
className={classNames(
'bullet',
styles.olListItemBullet,
tcls(textStyle.textSize),
)}
></div>
{/* zero width space to force layouts with empty lists */}
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={tcls('space-y-2', 'flex-1', 'flex', 'flex-col')}
blockStyle={tcls(
textStyle.lineHeight,
'min-h-[1lh]',
//flip heading hash icon if list item is a heading
'flip-heading-hash',
)}
/> />
</li> </ListItemPrefix>
);
default:
return (
<li className={tcls(textStyle.lineHeight)}>
<div className={tcls('bullet', textStyle.textSize)}></div>
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={tcls('space-y-2', 'flex', 'flex-col')}
blockStyle={tcls(
'min-h-[1lh]',
//flip heading hash icon if list item is a heading
'flip-heading-hash',
)}
/>
</li>
);
}
};
return <ListItemType />; <label htmlFor={block.key} className={tcls('flex-1')}>
{blocksElement}
</label>
</ListItemLI>
);
case 'list-ordered':
return (
<ListItemLI block={block}>
<ListItemPrefix block={block}>
<PseudoBefore
content={getOrderedListItemPrefixContent({
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
block,
parent,
})}
style={{
fontSize: 'min(1em, 24px)',
}}
/>
</ListItemPrefix>
{blocksElement}
</ListItemLI>
);
case 'list-unordered':
return (
<ListItemLI block={block}>
<ListItemPrefix block={block}>
<PseudoBefore
content={getUnorderedListItemsPrefixContent({
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
})}
fontFamily="Arial"
style={{ fontSize: 'min(1.5em, 24px)', lineHeight: 1 }}
/>
</ListItemPrefix>
{blocksElement}
</ListItemLI>
);
default:
assertNever(parent);
}
}
function getListItemDepth(input: {
ancestorBlocks: DocumentBlock[];
type: DocumentBlockListOrdered['type'] | DocumentBlockListUnordered['type'];
}): number {
const { ancestorBlocks, type } = input;
let depth = -1;
for (let i = ancestorBlocks.length - 1; i >= 0; i--) {
const block = ancestorBlocks[i];
if (block.type === type) {
depth = depth + 1;
continue;
}
if (block.type === 'list-item') {
continue;
}
break;
}
return depth;
}
function ListItemLI(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
const textStyle = getBlockTextStyle(props.block);
return <li className={tcls(textStyle.lineHeight, 'flex items-start')}>{props.children}</li>;
}
function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
const textStyle = getBlockTextStyle(props.block);
return (
<div
className={tcls(
textStyle.textSize,
textStyle.lineHeight,
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark/6 dark:text-light/5',
)}
>
{props.children}
</div>
);
}
function getUnorderedListItemsPrefixContent(input: { depth: number }): string {
switch (input.depth % 3) {
case 0:
return '•';
case 1:
return '◦';
case 2:
return '▪';
default:
return '•';
}
}
function PseudoBefore(props: {
style?: React.CSSProperties;
content: string;
fontFamily?: string;
}) {
return (
<div
className="before:font-var before:content-[--pseudoBefore--content]"
style={
{
'--pseudoBefore--content': `'${props.content}'`,
'--font-family': props.fontFamily ?? 'inherit',
...props.style,
} as React.CSSProperties
}
/>
);
}
function getOrderedListItemPrefixContent(input: {
depth: number;
parent: DocumentBlockListOrdered;
block: DocumentBlockListItem;
}): string {
const { parent, block } = input;
const start = parent.data.start ?? 1;
const index = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
const value = index + start;
switch (input.depth % 3) {
// Use numbers
case 0: {
return `${value}.`;
}
// Use letters
case 1: {
const letters = 'abcdefghijklmnopqrstuvwxyz';
return `${letters[(value - 1) % letters.length]}.`;
}
// Use roman numbers
case 2: {
return `${toRoman(value).toLowerCase()}.`;
}
default:
return '•';
}
}
function toRoman(input: number): string {
const lookup = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let roman = '';
let number = input;
for (const i in lookup) {
while (number >= lookup[i as keyof typeof lookup]) {
roman += i;
number -= lookup[i as keyof typeof lookup];
}
}
return roman;
} }
@@ -1,45 +0,0 @@
import { DocumentBlockListOrdered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListOrdered(props: BlockProps<DocumentBlockListOrdered>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag="ol"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'space-y-2',
'flex',
'flex-col',
'[&>li]:gap-[1ch]',
'[counter-reset:list-decimal]',
'[&>li]:flex',
'[&>li]:flex-row',
/* '[&>li>.bullet]:w-[1ch]', */
'[&>li>.bullet]:tabular-nums',
'[&>li>.bullet]:whitespace-nowrap',
'[&>li>.bullet]:list-decimal',
'[&>li>.bullet]:before:h-[1lh]',
'[&>li>.bullet]:before:leading-[inherit]',
'[&>li>.bullet]:before:flex',
/* '[&>li>.bullet]:before:pr-[1ch]', */
'[&>li>.bullet]:text-dark/6',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
'dark:[&>li>.bullet]:text-light/6',
style,
]}
/>
);
}
@@ -1,25 +0,0 @@
import { DocumentBlockListTasks, DocumentBlockListUnordered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListTasks(props: BlockProps<DocumentBlockListTasks>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag="ul"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'list-none',
'[&>li]:pl-[.25ch]',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
'space-y-2',
style,
]}
/>
);
}
@@ -1,51 +0,0 @@
import { DocumentBlockListUnordered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListUnordered(props: BlockProps<DocumentBlockListUnordered>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
const nestedBulletStyle = [
// Level 1
'[&>li>.bullet:before]:bullet-circleFilled',
// Level 2
`[&_&>li>.bullet:before]:bullet-circle`,
// Level 3
`[&_&_&>li>.bullet:before]:bullet-dash`,
// Level 4
`[&_&_&_&>li>.bullet:before]:bullet-squareFilled`,
// Level 5
`[&_&_&_&_&>li>.bullet:before]:bullet-square`,
// Level 6 // reset back to reg bullets here
`[&_&_&_&_&_&>li>.bullet:before]:bullet-circleFilled`,
];
return (
<Blocks
{...contextProps}
tag="ul"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'list-none',
'space-y-2',
'[&>li]:relative',
'[&>li]:ps-[2.25ch]',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
//custom content setup for lists
'[&>li>.bullet]:before:bg-dark/6',
'[&>li>.bullet]:before:absolute',
'[&>li>.bullet]:before:left-0',
'[&>li>.bullet]:before:w-[1ch]',
'[&>li>.bullet]:before:h-[1lh]',
'[&>li>.bullet]:before:[mask-repeat:no-repeat]',
'[&>li>.bullet]:before:[mask-position:left]',
'dark:[&>li>.bullet]:before:bg-light/6',
nestedBulletStyle,
style,
]}
/>
);
}
@@ -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;
@@ -57,13 +57,16 @@
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11); --scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px, --scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
#eeeeed 0px 0 0 1px; #eeeeed 0px 0 0 1px;
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--dark-base, 22 22 22));
} }
.dark .scalar-modal-layout, .dark .scalar-modal-layout,
.dark .scalar-app, .dark .scalar-app,
.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(
@@ -81,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;
@@ -114,6 +117,9 @@
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1); --scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px, --scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px,
0 0 0 1px rgba(255, 255, 255, 0.1); 0 0 0 1px rgba(255, 255, 255, 0.1);
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--light-base, 255 255 255));
} }
.scalar-modal-layout, .scalar-modal-layout,
.scalar-app, .scalar-app,
@@ -7,6 +7,11 @@ export function Stepper(props: BlockProps<DocumentBlockStepper>) {
const { block, style, ancestorBlocks, ...contextProps } = props; const { block, style, ancestorBlocks, ...contextProps } = props;
return ( return (
<Blocks {...contextProps} nodes={block.nodes} ancestorBlocks={[...ancestorBlocks, block]} /> <Blocks
blockStyle={style}
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
/>
); );
} }
@@ -30,17 +30,17 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
})(); })();
return ( return (
<div className="flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto"> <div className={tcls('flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto', style)}>
<div className="relative select-none"> <div className="relative select-none">
<div <div
className={tcls( className={tcls(
'flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums', 'can-override-bg can-override-text flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
'font-medium text-primary-800 dark:text-primary-200', 'font-medium text-primary-800 dark:text-primary-200',
)} )}
> >
{index + 1} {index + 1}
</div> </div>
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900" /> <div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900 can-override-bg" />
</div> </div>
<Blocks <Blocks
{...contextProps} {...contextProps}
@@ -2,7 +2,7 @@ import { ContentRef, 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';
@@ -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;
}
@@ -1,2 +1 @@
export * from './DocumentView'; export * from './DocumentView';
export { createHighlightingContext } from './CodeBlock';
@@ -6,46 +6,44 @@ import {
} from '@gitbook/api'; } from '@gitbook/api';
import { assertNever } from 'assert-never'; import { assertNever } from 'assert-never';
import { ClassValue } from '@/lib/tailwind';
/** /**
* Get the line height of a block * Get the line height of a block
*/ */
export function getBlockTextStyle(block: DocumentBlock): { export function getBlockTextStyle(block: DocumentBlock): {
/** Tailwind class for the text size */ /** Tailwind class for the text size */
textSize: ClassValue; textSize: string;
/** Tailwind class for the height (h-*) */ /** Tailwind class for the height (h-*) */
lineHeight: ClassValue; lineHeight: string;
/** Tailwind class for the margin top (mt-*) */ /** Tailwind class for the margin top (mt-*) */
marginTop?: ClassValue; marginTop?: string;
} { } {
switch (block.type) { switch (block.type) {
case 'paragraph': case 'paragraph':
return { return {
textSize: ['text-base'], textSize: 'text-base',
lineHeight: 'leading-normal', lineHeight: 'leading-normal',
}; };
case 'heading-1': case 'heading-1':
return { return {
textSize: ['text-3xl', 'font-semibold'], textSize: 'text-3xl font-semibold',
lineHeight: 'leading-tight', lineHeight: 'leading-tight',
marginTop: '[margin-top:_1em]', marginTop: 'mt-[1em]',
}; };
case 'heading-2': case 'heading-2':
return { return {
textSize: ['text-2xl', 'font-semibold'], textSize: 'text-2xl font-semibold',
lineHeight: 'leading-snug', lineHeight: 'leading-snug',
marginTop: '[margin-top:_0.75em]', marginTop: 'mt-[0.75em]',
}; };
case 'heading-3': case 'heading-3':
return { return {
textSize: ['text-base', 'font-semibold'], textSize: 'text-base font-semibold',
lineHeight: 'leading-snug', lineHeight: 'leading-snug',
marginTop: '[margin-top:_0.5em]', marginTop: 'mt-[0.5em]',
}; };
case 'divider': case 'divider':
return { return {
textSize: [], textSize: '',
lineHeight: 'leading-none', lineHeight: 'leading-none',
}; };
case 'list-ordered': case 'list-ordered':
@@ -56,7 +54,7 @@ export function getBlockTextStyle(block: DocumentBlock): {
return getBlockTextStyle(block.nodes[0]); return getBlockTextStyle(block.nodes[0]);
default: default:
return { return {
textSize: ['text-base'], textSize: 'text-base',
lineHeight: 'leading-normal', lineHeight: 'leading-normal',
}; };
} }
@@ -13,7 +13,7 @@ export function FooterLinksGroup(props: {
return ( return (
<div className={tcls('flex', 'flex-col', 'gap-3')}> <div className={tcls('flex', 'flex-col', 'gap-3')}>
<p className={tcls('text-base', 'font-medium')}>{group.title}</p> <p className={tcls('text-base', 'font-semibold')}>{group.title}</p>
{group.links.map((link, index) => { {group.links.map((link, index) => {
return <FooterLink key={index} link={link} context={context} />; return <FooterLink key={index} link={link} context={context} />;
})} })}
@@ -32,7 +32,14 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
return ( return (
<Link <Link
href={resolved.href} href={resolved.href}
className={tcls('text-sm', 'text-primary-400', 'hover:text-primary-500')} className={tcls(
'text-sm',
'font-normal',
'text-dark/8',
'hover:text-dark/9',
'dark:text-light/8',
'dark:hover:text-light/9',
)}
> >
{link.title} {link.title}
</Link> </Link>
@@ -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,12 +39,12 @@ 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',
'left-0', 'left-0',
'z-10', 'z-20',
'origin-top-left', 'origin-top-left',
'invisible', 'invisible',
'transition-opacity', 'transition-opacity',
@@ -82,11 +82,12 @@ export function Dropdown<E extends HTMLElement>(props: {
/** /**
* Animated chevron to display in the dropdown button. * Animated chevron to display in the dropdown button.
*/ */
export function DropdownChevron(props: {}) { export function DropdownChevron() {
return ( return (
<Icon <Icon
icon="chevron-down" icon="chevron-down"
className={tcls( className={tcls(
'shrink-0',
'opacity-6', 'opacity-6',
'size-3', 'size-3',
'ms-1', 'ms-1',
@@ -110,31 +111,38 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
* Menu item in a dropdown. * Menu item in a dropdown.
*/ */
export function DropdownMenuItem(props: { export function DropdownMenuItem(props: {
href: string; href: string | null;
active?: boolean; active?: boolean;
className?: ClassValue;
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { children, active = false, href } = props; const { children, active = false, href, className } = props;
if (href) {
return (
<Link
href={href}
prefetch={false}
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>
); );
} }
+145 -99
View File
@@ -1,15 +1,10 @@
import { import { CustomizationSettings, Site, SiteCustomizationSettings, Space } from '@gitbook/api';
CustomizationSettings,
Site,
SiteCustomizationSettings,
SiteSection,
Space,
} from '@gitbook/api';
import { CustomizationHeaderPreset } from '@gitbook/api'; import { CustomizationHeaderPreset } from '@gitbook/api';
import { Suspense } from 'react'; import { Suspense } from 'react';
import { CONTAINER_STYLE, HEADER_HEIGHT_DESKTOP } from '@/components/layout'; import { CONTAINER_STYLE, HEADER_HEIGHT_DESKTOP } from '@/components/layout';
import { t, getSpaceLanguage } from '@/intl/server'; import { t, getSpaceLanguage } from '@/intl/server';
import type { SectionsList } from '@/lib/api';
import { ContentRefContext } from '@/lib/references'; import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -20,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.
*/ */
@@ -27,14 +23,12 @@ export function Header(props: {
space: Space; space: Space;
site: Site | null; site: Site | null;
spaces: Space[]; spaces: Space[];
sections: { list: SiteSection[]; section: SiteSection } | null; sections: SectionsList | null;
context: ContentRefContext; context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings; customization: CustomizationSettings | SiteCustomizationSettings;
withTopHeader?: boolean; withTopHeader?: boolean;
children?: React.ReactNode;
}) { }) {
const { children, context, space, site, spaces, sections, customization, withTopHeader } = const { context, space, site, spaces, sections, customization, withTopHeader } = props;
props;
const isCustomizationDefault = const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default; customization.header.preset === CustomizationHeaderPreset.Default;
const hasSiteSections = sections && sections.list.length > 1; const hasSiteSections = sections && sections.list.length > 1;
@@ -52,109 +46,161 @@ 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',
<span> 'h-16',
{!hasSiteSections && isMultiVariants ? ( 'items-center',
<SpacesDropdown space={space} spaces={spaces} /> 'justify-between',
) : null} 'w-full',
</span> 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 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 z-[9] mt-0.5', 'scroll-nojump',
'w-full',
// Handle long section tabs, particularly on smaller screens.
'overflow-x-auto hide-scroll',
)} )}
> >
<div className={tcls(CONTAINER_STYLE)}> <SiteSectionTabs {...sections} />
<SiteSectionTabs sections={sections.list} section={sections.section} />
</div>
</div> </div>
) : null} ) : null}
</header> </header>
@@ -1,9 +1,9 @@
import { import {
CustomizationContentLink, CustomizationContentLink,
CustomizationHeaderLink,
CustomizationSettings, CustomizationSettings,
CustomizationHeaderPreset, CustomizationHeaderPreset,
SiteCustomizationSettings, SiteCustomizationSettings,
CustomizationHeaderItem,
} from '@gitbook/api'; } from '@gitbook/api';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
@@ -21,93 +21,41 @@ import { Button, Link } from '../primitives';
export async function HeaderLink(props: { export async function HeaderLink(props: {
context: ContentRefContext; context: ContentRefContext;
link: CustomizationHeaderLink; link: CustomizationHeaderItem;
customization: CustomizationSettings | SiteCustomizationSettings; customization: CustomizationSettings | SiteCustomizationSettings;
}) { }) {
const { context, link, customization } = props; const { context, link, customization } = props;
const target = await resolveContentRef(link.to, context); const target = link.to ? await resolveContentRef(link.to, context) : null;
if (!target) {
return null;
}
const headerPreset = customization.header.preset; const headerPreset = customization.header.preset;
const linkStyle = link.style ?? 'link';
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => {
const linkStyle = link.style ?? 'link';
switch (linkStyle) {
case 'button-secondary':
case 'button-primary': {
const variant = (() => {
switch (linkStyle) {
case 'button-secondary':
return 'secondary';
case 'button-primary':
return 'primary';
default:
assertNever(linkStyle);
}
})();
return (
<Button
href={target.href}
variant={variant}
size="medium"
className={tcls(
{
'button-primary':
headerPreset === CustomizationHeaderPreset.Custom ||
headerPreset === CustomizationHeaderPreset.Bold
? tcls(
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
)
: null,
'button-secondary': tcls(
'bg:transparent hover:bg-transparent',
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
),
}[linkStyle],
)}
>
{link.title}
</Button>
);
}
case 'link': {
return (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light',
headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}>{link.title}</span>
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</Link>
);
}
default:
assertNever(linkStyle);
}
};
if (link.links && link.links.length > 0) { if (link.links && link.links.length > 0) {
return ( return (
<Dropdown button={renderLink}> <Dropdown
className="shrink"
button={(buttonProps) => {
if (!target) {
return (
<HeaderItemDropdown
{...buttonProps}
headerPreset={headerPreset}
title={link.title}
/>
);
}
return (
<HeaderLinkNavItem
{...buttonProps}
linkStyle={linkStyle}
headerPreset={headerPreset}
title={link.title}
isDropdown
href={target?.href}
/>
);
}}
>
<DropdownMenu> <DropdownMenu>
{link.links.map((subLink, index) => ( {link.links.map((subLink, index) => (
<SubHeaderLink key={index} {...props} link={subLink} /> <SubHeaderLink key={index} {...props} link={subLink} />
@@ -117,7 +65,125 @@ export async function HeaderLink(props: {
); );
} }
return renderLink({}); if (!target) {
return null;
}
return (
<HeaderLinkNavItem
linkStyle={linkStyle}
headerPreset={headerPreset}
title={link.title}
isDropdown={false}
href={target.href}
/>
);
}
export type HeaderLinkNavItemProps = {
linkStyle: NonNullable<CustomizationHeaderItem['style']>;
headerPreset: CustomizationHeaderPreset;
title: string;
href: string;
isDropdown: boolean;
} & DropdownButtonProps<HTMLElement>;
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
switch (props.linkStyle) {
case 'button-secondary':
case 'button-primary':
return <HeaderItemButton {...props} linkStyle={props.linkStyle} />;
case 'link':
return <HeaderItemLink {...props} />;
default:
assertNever(props.linkStyle);
}
}
function HeaderItemButton(
props: Omit<HeaderLinkNavItemProps, 'linkStyle'> & {
linkStyle: 'button-secondary' | 'button-primary';
},
) {
const { linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
const variant = (() => {
switch (linkStyle) {
case 'button-secondary':
return 'secondary';
case 'button-primary':
return 'primary';
default:
assertNever(linkStyle);
}
})();
return (
<Button
href={href}
variant={variant}
size="medium"
className={tcls(
{
'button-primary':
headerPreset === CustomizationHeaderPreset.Custom ||
headerPreset === CustomizationHeaderPreset.Bold
? tcls(
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
)
: null,
'button-secondary': tcls(
'bg:transparent hover:bg-transparent',
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
),
}[linkStyle],
)}
{...rest}
>
{title}
</Button>
);
}
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
return tcls(
'flex items-center shrink',
'hover:text-header-link-400 dark:hover:text-light',
'min-w-0',
props.headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
);
}
function HeaderItemLink(props: HeaderLinkNavItemProps) {
const { headerPreset, title, isDropdown, href, ...rest } = props;
return (
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
<span className="truncate min-w-0">{title}</span>
{isDropdown ? <DropdownChevron /> : null}
</Link>
);
}
function HeaderItemDropdown(
props: {
headerPreset: CustomizationHeaderPreset;
title: string;
} & DropdownButtonProps<HTMLElement>,
) {
const { headerPreset, title, ...rest } = props;
return (
<span
className={tcls(getHeaderLinkClassName({ headerPreset }), 'cursor-default')}
{...rest}
>
{title}
<DropdownChevron />
</span>
);
} }
async function SubHeaderLink(props: { async function SubHeaderLink(props: {
@@ -1,5 +1,6 @@
import { import {
CustomizationHeaderLink, CustomizationContentLink,
CustomizationHeaderItem,
CustomizationHeaderPreset, CustomizationHeaderPreset,
CustomizationSettings, CustomizationSettings,
SiteCustomizationSettings, SiteCustomizationSettings,
@@ -10,7 +11,7 @@ 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';
/** /**
@@ -18,7 +19,7 @@ import styles from './headerLinks.module.css';
*/ */
export function HeaderLinkMore(props: { export function HeaderLinkMore(props: {
label: React.ReactNode; label: React.ReactNode;
links: CustomizationHeaderLink[]; links: CustomizationHeaderItem[];
context: ContentRefContext; context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings; customization: CustomizationSettings | SiteCustomizationSettings;
}) { }) {
@@ -30,20 +31,27 @@ 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>
); );
return ( return (
<div className={`${styles.linkEllipsis} items-center`}> <div className={`${styles.linkEllipsis} items-center z-20`}>
<Dropdown button={renderButton} className="-translate-x-48 md:translate-x-0"> <Dropdown button={renderButton} className="-translate-x-48 md:translate-x-0">
<DropdownMenu> <DropdownMenu>
{links.map((link, index) => ( {links.map((link, index) => (
@@ -55,14 +63,25 @@ export function HeaderLinkMore(props: {
); );
} }
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderLink }) { async function MoreMenuLink(props: {
context: ContentRefContext;
link: CustomizationHeaderItem | CustomizationContentLink;
}) {
const { context, link } = props; const { context, link } = props;
const target = await resolveContentRef(link.to, context); 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}>{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', '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,27 @@
'use client';
import { Transition, motion, useReducedMotion } from 'framer-motion';
import React from 'react';
import { tcls } from '@/lib/tailwind';
export function AnimatedLine({ transition }: { transition?: Transition }) {
const prefersReducedMotion = useReducedMotion();
return (
<motion.div
layout
layoutId="sections-line"
className={tcls([
'border-primary',
'border-l',
'dark:border-primary-400',
'h-full',
'absolute',
'z-20',
'-left-[5px]',
])}
transition={prefersReducedMotion ? { duration: 0 } : transition}
/>
);
}
@@ -1,11 +1,12 @@
'use client'; 'use client';
import { motion } from 'framer-motion';
import React from 'react'; import React from 'react';
import { useScrollActiveId } from '@/components/hooks'; import { useScrollActiveId } from '@/components/hooks';
import { DocumentSection } from '@/lib/document'; import { DocumentSection } from '@/lib/document';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { AnimatedLine } from './AnimatedLine';
import { HEADER_HEIGHT_DESKTOP } from '../layout'; import { HEADER_HEIGHT_DESKTOP } from '../layout';
/** /**
@@ -13,6 +14,13 @@ import { HEADER_HEIGHT_DESKTOP } from '../layout';
*/ */
const SECTION_INTERSECTING_THRESHOLD = 0.9; const SECTION_INTERSECTING_THRESHOLD = 0.9;
const springCurve = {
type: 'spring',
stiffness: 700,
damping: 50,
mass: 0.8,
};
export function ScrollSectionsList(props: { sections: DocumentSection[] }) { export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
const { sections } = props; const { sections } = props;
@@ -28,37 +36,44 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
}); });
return ( return (
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'space-y-1')}> <ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'pl-1')}>
{sections.map((section) => ( {sections.map((section) => (
<li key={section.id} className={tcls('flex', 'flex-row')}> <motion.li
key={section.id}
className={tcls('flex', 'flex-row', 'relative', 'h-fit')}
>
{activeId === section.id ? <AnimatedLine transition={springCurve} /> : null}
<a <a
href={`#${section.id}`} href={`#${section.id}`}
className={tcls( className={tcls(
'flex', 'flex',
'flex-row', 'flex-row',
'z-10',
'w-full',
'items-baseline', 'items-baseline',
'left-[-1px]', 'left-[-1px]',
'relative', 'relative',
'text-sm', 'text-sm',
'py-1', 'py-1',
'ps-3', 'ps-3',
'hover:text-primary', 'pe-2',
'transition-all', 'transition-all',
'border-l', 'duration-200',
'border-transparent',
section.depth > 1 ? ['ps-6', 'opacity-8'] : null, section.depth > 1 ? ['ps-6', 'opacity-8'] : null,
activeId === section.id activeId === section.id
? [ ? [
'text-primary', 'text-primary',
'border-primary',
'dark:text-primary-400', 'dark:text-primary-400',
'dark:border-primary-400',
'opacity-[1]',
'[&>span]:bg-primary-400', '[&>span]:bg-primary-400',
'dark:[&>span]:bg-primary-600', 'dark:[&>span]:bg-primary-600',
'dark:[&>span]:text-dark', 'dark:[&>span]:text-dark',
] ]
: '', : [
'text-neutral-500',
'dark:text-neutral-400',
'hover:text-neutral-900',
'dark:hover:text-neutral-100',
],
)} )}
> >
{section.tag ? ( {section.tag ? (
@@ -71,7 +86,7 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
{section.title} {section.title}
</a> </a>
</li> </motion.li>
))} ))}
</ul> </ul>
); );
@@ -11,6 +11,7 @@ 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 { shouldTrackPageViews } from '@/lib/tracking';
@@ -21,7 +22,7 @@ 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 { TrackPageView } from './TrackPageView';
import { DocumentView, DocumentViewSkeleton, createHighlightingContext } from '../DocumentView'; import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { PageFeedbackForm } from '../PageFeedback'; import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative } from '../primitives'; import { DateRelative } from '../primitives';
@@ -31,6 +32,7 @@ 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;
@@ -42,6 +44,7 @@ export function PageBody(props: {
customization, customization,
context, context,
page, page,
ancestors,
document, document,
withPageFeedback, withPageFeedback,
} = props; } = props;
@@ -49,7 +52,6 @@ export function PageBody(props: {
const asFullWidth = document ? hasFullWidthBlock(document) : false; const asFullWidth = document ? hasFullWidthBlock(document) : false;
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
const updatedAt = page.updatedAt ?? page.createdAt; const updatedAt = page.updatedAt ?? page.createdAt;
const shouldHighlightCode = createHighlightingContext();
return ( return (
<> <>
@@ -80,7 +82,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={
@@ -100,7 +102,6 @@ export function PageBody(props: {
contentRefContext: context, contentRefContext: context,
resolveContentRef: (ref, options) => resolveContentRef: (ref, options) =>
resolveContentRef(ref, context, options), resolveContentRef(ref, context, options),
shouldHighlightCode,
}} }}
/> />
</React.Suspense> </React.Suspense>
@@ -150,7 +151,7 @@ export function PageBody(props: {
sitePointer={pointer} sitePointer={pointer}
spaceId={space.id} spaceId={space.id}
pageId={page.id} pageId={page.id}
apiHost={api().endpoint} apiHost={api().client.endpoint}
/> />
) : null} ) : null}
</> </>
@@ -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']} />
@@ -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';
@@ -17,11 +17,13 @@ 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 { emojiFontClassName } from '../primitives'; import { emojiFontClassName } from '../primitives';
import { ClientContexts } from './ClientContexts';
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 +38,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 +84,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 +112,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 +126,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,
@@ -160,6 +182,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 +214,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 +233,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 +265,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,
}, },
}; };
@@ -7,27 +7,19 @@
--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 +28,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;
@@ -126,23 +102,6 @@
@apply [&:is(h1,h2,h3,h4)>div:first-child]:[grid-area:1/2]; @apply [&:is(h1,h2,h3,h4)>div:first-child]:[grid-area:1/2];
@apply [&:is(h1,h2,h3,h4)>div:first-child]:ml-1; @apply [&:is(h1,h2,h3,h4)>div:first-child]:ml-1;
} }
/* bullet icons */
.bullet-dash {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjEiIHk9IjIuNSIgd2lkdGg9IjgiIGhlaWdodD0iMS41IiByeD0iMC42NiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==")];
}
.bullet-circleFilled {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIzIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
}
.bullet-circle {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIuNzUiIHk9IjAuNzUiIHdpZHRoPSI1LjUiIGhlaWdodD0iNS41IiByeD0iMi43NSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiLz4KPC9zdmc+Cg==")];
}
.bullet-squareFilled {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIxIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
}
.bullet-square {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxtYXNrIGlkPSJwYXRoLTEtaW5zaWRlLTFfOV80OCIgZmlsbD0id2hpdGUiPgo8cmVjdCB4PSIyIiB3aWR0aD0iNyIgaGVpZ2h0PSI3IiByeD0iMSIvPgo8L21hc2s+CjxyZWN0IHg9IjIiIHdpZHRoPSI3IiBoZWlnaHQ9IjciIHJ4PSIxIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjMiIG1hc2s9InVybCgjcGF0aC0xLWluc2lkZS0xXzlfNDgpIi8+Cjwvc3ZnPgo=")];
}
} }
@layer utilities { @layer utilities {
@@ -233,3 +192,30 @@ html {
html.dark { html.dark {
color-scheme: dark light; color-scheme: dark light;
} }
/* Emojis */
[class*='emoji'] {
font-family: var(--font-emojis-sbix);
}
/* Safari Only CSS here */
_::-webkit-full-page-media,
_:future,
:root [class*='emoji'] {
font-family: var(--font-emojis-sbix);
}
/* Chrome Only CSS here */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.emoji {
font-family: var(--font-emojis-colrv1);
}
}
/* Firefox Only CSS here */
@-moz-document url-prefix() {
.emoji {
font-family: var(--font-emojis-colrv1);
}
}
@@ -11,7 +11,26 @@ export function HighlightQuery(props: {
/** Style to apply on matching parts (default to primary) */ /** Style to apply on matching parts (default to primary) */
highlight?: ClassValue; highlight?: ClassValue;
}): React.ReactElement { }): React.ReactElement {
const { query, text, highlight = ['text-bold', 'text-primary'] } = props; const {
query,
text,
highlight = [
'text-bold',
'bg-primary-100',
'text-contrast-primary-100',
'dark:bg-primary-700',
'dark:text-contrast-primary-700',
'px-0.5',
'-mx-0.5',
'py-0.5',
'rounded',
'straight-corners:rounded-sm',
'group-[.is-active]:bg-primary-200',
'group-[.is-active]:text-contrast-primary-200',
'dark:group-[.is-active]:bg-primary-700',
'dark:group-[.is-active]:text-contrast-primary-700',
],
} = props;
const matches = matchString(text, query); const matches = matchString(text, query);
return ( return (
@@ -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,30 @@ 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 { 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,12 +40,13 @@ 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 [, 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;
@@ -52,7 +56,9 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
}); });
(async () => { (async () => {
const stream = iterateStreamResponse(streamAskQuestion(spaceId, query)); const stream = iterateStreamResponse(
streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query),
);
setSearchState((prev) => setSearchState((prev) =>
prev prev
@@ -68,7 +74,6 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
if (cancelled) { if (cancelled) {
return; return;
} }
setState({ setState({
type: 'answer', type: 'answer',
answer: chunk, answer: chunk,
@@ -91,7 +96,7 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
cancelled = true; cancelled = true;
} }
}; };
}, [spaceId, query, setSearchState, setState]); }, [organizationId, siteId, siteSpaceId, query]);
React.useEffect(() => { React.useEffect(() => {
return () => { return () => {
@@ -101,30 +106,16 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
const loading = ( const loading = (
<div className={tcls('w-full', 'flex', 'items-center', 'justify-center')}> <div className={tcls('w-full', 'flex', 'items-center', 'justify-center')}>
<Loading className={tcls('w-5', 'py-4', 'text-primary')} /> <Loading className={tcls('w-6', 'py-8', 'text-primary')} />
</div> </div>
); );
return ( return (
<div <div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
className={tcls(
'max-h-[60vh]',
'overflow-y-auto',
'border-t',
'border-dark/2',
'dark:border-light/1',
)}
>
{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>
@@ -166,18 +157,25 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
<> <>
<div <div
data-test="search-ask-answer" data-test="search-ask-answer"
className={tcls('mt-4', 'px-4', 'text-dark/9', 'dark:text-light/8')} className={tcls(
'my-4',
'sm:mt-6',
'px-4',
'sm:px-12',
'text-dark/9',
'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 ? (
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
) : null}
</div> </div>
{answer.followupQuestions.length > 0 ? (
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
) : null}
{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}
</> </>
@@ -189,23 +187,25 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
const getSearchLinkProps = useSearchLink(); const getSearchLinkProps = useSearchLink();
return ( return (
<div className={tcls('mt-7 mb-4', 'flex', 'flex-col', 'flex-wrap', 'gap-1')}> <div className={tcls('flex', 'flex-col', 'flex-wrap', 'mt-4', 'sm:mt-6')}>
{followupQuestions.map((question) => ( {followupQuestions.map((question) => (
<Link <Link
key={question} key={question}
className={tcls( className={tcls(
'text-sm', 'flex',
'font-medium', 'items-center',
'inline-flex',
'items-start',
'gap-2', 'gap-2',
'px-4', 'px-4',
'py-1', '-mx-4',
'text-primary-500', 'py-2',
'focus-within:text-primary-700', 'rounded',
'hover:bg-primary/2', 'straight-corners:rounded-none',
'dark:text-primary-400', 'text-dark/7',
'dark:hover:bg-primary-500/3', 'dark:text-light/8',
'hover:bg-dark-4/2',
'dark:hover:bg-light-4/2',
'focus-within:bg-dark-4/2',
'dark:focus-within:bg-light-4/2',
)} )}
{...getSearchLinkProps({ {...getSearchLinkProps({
query: question, query: question,
@@ -214,7 +214,13 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
> >
<Icon <Icon
icon="magnifying-glass" icon="magnifying-glass"
className={tcls('size-[15px]', 'shrink-0', 'mt-0.5', '[opacity:0.64]')} className={tcls(
'size-4',
'shrink-0',
'mr-2',
'text-dark/5',
'dark:text-light/5',
)}
/> />
<span>{question}</span> <span>{question}</span>
</Link> </Link>
@@ -226,7 +232,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;
@@ -236,7 +242,8 @@ function AnswerSources(props: {
'flex', 'flex',
'flex-wrap', 'flex-wrap',
'gap-2', 'gap-2',
'mt-7', 'mt-4',
'sm:mt-6',
'py-4', 'py-4',
'px-4', 'px-4',
'border-t', 'border-t',
@@ -244,7 +251,7 @@ function AnswerSources(props: {
'dark:border-light/1', 'dark:border-light/1',
)} )}
> >
<span className={tcls('text-sm')}> <span>
{t(language, hasAnswer ? 'search_ask_sources' : 'search_ask_sources_no_answer')} {t(language, hasAnswer ? 'search_ask_sources' : 'search_ask_sources_no_answer')}
</span> </span>
@@ -253,7 +260,9 @@ function AnswerSources(props: {
<Link <Link
className={tcls( className={tcls(
'flex', 'flex',
'text-sm', 'flex-wrap',
'gap-1',
'items-center',
'text-dark/7', 'text-dark/7',
'hover:underline', 'hover:underline',
'focus-within:text-primary-700', 'focus-within:text-primary-700',
@@ -266,11 +275,8 @@ function AnswerSources(props: {
icon="arrow-up-right" icon="arrow-up-right"
className={tcls( className={tcls(
'text-dark/6', 'text-dark/6',
'w-[15px]', 'size-4',
'h-[15px]',
'shrink-0', 'shrink-0',
'mt-0.5',
'mr-0.5',
'dark:text-light/6', 'dark:text-light/6',
)} )}
/> />
@@ -1,6 +1,7 @@
'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';
@@ -35,45 +36,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/6',
'dark:text-light/6',
'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 +121,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/6',
'contrast-more:text-dark', 'contrast-more:text-dark',
'dark:text-light/5', 'dark:text-light/6',
'whitespace-nowrap',
'contrast-more:dark:text-light', 'contrast-more:dark:text-light',
`[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';
@@ -56,10 +55,6 @@ export function SearchModal(props: SearchModalProps) {
}; };
}, [isSearchOpened]); }, [isSearchOpened]);
if (state === null) {
return null;
}
const onChangeQuery = (newQuery: SearchState) => { const onChangeQuery = (newQuery: SearchState) => {
setSearchState(newQuery); setSearchState(newQuery);
}; };
@@ -72,62 +67,75 @@ 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}
onChangeQuery={onChangeQuery}
onClose={onClose}
/>
</div>
</motion.div>
) : null}
</AnimatePresence>
); );
} }
@@ -158,10 +166,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') {
@@ -182,23 +201,41 @@ function SearchModalBody(
}; };
return ( return (
<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',
'max-h',
'rounded-lg', 'rounded-lg',
'straight-corners:rounded-sm',
'ring-1', 'ring-1',
'ring-dark/1', 'ring-dark/1',
'shadow-2xl', 'shadow-2xl',
'backdrop-blur-lg',
'overflow-hidden', 'overflow-hidden',
'dark:ring-inset', 'dark:ring-inset',
'dark:bg-dark-3', 'dark:bg-dark-3',
@@ -208,14 +245,33 @@ function SearchModalBody(
event.stopPropagation(); event.stopPropagation();
}} }}
> >
<div className={tcls('flex', 'flex-row', 'items-center')}> <div
<div className={tcls('p-2', 'pl-4')}> className={tcls(
'flex',
'flex-row',
'items-start',
state.query !== null ? 'border-b' : null,
'border-dark/2',
'dark:border-light/2',
)}
>
<div className={tcls('p-2', 'pl-4', 'pt-4')}>
<Icon <Icon
icon="magnifying-glass" icon="magnifying-glass"
className={tcls('size-4', 'text-dark/4', 'dark:text-light/5')} className={tcls('size-4', 'text-dark/4', 'dark:text-light/5')}
/> />
</div> </div>
<div className={tcls('flex-1')}> <div
className={tcls(
'w-full',
'flex',
'flex-row',
'flex-wrap',
'gap-y-0',
'gap-x-4',
'items-end',
)}
>
<input <input
ref={inputRef} ref={inputRef}
value={state.query} value={state.query}
@@ -226,7 +282,7 @@ function SearchModalBody(
'placeholder:text-dark/7', 'placeholder:text-dark/7',
'flex', 'flex',
'resize-none', 'resize-none',
'w-full', 'flex-1',
'h-12', 'h-12',
'p-2', 'p-2',
'focus:outline-none', 'focus:outline-none',
@@ -243,6 +299,7 @@ function SearchModalBody(
autoComplete="off" autoComplete="off"
autoCorrect="off" autoCorrect="off"
/> />
{isMultiVariants ? <SearchScopeToggle spaceTitle={spaceTitle} /> : null}
</div> </div>
</div> </div>
{!state.ask || !withAsk ? ( {!state.ask || !withAsk ? (
@@ -261,15 +318,11 @@ function SearchModalBody(
global: state.global, global: state.global,
}); });
}} }}
> ></SearchResults>
{isMultiVariants && state.query ? (
<SearchScopeToggle spaceTitle={spaceTitle} />
) : null}
</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}
</div> </motion.div>
); );
} }
@@ -1,3 +1,4 @@
import { Icon } from '@gitbook/icons';
import React from 'react'; import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -22,26 +23,68 @@ 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',
'px-6', 'items-center',
'py-3', 'p-4',
'hover:bg-dark-4/2', 'border-t',
'border-dark/2',
'dark:border-light/1',
'first:border-none',
'text-base', 'text-base',
'text-dark', 'font-medium',
'font-semibold', 'hover:bg-dark/1',
'first:mt-0', 'dark:hover:bg-light/1',
'[&:has(+.search-section-result-item):not(:first-child)]:mt-6', 'group',
'dark:text-light', active
'dark:hover:bg-light-4/2', ? [
active ? ['bg-dark/1', 'dark:bg-light/1'] : null, '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,
)} )}
> >
{item.spaceTitle ? ( <div className="size-4">
<span className={tcls('opacity-6', 'font-normal', 'mr-2')}> <Icon
{item.spaceTitle + ' '} icon="file-lines"
</span> className={tcls('size-4', active ? 'text-primary' : 'opacity-5')}
) : null} />
<HighlightQuery query={query} text={item.title} /> </div>
<div className={tcls('flex', 'flex-col', 'w-full')}>
{item.spaceTitle ? (
<div
className={tcls(
'text-xs',
'opacity-6',
'font-normal',
'uppercase',
'tracking-wider',
'mb-1',
)}
>
{item.spaceTitle}
</div>
) : null}
<HighlightQuery query={query} text={item.title} />
</div>
<div
className={tcls(
'p-2',
'rounded',
'straight-corners:rounded-none',
active ? ['bg-primary', 'text-contrast-primary'] : ['opacity-6'],
)}
>
<Icon
icon={active ? 'arrow-turn-down-left' : 'chevron-right'}
className={tcls('size-4')}
/>
</div>
</Link> </Link>
); );
}); });
@@ -26,18 +26,21 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
onClick={onClick} onClick={onClick}
className={tcls( className={tcls(
'flex', 'flex',
'flex-row',
'px-4', 'px-4',
'py-2', recommended ? ['py-2', 'text-dark/7', 'dark:text-light/8'] : 'py-4',
'hover:bg-dark-4/2', 'hover:bg-dark/1',
'text-dark/7', 'dark:hover:bg-light/1',
'text-sm',
'font-medium',
'first:mt-0', 'first:mt-0',
'last:pb-3', 'last:pb-3',
'dark:text-light/8', active && [
'dark:hover:bg-light-4/2', 'is-active',
active ? ['bg-dark/1', 'dark:bg-light/1'] : null, 'bg-primary-50',
'text-contrast-primary-50',
'dark:bg-primary-800',
'dark:text-contrast-primary-800',
'hover:bg-primary-100/8',
'dark:hover:bg-primary-700/7',
],
)} )}
{...getLinkProp({ {...getLinkProp({
ask: true, ask: true,
@@ -45,18 +48,41 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
})} })}
> >
<Icon <Icon
icon="magnifying-glass" icon={recommended ? 'search' : 'sparkles'}
className={tcls( className={tcls(
'w-[15px]', 'size-4',
'h-[15px]',
'shrink-0', 'shrink-0',
'mt-0.5', 'mt-1.5',
'mr-4', 'mr-4',
'text-dark/5', active ? ['text-primary'] : ['text-dark/5', 'dark:text-light/5'],
'dark:text-light/5',
)} )}
/> />
{recommended ? question : t(language, 'search_ask', [question])} <div className="w-full">
{recommended ? (
question
) : (
<>
<div className="font-medium">{t(language, 'search_ask', [question])}</div>
<div className={tcls('text-sm', 'text-dark/8', 'dark:text-light/8')}>
{t(language, 'search_ask_description')}
</div>
</>
)}
</div>
<div
className={tcls(
'p-2',
'rounded',
'self-center',
'straight-corners:rounded-none',
active ? ['bg-primary', 'text-contrast-primary'] : ['opacity-6'],
)}
>
<Icon
icon={active ? 'arrow-turn-down-left' : 'chevron-right'}
className={tcls('size-4')}
/>
</div>
</Link> </Link>
); );
}); });
@@ -5,7 +5,6 @@ import { t, useLanguage } from '@/intl/client';
import { SiteContentPointer } from '@/lib/api'; import { SiteContentPointer } from '@/lib/api';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { isQuestion } from './isQuestion';
import { SearchPageResultItem } from './SearchPageResultItem'; import { SearchPageResultItem } from './SearchPageResultItem';
import { SearchQuestionResultItem } from './SearchQuestionResultItem'; import { SearchQuestionResultItem } from './SearchQuestionResultItem';
import { SearchSectionResultItem } from './SearchSectionResultItem'; import { SearchSectionResultItem } from './SearchSectionResultItem';
@@ -92,8 +91,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
} }
debounceTimeout.current = setTimeout(async () => { debounceTimeout.current = setTimeout(async () => {
setCursor(null);
const fetchedResults = await (global const fetchedResults = await (global
? searchAllSiteContent(query, pointer) ? searchAllSiteContent(query, pointer)
: searchSiteSpaceContent(query, pointer, revisionId)); : searchSiteSpaceContent(query, pointer, revisionId));
@@ -110,6 +107,16 @@ export const SearchResults = React.forwardRef(function SearchResults(
} }
}, [query, global, pointer, spaceId, revisionId, withAsk]); }, [query, global, pointer, spaceId, revisionId, withAsk]);
React.useEffect(() => {
if (!query) {
// Reset the cursor when there's no query
setCursor(null);
} else if (results && results.length > 0) {
// Auto-focus the first result
setCursor(0);
}
}, [results, query]);
// Scroll to the active result. // Scroll to the active result.
React.useEffect(() => { React.useEffect(() => {
if (cursor === null || !refs.current[cursor]) { if (cursor === null || !refs.current[cursor]) {
@@ -174,24 +181,15 @@ export const SearchResults = React.forwardRef(function SearchResults(
} }
return ( return (
<div <div className={tcls('overflow-auto')}>
className={tcls(
'max-h-[60vh]',
'overflow-auto',
'relative',
'shadow-[0_1px_0_0_inset]',
'shadow-dark/2',
'dark:shadow-light/2',
)}
>
{children} {children}
{results.length === 0 ? ( {results.length === 0 ? (
<div <div
data-test="search-noresults" data-test="search-noresults"
className={tcls( className={tcls(
'text-sm', 'text',
'text-dark', 'text-dark/8',
'p-6', 'p-8',
'text-center', 'text-center',
'dark:text-light/8', 'dark:text-light/8',
)} )}
@@ -265,10 +263,13 @@ export const SearchResults = React.forwardRef(function SearchResults(
); );
}); });
/**
* Add a "Ask <question>" item at the top of the results list.
*/
function withQuestionResult(results: null | ResultType[], query: string): null | ResultType[] { function withQuestionResult(results: null | ResultType[], query: string): null | ResultType[] {
const without = results ? results.filter((result) => result.type !== 'question') : null; const without = results ? results.filter((result) => result.type !== 'question') : null;
if (!isQuestion(query)) { if (query.length === 0) {
return without; return without;
} }
@@ -20,31 +20,7 @@ export function SearchScopeToggle(props: { spaceTitle: string }) {
<div <div
role="toolbar" role="toolbar"
aria-orientation="horizontal" aria-orientation="horizontal"
className={tcls( className={tcls('flex', 'flex-row', 'mr-4')}
'overflow-x-auto',
'hide-scroll',
'flex',
'flex-row',
'py-3',
'gap-0',
'px-0',
'pt-0',
'sticky',
'z-[0]',
'w-[calc(100%-1px)]',
'left-[1px]',
'top-[0px]',
'bg-gradient-to-b',
'from-white',
'to-transparent',
'from-60%',
'dark:from-dark-3',
'shadow-[0_1px_0_0_inset]',
'shadow-dark/2',
'dark:shadow-light/2',
'md:px-6',
'md:gap-3',
)}
> >
<ToggleButton <ToggleButton
active={!state.global} active={!state.global}
@@ -81,30 +57,14 @@ function ToggleButton(props: { onClick: () => void; children: React.ReactNode; a
aria-selected={active} aria-selected={active}
onClick={onClick} onClick={onClick}
className={tcls( className={tcls(
'text-xs', 'text-sm',
'transition-colors', 'transition-colors',
'duration-75', 'px-3',
'px-2.5', 'py-2',
'py-1.5', 'border-b-2',
'border-t',
'relative',
'top-[0px]',
'z-[1]',
'border-dark/2',
'whitespace-pre', 'whitespace-pre',
'hover:border-dark/6', '-mb-[1px]',
'dark:hover:border-light/6', active ? ['text-primary-500', 'border-primary-500'] : ['border-transparent'],
'md:px-1',
active
? [
'text-primary-400',
'border-primary-400',
'hover:border-primary-400',
'dark:hover:text-primary-400',
'dark:border-primary-400',
'dark:hover:border-primary-400',
]
: null,
)} )}
> >
{children} {children}
@@ -1,3 +1,4 @@
import { Icon } from '@gitbook/icons';
import React from 'react'; import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -21,38 +22,68 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
ref={ref} ref={ref}
href={item.href} href={item.href}
className={tcls( className={tcls(
'search-section-result-item',
'[&:has(+:not(&))]:mb-6', '[&:has(+:not(&))]:mb-6',
'flex', 'flex',
'flex-col', 'items-center',
'pl-6', 'pl-6',
'hover:bg-dark-4/2', 'sm:pl-12',
'dark:hover:bg-light-4/2', 'pr-4',
active ? ['bg-dark/1', 'dark:bg-light/1'] : null, 'text-dark/8',
'dark:text-light/8',
'hover:bg-dark/1',
'dark:hover:bg-light/1',
'font-normal',
'py-2',
'group',
active && [
'is-active',
'bg-primary-50',
'text-contrast-primary-50',
'dark:bg-primary-800',
'dark:text-contrast-primary-800',
'hover:bg-primary-100/8',
'dark:hover:bg-primary-700/7',
],
)} )}
> >
<div className={tcls('border-l', 'p-3', 'border-dark/2', 'dark:border-light/2')}> <div
className={tcls(
'border-l-2',
'px-4',
'py-1',
'flex',
'flex-1',
'overflow-hidden',
'flex-col',
'border-dark/2',
'dark:border-light/2',
)}
>
{item.title ? ( {item.title ? (
<p className={tcls('text-base', 'text-dark/7', 'dark:text-light/8')}> <p className={tcls('text-base', 'mb-2')}>
<HighlightQuery query={query} text={item.title} /> <HighlightQuery query={query} text={item.title} />
</p> </p>
) : null} ) : null}
{item.body ? ( {item.body ? (
<p <p className={tcls('text-sm', 'line-clamp-3', 'relative')}>
className={tcls(
'text-sm',
'text-dark',
'line-clamp-6',
'linear-mask-gradient',
'z-[-1]', //to force stacking order
'relative',
'dark:text-light/8',
)}
>
<HighlightQuery query={query} text={item.body} /> <HighlightQuery query={query} text={item.body} />
</p> </p>
) : null} ) : null}
</div> </div>
<div
className={tcls(
'p-2',
'rounded',
'straight-corners:rounded-none',
'bg-primary',
'text-contrast-primary',
'hidden',
'sm:block',
active ? ['opacity-11', 'block'] : ['opacity-0'],
)}
>
<Icon icon="arrow-turn-down-left" className={tcls('size-4')} />
</div>
</Link> </Link>
); );
}); });
@@ -39,10 +39,10 @@ export interface AskAnswerSource {
} }
export interface AskAnswerResult { export interface AskAnswerResult {
/** Undefined if no answer. */
body?: React.ReactNode; body?: React.ReactNode;
followupQuestions: string[]; followupQuestions: string[];
sources: AskAnswerSource[]; sources: AskAnswerSource[];
hasAnswer: boolean;
} }
/** /**
@@ -68,16 +68,11 @@ async function searchSiteContent(args: {
scope.mode === 'current' || scope.mode === 'current' ||
(scope.mode === 'specific' && scope.siteSpaceIds.length > 1); (scope.mode === 'specific' && scope.siteSpaceIds.length > 1);
const [searchResults, siteStructure] = await Promise.all([ const [searchResults, siteData] = await Promise.all([
api.searchSiteContent(pointer.organizationId, pointer.siteId, query, scope, cacheBust), api.searchSiteContent(pointer.organizationId, pointer.siteId, query, scope, cacheBust),
needsStructure needsStructure ? api.getSiteData(pointer) : null,
? api.getSiteStructure({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
})
: null,
]); ]);
const siteStructure = siteData?.structure;
const siteSpaces = siteStructure const siteSpaces = siteStructure
? siteStructure.type === 'siteSpaces' ? siteStructure.type === 'siteSpaces'
@@ -87,7 +82,7 @@ async function searchSiteContent(args: {
...siteSpace, ...siteSpace,
space: { space: {
...siteSpace.space, ...siteSpace.space,
title: section.title + ' ' + siteSpace.space.title, title: section.title || siteSpace.space.title,
}, },
})); }));
@@ -157,16 +152,53 @@ export async function searchSiteSpaceContent(
/** /**
* Server action to ask a question in a space. * Server action to ask a question in a space.
*/ */
export const streamAskQuestion = streamResponse(async function* (spaceId: string, query: string) { export const streamAskQuestion = streamResponse(async function* (
const stream = api organizationId: string,
.api() siteId: string,
.spaces.streamAskInSpace(spaceId, { query, format: 'document', details: true }); siteSpaceId: string | null,
const pagesPromise = api.getSpaceContentData({ spaceId }, undefined); question: string,
) {
const stream = api.api().client.orgs.streamAskInSite(
organizationId,
siteId,
{
question,
context: siteSpaceId
? {
siteSpaceId,
}
: undefined,
scope: {
mode: 'default',
// Include the current site space regardless.
includedSiteSpaces: siteSpaceId ? [siteSpaceId] : undefined,
},
},
{ format: 'document' },
);
const spaceData = new PromiseQueue<string, RevisionPage[]>();
for await (const chunk of stream) { for await (const chunk of stream) {
// We run the AI search and fetch the pages in parallel const answer = chunk.answer;
const { pages } = await pagesPromise;
// Register the space of each page source into the promise queue.
const spaces = answer.sources
.map((source) => {
if (source.type !== 'page') {
return null;
}
spaceData.registerPromise(source.space, () => {
return api.getRevisionPages(source.space, source.revision, { metadata: false });
});
return source.space;
})
.filter(filterOutNullable);
// Get the pages for all spaces referenced by this answer.
const pages = await spaceData.getPromises(spaces);
yield transformAnswer(chunk.answer, pages); yield transformAnswer(chunk.answer, pages);
} }
}); });
@@ -180,26 +212,28 @@ export async function getRecommendedQuestions(spaceId: string): Promise<string[]
} }
function transformAnswer( function transformAnswer(
answer: SearchAIAnswer | undefined, answer: SearchAIAnswer,
pages: RevisionPage[], spacePages: Map<string, RevisionPage[]>,
): AskAnswerResult | null { ): AskAnswerResult {
if (!answer) {
return null;
}
const sources = answer.sources const sources = answer.sources
.map((source) => { .map((source) => {
if (source.type !== 'page') { if (source.type !== 'page') {
return null; return null;
} }
const pages = spacePages.get(source.space);
if (!pages) {
return null;
}
const page = resolvePageId(pages, source.page); const page = resolvePageId(pages, source.page);
if (!page) { if (!page) {
return null; return null;
} }
return { return {
id: page.page.id, id: source.page,
title: page.page.title, title: page.page.title,
href: pageHref(pages, page.page), href: pageHref(pages, page.page),
}; };
@@ -215,7 +249,6 @@ function transformAnswer(
mode: 'default', mode: 'default',
contentRefContext: null, contentRefContext: null,
resolveContentRef: async () => null, resolveContentRef: async () => null,
shouldHighlightCode: () => true,
wrapBlocksInSuspense: false, wrapBlocksInSuspense: false,
}} }}
style={['space-y-5']} style={['space-y-5']}
@@ -223,7 +256,6 @@ function transformAnswer(
) : null, ) : null,
followupQuestions: answer.followupQuestions, followupQuestions: answer.followupQuestions,
sources, sources,
hasAnswer: !!answer.answer && 'document' in answer.answer,
}; };
} }
@@ -289,3 +321,70 @@ function transformPageResult(item: SearchPageResult, space?: Space) {
return [page, ...sections]; return [page, ...sections];
} }
/**
* A queue for promises that performs deduplication of requests
* and ensures they run sequentially.
*
* This is useful when you want to make multiple async requests
* but want to avoid making the same request multiple times.
*
* Running the promises sequentially gives us some safety about
* hitting Cloudflare Worker's 6 parallel subrequest limits.
*/
class PromiseQueue<Key extends string, Value> {
private promiseQueue: (() => Promise<Value>)[] = [];
private results: Map<Key, Value> = new Map();
private registeredKeys: Set<Key> = new Set();
private currentExecution: Promise<void> | null = null;
private async executeQueue() {
while (this.promiseQueue.length > 0) {
const promiseFn = this.promiseQueue.shift()!;
await promiseFn();
}
this.currentExecution = null; // Mark the queue as idle
}
registerPromise(key: Key, fn: () => Promise<Value>): void {
if (this.registeredKeys.has(key)) {
return;
}
this.registeredKeys.add(key);
const wrapperFn = async () => {
const result = await fn();
this.results.set(key, result);
return result;
};
this.promiseQueue.push(wrapperFn);
// Start executing if not already running
if (!this.currentExecution) {
this.currentExecution = this.executeQueue();
}
}
/**
* Returns a promise that resolves to a map of results for the given keys.
* If the key has not been registered in the queue, it will be ignored.
*/
async getPromises(keys: Key[]): Promise<Map<Key, Value>> {
// Wait for any ongoing executions to finish
if (this.currentExecution) {
await this.currentExecution;
}
return keys.reduce((map, key) => {
const data = this.results.get(key);
if (data) {
return map.set(key, data);
}
return map;
}, new Map<Key, Value>());
}
}
@@ -0,0 +1,21 @@
import type { SiteSection } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import { type ClassValue, tcls } from '@/lib/tailwind';
/**
* Icon shown beside a section in the site section tabs.
*/
export function SectionIcon(props: { icon: IconName; isActive: boolean }) {
const { icon, isActive } = props;
return (
<Icon
icon={icon}
className={tcls(
'size-[1em] text-inherit opacity-8',
isActive && 'text-inherit opacity-10',
)}
/>
);
}
@@ -1,107 +1,132 @@
'use client'; 'use client';
import { SiteSection } from '@gitbook/api';
import { Icon } from '@gitbook/icons'; import type { SiteSection } from '@gitbook/api';
import type { IconName } from '@gitbook/icons';
import React from 'react'; import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { Button, Link } from '../primitives'; import { Link } from '../primitives';
import { SectionIcon } from './SectionIcon';
/** /**
* A set of tabs representing site sections for multi-section sites * A set of navigational tabs representing site sections for multi-section sites
*/ */
export function SiteSectionTabs(props: { sections: SiteSection[]; section: SiteSection }) { export function SiteSectionTabs(props: {
const { sections, section: currentSection } = props; list: SiteSection[];
section: SiteSection;
const tabs = sections.map((section) => ({ index: number;
id: section.id, }) {
label: section.title, const { list: sections, index: currentIndex } = props;
path: section.urls.published ?? '',
}));
const currentTabRef = React.useRef<HTMLAnchorElement>(null); const currentTabRef = React.useRef<HTMLAnchorElement>(null);
const navRef = React.useRef<HTMLDivElement>(null); const navRef = React.useRef<HTMLDivElement>(null);
const [currentIndex, setCurrentIndex] = React.useState(
sections.findIndex((section) => section.id === currentSection?.id),
);
const [tabDimensions, setTabDimensions] = React.useState<{ const [tabDimensions, setTabDimensions] = React.useState<{
left: number; left: number;
width: number; width: number;
} | null>(null); } | null>(null);
React.useEffect(() => { const updateTabDimensions = React.useCallback(() => {
if (currentTabRef.current && navRef.current) { if (currentTabRef.current && navRef.current) {
const rect = currentTabRef.current.getBoundingClientRect(); const rect = currentTabRef.current.getBoundingClientRect();
const navRect = navRef.current.getBoundingClientRect(); const navRect = navRef.current.getBoundingClientRect();
setTabDimensions({ left: rect.left - navRect.left, width: rect.width });
}
}, [currentIndex]);
React.useLayoutEffect(() => { setTabDimensions({
function onResize() { left: rect.left - navRect.left,
if (currentTabRef.current && navRef.current) { width: rect.width,
const rect = currentTabRef.current.getBoundingClientRect(); });
const navRect = navRef.current.getBoundingClientRect();
setTabDimensions({ left: rect.left - navRect.left, width: rect.width });
}
} }
window.addEventListener('resize', onResize);
() => window.removeEventListener('resize', onResize);
}, []); }, []);
React.useEffect(() => {
if (currentIndex >= 0) {
updateTabDimensions();
}
}, [currentIndex, updateTabDimensions]);
React.useLayoutEffect(() => {
window.addEventListener('load', updateTabDimensions);
window.addEventListener('resize', updateTabDimensions);
() => {
window.removeEventListener('resize', updateTabDimensions);
window.removeEventListener('load', updateTabDimensions);
};
}, [updateTabDimensions]);
const opacity = tabDimensions ? 1 : 0.0;
const scale = (tabDimensions?.width ?? 0) * 0.01; const scale = (tabDimensions?.width ?? 0) * 0.01;
const startPos = `${tabDimensions?.left ?? 0}px`; const startPos = `${tabDimensions?.left ?? 0}px`;
const hasMoreSections = false; /** TODO: determine whether we need to show the more button */ return sections.length > 0 ? (
return tabs.length > 0 ? (
<nav <nav
aria-label="Sections" aria-label="Sections"
ref={navRef} ref={navRef}
className="flex flex-nowrap items-center max-w-screen mb-px" className="flex flex-nowrap items-center mb-px max-w-screen-2xl mx-auto page-full-width:max-w-full"
style={ style={
{ {
'--tab-opacity': `${opacity}`,
'--tab-scale': `${scale}`, '--tab-scale': `${scale}`,
'--tab-start': `${startPos}`, '--tab-start': `${startPos}`,
} as React.CSSProperties } as React.CSSProperties
} }
> >
<div <div className="flex flex-col bg-transparent">
className={tcls( {/* An element for the tabs which includes the page padding */}
'relative', <div
'flex', role="tablist"
'gap-2', className={tcls(
'bg-transparent', 'flex flex-row gap-2',
/* add a pseudo element for active tab indicator */ // Horizontal padding, which is the layout padding minus the padding of the tabs themselves.
'after:block', 'px-1',
"after:content-['']", 'sm:px-3',
'after:origin-left', 'md:px-5',
'after:absolute', )}
'after:-bottom-px', >
'after:left-0', {sections.map((section, index) => {
'after:scale-x-[--tab-scale]', const { id, urls, title, icon } = section;
'after:transition-transform', const isActive = index === currentIndex;
'after:translate-x-[var(--tab-start)]', return (
'after:h-0.5', <Tab
'after:w-[100px]', active={isActive}
'after:bg-primary', key={id}
'dark:after:bg-primary-400', label={title}
)} href={urls.published ?? ''}
role="tablist" ref={isActive ? currentTabRef : null}
> icon={
{tabs.map((tab, index) => ( icon ? (
<Tab <SectionIcon isActive={isActive} icon={icon as IconName} />
active={currentIndex === index} ) : null
key={index + tab.path} }
label={tab.label} />
href={tab.path} );
ref={currentIndex === index ? currentTabRef : null} })}
onClick={() => setCurrentIndex(index)} </div>
/> {/* A container for a pseudo element for active tab indicator. A container is needed so we can set
))} a relative position without breaking the z-index of other parts of the header. */}
<div
className={tcls(
'flex',
'relative',
'after:block',
"after:content-['']",
'after:origin-left',
'after:absolute',
'after:-bottom-px',
'after:left-0',
'after:opacity-[--tab-opacity]',
'after:scale-x-[--tab-scale]',
'after:[transition:_opacity_150ms_25ms,transform_150ms]',
'after:motion-reduce:transition-none',
'after:translate-x-[var(--tab-start)]',
'after:will-change-transform',
'after:h-0.5',
'after:w-[100px]',
'after:bg-primary',
'dark:after:bg-primary-400',
)}
/>
</div> </div>
{hasMoreSections ? <MoreSectionsButton /> : null}
</nav> </nav>
) : null; ) : null;
} }
@@ -111,37 +136,24 @@ export function SiteSectionTabs(props: { sections: SiteSection[]; section: SiteS
*/ */
const Tab = React.forwardRef< const Tab = React.forwardRef<
HTMLSpanElement, HTMLSpanElement,
{ active: boolean; href: string; label: string; onClick?: () => void } { active: boolean; href: string; icon?: React.ReactNode; label: string }
>(function Tab(props, ref) { >(function Tab(props, ref) {
const { active, href, label, onClick } = props; const { active, href, icon, label } = props;
return ( return (
<Link <Link
className={tcls( className={tcls(
'px-3 py-1 my-2 rounded straight-corners:rounded-none transition-colors', 'group/tab px-3 py-1 my-2 rounded straight-corners:rounded-none transition-colors',
active && 'text-primary dark:text-primary-400', active && 'text-primary dark:text-primary-400',
!active && !active &&
'text-dark/8 hover:bg-dark/1 hover:text-dark/9 dark:text-light/8 dark:hover:bg-light/2 dark:hover:text-light/9', 'text-dark/8 hover:bg-dark/1 hover:text-dark/9 dark:text-light/8 dark:hover:bg-light/2 dark:hover:text-light/9',
)} )}
role="tab" role="tab"
href={href} href={href}
onClick={onClick}
> >
<span ref={ref} className={tcls('inline-flex w-full truncate')}> <span ref={ref} className={tcls('flex gap-2 items-center w-full truncate')}>
{icon}
{label} {label}
</span> </span>
</Link> </Link>
); );
}); });
/**
* Dropdown trigger for when there are too many sections to show them all
*/
function MoreSectionsButton() {
return (
<div>
<Button variant="secondary" size="small">
<Icon icon="ellipsis-h" size={12} />
</Button>
</div>
);
}
@@ -6,7 +6,6 @@ import {
RevisionPageGroup, RevisionPageGroup,
Site, Site,
SiteCustomizationSettings, SiteCustomizationSettings,
SiteSection,
Space, Space,
} from '@gitbook/api'; } from '@gitbook/api';
import React from 'react'; import React from 'react';
@@ -17,7 +16,7 @@ import { CONTAINER_STYLE } from '@/components/layout';
import { ColorDebugger } from '@/components/primitives/ColorDebugger'; import { ColorDebugger } from '@/components/primitives/ColorDebugger';
import { SearchModal } from '@/components/Search'; import { SearchModal } from '@/components/Search';
import { TableOfContents } from '@/components/TableOfContents'; import { TableOfContents } from '@/components/TableOfContents';
import { ContentTarget, SiteContentPointer } from '@/lib/api'; import { ContentTarget, type SectionsList, SiteContentPointer } from '@/lib/api';
import { ContentRefContext } from '@/lib/references'; import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -31,7 +30,7 @@ export function SpaceLayout(props: {
contentTarget: ContentTarget; contentTarget: ContentTarget;
space: Space; space: Space;
site: Site | null; site: Site | null;
sections: { list: SiteSection[]; section: SiteSection } | null; sections: SectionsList | null;
spaces: Space[]; spaces: Space[];
customization: CustomizationSettings | SiteCustomizationSettings; customization: CustomizationSettings | SiteCustomizationSettings;
pages: Revision['pages']; pages: Revision['pages'];
@@ -107,9 +106,13 @@ export function SpaceLayout(props: {
) )
} }
innerHeader={ innerHeader={
(sections || !withTopHeader) && withVariants ? ( withVariants && (
<SpacesDropdown space={space} spaces={spaces} /> <SpacesDropdown
) : null className={withTopHeader && !sections ? 'sm:hidden' : undefined}
space={space}
spaces={spaces}
/>
)
} }
headerOffset={headerOffset} headerOffset={headerOffset}
/> />
@@ -8,13 +8,16 @@ import { useHash } from './useHash';
* to the top of the page when navigating between pages (pathname) * to the top of the page when navigating between pages (pathname)
* or sections of a page (hash). * or sections of a page (hash).
*/ */
export function useScrollPage() { export function useScrollPage(props: { scrollMarginTop?: number }) {
const hash = useHash(); const hash = useHash();
const pathname = usePathname(); const pathname = usePathname();
React.useLayoutEffect(() => { React.useLayoutEffect(() => {
if (hash) { if (hash) {
const element = document.getElementById(hash); const element = document.getElementById(hash);
if (element) { if (element) {
if (props.scrollMarginTop) {
element.style.scrollMarginTop = `${props.scrollMarginTop}px`;
}
element.scrollIntoView({ element.scrollIntoView({
block: 'start', block: 'start',
behavior: 'smooth', behavior: 'smooth',
@@ -23,5 +26,13 @@ export function useScrollPage() {
} else { } else {
window.scrollTo(0, 0); window.scrollTo(0, 0);
} }
}, [hash, pathname]); return () => {
if (hash) {
const element = document.getElementById(hash);
if (element) {
element.style.scrollMarginTop = '';
}
}
};
}, [hash, pathname, props.scrollMarginTop]);
} }
@@ -1,25 +1,25 @@
'use client'; 'use client';
import type { ComponentPropsWithoutRef, HTMLAttributes } from 'react';
import { tcls, ClassValue } from '@/lib/tailwind'; import { tcls, ClassValue } from '@/lib/tailwind';
import { Link } from './Link'; import { Link } from './Link';
type ButtonProps = { type ButtonProps = {
href?: string; href?: string;
onClick?: () => void;
children: React.ReactNode;
variant?: 'primary' | 'secondary'; variant?: 'primary' | 'secondary';
size?: 'default' | 'medium' | 'small'; size?: 'default' | 'medium' | 'small';
className?: ClassValue; className?: ClassValue;
}; } & HTMLAttributes<HTMLElement>;
export function Button({ export function Button({
href, href,
onClick,
children, children,
variant = 'primary', variant = 'primary',
size = 'default', size = 'default',
className, className,
...rest
}: ButtonProps) { }: ButtonProps) {
const variantClasses = const variantClasses =
variant === 'primary' variant === 'primary'
@@ -45,7 +45,7 @@ export function Button({
const sizes = { const sizes = {
default: ['text-base', 'px-4', 'py-2'], default: ['text-base', 'px-4', 'py-2'],
medium: ['text-base', 'px-3', 'py-1'], medium: ['text-sm', 'px-3', 'py-1'],
small: ['text-xs', 'px-3 py-2'], small: ['text-xs', 'px-3 py-2'],
}; };
@@ -69,14 +69,14 @@ export function Button({
if (href) { if (href) {
return ( return (
<Link href={href} className={domClassName}> <Link href={href} className={domClassName} {...rest}>
{children} {children}
</Link> </Link>
); );
} }
return ( return (
<button type="button" onClick={onClick} className={domClassName}> <button type="button" className={domClassName} {...rest}>
{children} {children}
</button> </button>
); );
@@ -6,16 +6,22 @@ import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
export type CheckboxProps = React.ComponentProps<typeof CheckboxPrimitive.Root> & {
/**
* The size of the checkbox.
* @default medium
*/
size?: 'small' | 'medium';
};
export const Checkbox = React.forwardRef< export const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>, React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root> CheckboxProps
>(({ className, ...props }, ref) => ( >(({ className, size = 'medium', ...props }, ref) => (
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
ref={ref} ref={ref}
className={tcls( className={tcls(
'peer', 'peer',
'h-5',
'w-5',
'shrink-0', 'shrink-0',
'rounded-sm', 'rounded-sm',
'straight-corners:rounded-none', 'straight-corners:rounded-none',
@@ -32,11 +38,12 @@ export const Checkbox = React.forwardRef<
'dark:ring-light/3', 'dark:ring-light/3',
'dark:contrast-more:ring-light/6', 'dark:contrast-more:ring-light/6',
'dark:data-[state=checked]:bg-primary-500', 'dark:data-[state=checked]:bg-primary-500',
{ small: 'size-4', medium: 'size-5' }[size],
className, className,
)} )}
{...props} {...props}
> >
<CheckboxPrimitive.Indicator className={tcls('relative', 'text-current')}> <CheckboxPrimitive.Indicator className="relative text-current">
{props.checked ? ( {props.checked ? (
<Icon icon="check" iconStyle={IconStyle.Solid} className={'size-3'} /> <Icon icon="check" iconStyle={IconStyle.Solid} className={'size-3'} />
) : null} ) : null}
@@ -3,24 +3,38 @@ import localFont from 'next/font/local';
import { getEmojiForCode } from '@/lib/emojis'; import { getEmojiForCode } from '@/lib/emojis';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
import './emoji.css'; /**
COLRv1 font.
/* Load the 3 variants of the font as CSS variables and let the emoji.css decide on the best one to use */ - lightweight, top quality
- widely supported by modern browsers
const svgFont = localFont({ - currently not by Safari (or iOS)
src: './svg.woff2', */
const colrv1Font = localFont({
src: './joypixels-colrv1.woff2',
preload: false, preload: false,
variable: '--font-emojis-svg', variable: '--font-emojis-colrv1',
}); });
/**
SBIX font.
- narrowly supported
- currently required for Safari (or iOS)
- provide alternative font-family name (see below)
*/
const sbixFont = localFont({ const sbixFont = localFont({
src: './sbix.woff2', src: './joypixels-sbix.woff2',
preload: false, preload: false,
variable: '--font-emojis-sbix', variable: '--font-emojis-sbix',
}); });
/**
CBDT font.
- widely supported
- currently not by Safari (or iOS)
- retain for legacy browser support
*/
const cbdtFont = localFont({ const cbdtFont = localFont({
src: './cbdt.woff2', src: './joypixels-cbdt.woff2',
preload: false, preload: false,
variable: '--font-emojis-cbdt', variable: '--font-emojis-cbdt',
}); });
@@ -28,7 +42,7 @@ const cbdtFont = localFont({
/** /**
* Class name to set on the <html> tag to use the emoji font. * Class name to set on the <html> tag to use the emoji font.
*/ */
export const emojiFontClassName = [svgFont.variable, sbixFont.variable, cbdtFont.variable].join( export const emojiFontClassName = [colrv1Font.variable, sbixFont.variable, cbdtFont.variable].join(
' ', ' ',
); );
@@ -40,5 +54,5 @@ export async function Emoji(props: { code: string; style?: ClassValue }) {
const { code, style } = props; const { code, style } = props;
const fallback = getEmojiForCode(code); const fallback = getEmojiForCode(code);
return <span className={'emoji ' + tcls(style)}>{fallback}</span>; return <span className={tcls('emoji', style)}>{fallback}</span>;
} }
@@ -1,24 +0,0 @@
[class*='emoji'] {
font-family: var(--font-emojis-cbdt);
}
/* Safari Only CSS here */
_::-webkit-full-page-media,
_:future,
:root [class*='emoji'] {
font-family: var(--font-emojis-sbix);
}
/* Chrome Only CSS here */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.emoji {
font-family: var(--font-emojis-svg);
}
}
/* Firefox Only CSS here */
@-moz-document url-prefix() {
.emoji {
font-family: var(--font-emojis-svg);
}
}
+1
View File
@@ -39,6 +39,7 @@ export const ibmPlexMono = IBM_Plex_Mono({
display: 'swap', display: 'swap',
preload: false, preload: false,
fallback: ['monospace'], fallback: ['monospace'],
adjustFontFallback: false,
}); });
const firaSans = Fira_Sans_Extra_Condensed({ const firaSans = Fira_Sans_Extra_Condensed({
+2 -1
View File
@@ -10,9 +10,10 @@ export const de = {
search_input_placeholder: 'Inhalt durchsuchen', search_input_placeholder: 'Inhalt durchsuchen',
search_ask_input_placeholder: 'Inhalt durchsuchen oder eine Frage stellen', search_ask_input_placeholder: 'Inhalt durchsuchen oder eine Frage stellen',
search_no_results: 'Keine Ergebnisse für "${1}".', search_no_results: 'Keine Ergebnisse für "${1}".',
search_scope_space: 'Nur in ${1}', search_scope_space: '${1}',
search_scope_all: 'Alle Inhalte', search_scope_all: 'Alle Inhalte',
search_ask: 'Fragen "${1}"', search_ask: 'Fragen "${1}"',
search_ask_description: 'Finden Sie die Antwort mit AI',
search_ask_sources: 'Quellen', search_ask_sources: 'Quellen',
search_ask_sources_no_answer: 'Verwandte Seiten', search_ask_sources_no_answer: 'Verwandte Seiten',
search_ask_no_answer: search_ask_no_answer:
+4 -3
View File
@@ -6,13 +6,14 @@ export const en = {
switch_to_light_theme: 'Switch to light theme', switch_to_light_theme: 'Switch to light theme',
switch_to_system_theme: 'Switch to system theme', switch_to_system_theme: 'Switch to system theme',
search: 'Search', search: 'Search',
search_or_ask: 'Ask or Search', search_or_ask: 'Ask or search',
search_input_placeholder: 'Search content', search_input_placeholder: 'Search content',
search_ask_input_placeholder: 'Search content or ask a question', search_ask_input_placeholder: 'Search content or ask a question',
search_no_results: 'No results for "${1}".', search_no_results: 'No results for "${1}".',
search_scope_space: 'Only in ${1}', search_scope_space: '${1}',
search_scope_all: 'All the content', search_scope_all: 'All content',
search_ask: 'Ask "${1}"', search_ask: 'Ask "${1}"',
search_ask_description: 'Find the answer with AI',
search_ask_sources: 'Sources', search_ask_sources: 'Sources',
search_ask_sources_no_answer: 'Related pages', search_ask_sources_no_answer: 'Related pages',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const es: TranslationLanguage = {
search_input_placeholder: 'Buscar contenido', search_input_placeholder: 'Buscar contenido',
search_ask_input_placeholder: 'Buscar contenido o hacer una pregunta', search_ask_input_placeholder: 'Buscar contenido o hacer una pregunta',
search_no_results: 'No hay resultados para "${1}".', search_no_results: 'No hay resultados para "${1}".',
search_scope_space: 'Solo en ${1}', search_scope_space: '${1}',
search_scope_all: 'Todo el contenido', search_scope_all: 'Todo el contenido',
search_ask: 'Preguntar "${1}"', search_ask: 'Preguntar "${1}"',
search_ask_description: 'Encuentra la respuesta con IA',
search_ask_sources: 'Fuentes', search_ask_sources: 'Fuentes',
search_ask_sources_no_answer: 'Páginas relacionadas', search_ask_sources_no_answer: 'Páginas relacionadas',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const fr: TranslationLanguage = {
search_input_placeholder: 'Rechercher le contenu', search_input_placeholder: 'Rechercher le contenu',
search_ask_input_placeholder: 'Rechercher du contenu ou poser une question', search_ask_input_placeholder: 'Rechercher du contenu ou poser une question',
search_no_results: 'Aucun résultat pour "${1}".', search_no_results: 'Aucun résultat pour "${1}".',
search_scope_space: 'Uniquement dans ${1}', search_scope_space: '${1}',
search_scope_all: 'Tout le contenu', search_scope_all: 'Tout le contenu',
search_ask: 'Demander "${1}"', search_ask: 'Demander "${1}"',
search_ask_description: "Trouvez la réponse avec l'IA",
search_ask_sources: 'Sources', search_ask_sources: 'Sources',
search_ask_sources_no_answer: 'Pages connexes', search_ask_sources_no_answer: 'Pages connexes',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const ja: TranslationLanguage = {
search_input_placeholder: 'コンテンツを検索', search_input_placeholder: 'コンテンツを検索',
search_ask_input_placeholder: 'コンテンツを検索するか質問をする', search_ask_input_placeholder: 'コンテンツを検索するか質問をする',
search_no_results: '"${1}" の結果はありません。', search_no_results: '"${1}" の結果はありません。',
search_scope_space: '${1}内のみ', search_scope_space: '${1}',
search_scope_all: '全てのコンテンツ', search_scope_all: '全てのコンテンツ',
search_ask: '"${1}" を質問する', search_ask: '"${1}" を質問する',
search_ask_description: 'AIで答えを見つける',
search_ask_sources: '情報源', search_ask_sources: '情報源',
search_ask_sources_no_answer: '関連ページ', search_ask_sources_no_answer: '関連ページ',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const nl: TranslationLanguage = {
search_input_placeholder: 'Zoek inhoud', search_input_placeholder: 'Zoek inhoud',
search_ask_input_placeholder: 'Zoek inhoud of stel een vraag', search_ask_input_placeholder: 'Zoek inhoud of stel een vraag',
search_no_results: 'Geen resultaten voor "${1}".', search_no_results: 'Geen resultaten voor "${1}".',
search_scope_space: 'Alleen in ${1}', search_scope_space: '${1}',
search_scope_all: 'Alle inhoud', search_scope_all: 'Alle inhoud',
search_ask: 'Vraag "${1}"', search_ask: 'Vraag "${1}"',
search_ask_description: 'Vind het antwoord met AI',
search_ask_sources: 'Bronnen', search_ask_sources: 'Bronnen',
search_ask_sources_no_answer: 'Gerelateerde paginas', search_ask_sources_no_answer: 'Gerelateerde paginas',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const no: TranslationLanguage = {
search_input_placeholder: 'Søk i innhold', search_input_placeholder: 'Søk i innhold',
search_ask_input_placeholder: 'Søk i innhold eller still et spørsmål', search_ask_input_placeholder: 'Søk i innhold eller still et spørsmål',
search_no_results: 'Ingen resultater for "${1}".', search_no_results: 'Ingen resultater for "${1}".',
search_scope_space: 'Kun i ${1}', search_scope_space: '${1}',
search_scope_all: 'Alt innhold', search_scope_all: 'Alt innhold',
search_ask: 'Spør "${1}"', search_ask: 'Spør "${1}"',
search_ask_description: 'Finn svaret med AI',
search_ask_sources: 'Kilder', search_ask_sources: 'Kilder',
search_ask_sources_no_answer: 'Relaterte sider', search_ask_sources_no_answer: 'Relaterte sider',
search_ask_no_answer: search_ask_no_answer:
@@ -10,9 +10,10 @@ export const pt_br = {
search_input_placeholder: 'Buscar conteúdo', search_input_placeholder: 'Buscar conteúdo',
search_ask_input_placeholder: 'Buscar conteúdo ou fazer uma pergunta', search_ask_input_placeholder: 'Buscar conteúdo ou fazer uma pergunta',
search_no_results: 'Sem resultados para "${1}".', search_no_results: 'Sem resultados para "${1}".',
search_scope_space: 'Somente em ${1}', search_scope_space: '${1}',
search_scope_all: 'Todo o conteúdo', search_scope_all: 'Todo o conteúdo',
search_ask: 'Perguntar "${1}"', search_ask: 'Perguntar "${1}"',
search_ask_description: 'Encontre a resposta com IA',
search_ask_sources: 'Fontes', search_ask_sources: 'Fontes',
search_ask_sources_no_answer: 'Páginas relacionadas', search_ask_sources_no_answer: 'Páginas relacionadas',
search_ask_no_answer: search_ask_no_answer:
+2 -1
View File
@@ -12,9 +12,10 @@ export const zh: TranslationLanguage = {
search_input_placeholder: '搜索内容', search_input_placeholder: '搜索内容',
search_ask_input_placeholder: '搜索内容或提问', search_ask_input_placeholder: '搜索内容或提问',
search_no_results: '没有找到"${1}"的结果。', search_no_results: '没有找到"${1}"的结果。',
search_scope_space: '仅在${1}', search_scope_space: '${1}',
search_scope_all: '所有内容', search_scope_all: '所有内容',
search_ask: '询问"${1}"', search_ask: '询问"${1}"',
search_ask_description: '利用人工智能找到答案',
search_ask_sources: '来源', search_ask_sources: '来源',
search_ask_sources_no_answer: '相关页面', search_ask_sources_no_answer: '相关页面',
search_ask_no_answer: '无法找到您的问题的答案。您可以尝试改述问题或提供更具体的信息。', search_ask_no_answer: '无法找到您的问题的答案。您可以尝试改述问题或提供更具体的信息。',
+190 -263
View File
@@ -13,11 +13,15 @@ import {
RevisionFile, RevisionFile,
SiteCustomizationSettings, SiteCustomizationSettings,
RevisionReusableContent, RevisionReusableContent,
SiteSpace,
Space,
SiteSection,
PublishedSiteContent,
} from '@gitbook/api'; } from '@gitbook/api';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
import rison from 'rison'; import rison from 'rison';
import { DeepPartial } from 'ts-essentials'; import { assert, DeepPartial } from 'ts-essentials';
import { batch } from './async'; import { batch } from './async';
import { buildVersion } from './build'; import { buildVersion } from './build';
@@ -83,14 +87,30 @@ const cacheTtl_1day = {
ttl: 24 * 60 * 60, ttl: 24 * 60 * 60,
}; };
const apiSyncStorage = new AsyncLocalStorage<GitBookAPI>(); export type GitBookAPIContext = {
/**
* Instance of the GitBook API client.
*/
client: GitBookAPI;
/**
* Context ID representing a hash of the visitor's attributes/assertions that are
* included in the claims property of the content API JWT token.
*
* It serves as a suffix for the cache key to ensure that the content cache is invalidated
* when these attributees/assertions change.
*/
contextId: string | undefined;
};
const apiSyncStorage = new AsyncLocalStorage<GitBookAPIContext>();
export const DEFAULT_API_ENDPOINT = process.env.GITBOOK_API_URL ?? 'https://api.gitbook.com'; export const DEFAULT_API_ENDPOINT = process.env.GITBOOK_API_URL ?? 'https://api.gitbook.com';
/** /**
* Create a new API client with a token. * Create a new API client with a token.
*/ */
export function apiWithToken(apiToken: string): GitBookAPI { export function apiWithToken(apiToken: string, contextId: string | undefined): GitBookAPIContext {
const headersList = headers(); const headersList = headers();
const apiEndpoint = headersList.get('x-gitbook-api') ?? DEFAULT_API_ENDPOINT; const apiEndpoint = headersList.get('x-gitbook-api') ?? DEFAULT_API_ENDPOINT;
@@ -100,13 +120,13 @@ export function apiWithToken(apiToken: string): GitBookAPI {
userAgent: userAgent(), userAgent: userAgent(),
}); });
return gitbook; return { client: gitbook, contextId };
} }
/** /**
* Create an API client for the current request. * Create an API client for the current request.
*/ */
export function api(): GitBookAPI { export function api(): GitBookAPIContext {
const existing = apiSyncStorage.getStore(); const existing = apiSyncStorage.getStore();
if (existing) { if (existing) {
return existing; return existing;
@@ -114,6 +134,7 @@ export function api(): GitBookAPI {
const headersList = headers(); const headersList = headers();
const apiToken = headersList.get('x-gitbook-token'); const apiToken = headersList.get('x-gitbook-token');
const contextId = headersList.get('x-gitbook-token-context') ?? undefined;
if (!apiToken) { if (!apiToken) {
throw new Error( throw new Error(
@@ -121,32 +142,20 @@ export function api(): GitBookAPI {
); );
} }
return apiWithToken(apiToken); return apiWithToken(apiToken, contextId);
} }
/** /**
* Use an API client for an async function. * Use an API client for an async function.
*/ */
export function withAPI<T>(client: GitBookAPI, fn: () => Promise<T>): Promise<T> { export function withAPI<T>(client: GitBookAPIContext, fn: () => Promise<T>): Promise<T> {
return apiSyncStorage.run(client, fn); return apiSyncStorage.run(client, fn);
} }
// FIXME: Fix @gitbook/api types for PublishedSiteContentLookup type SpaceContentLookup = Pick<
type SpaceContentLookup = { PublishedSiteContent,
kind: 'space'; 'space' | 'changeRequest' | 'revision' | 'pathname' | 'basePath' | 'apiToken'
/** ID of the space matching. */ > & { kind: 'space' };
space: string;
/** Identifier of the change request being previewed in this URL. */
changeRequest?: string;
/** Identifier of the revision being previewed in this URL. */
revision?: string;
/** Path of the content relative to the space */
pathname: string;
/** Prefix of the path in the URL dedicated to the space */
basePath: string;
/** Short-lived API token to fetch content related to the space in the context of the URL. */
apiToken: string;
};
export type PublishedContentWithCache = export type PublishedContentWithCache =
| ((SpaceContentLookup | PublishedSiteContentLookup) & { | ((SpaceContentLookup | PublishedSiteContentLookup) & {
@@ -172,7 +181,7 @@ export const getUserById = cache({
}), }),
get: async (userId: string, options: CacheFunctionOptions) => { get: async (userId: string, options: CacheFunctionOptions) => {
try { try {
const response = await api().users.getUserById(userId, { const response = await api().client.users.getUserById(userId, {
signal: options.signal, signal: options.signal,
...noCacheFetchOptions, ...noCacheFetchOptions,
}); });
@@ -208,7 +217,7 @@ export const getPublishedContentByUrl = cache({
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
try { try {
const response = await api().urls.getPublishedContentByUrl( const response = await api().client.urls.getPublishedContentByUrl(
{ {
url, url,
visitorAuthToken, visitorAuthToken,
@@ -257,7 +266,7 @@ export const getSpace = cache({
name: 'api.getSpace', name: 'api.getSpace',
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }), tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
get: async (spaceId: string, shareKey: string | undefined, options: CacheFunctionOptions) => { get: async (spaceId: string, shareKey: string | undefined, options: CacheFunctionOptions) => {
const response = await api().spaces.getSpaceById( const response = await api().client.spaces.getSpaceById(
spaceId, spaceId,
{ {
shareKey, shareKey,
@@ -281,7 +290,7 @@ export const getChangeRequest = cache({
tag: (spaceId, changeRequestId) => tag: (spaceId, changeRequestId) =>
getAPICacheTag({ tag: 'change-request', space: spaceId, changeRequest: changeRequestId }), getAPICacheTag({ tag: 'change-request', space: spaceId, changeRequest: changeRequestId }),
get: async (spaceId: string, changeRequestId: string, options: CacheFunctionOptions) => { get: async (spaceId: string, changeRequestId: string, options: CacheFunctionOptions) => {
const response = await api().spaces.getChangeRequestById(spaceId, changeRequestId, { const response = await api().client.spaces.getChangeRequestById(spaceId, changeRequestId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -309,13 +318,14 @@ export const getRevision = cache({
name: 'api.getRevision.v2', name: 'api.getRevision.v2',
tag: (spaceId, revisionId) => tag: (spaceId, revisionId) =>
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }), getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
spaceId: string, spaceId: string,
revisionId: string, revisionId: string,
fetchOptions: GetRevisionOptions, fetchOptions: GetRevisionOptions,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().spaces.getRevisionById( const response = await api().client.spaces.getRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -339,13 +349,14 @@ export const getRevisionPages = cache({
name: 'api.getRevisionPages.v4', name: 'api.getRevisionPages.v4',
tag: (spaceId, revisionId) => tag: (spaceId, revisionId) =>
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }), getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
spaceId: string, spaceId: string,
revisionId: string, revisionId: string,
fetchOptions: GetRevisionOptions, fetchOptions: GetRevisionOptions,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().spaces.listPagesInRevisionById( const response = await api().client.spaces.listPagesInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -372,6 +383,7 @@ export const getRevisionPageByPath = cache({
name: 'api.getRevisionPageByPath.v3', name: 'api.getRevisionPageByPath.v3',
tag: (spaceId, revisionId) => tag: (spaceId, revisionId) =>
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }), getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
spaceId: string, spaceId: string,
revisionId: string, revisionId: string,
@@ -381,7 +393,7 @@ export const getRevisionPageByPath = cache({
const encodedPath = encodeURIComponent(pagePath); const encodedPath = encodeURIComponent(pagePath);
try { try {
const response = await api().spaces.getPageInRevisionByPath( const response = await api().client.spaces.getPageInRevisionByPath(
spaceId, spaceId,
revisionId, revisionId,
encodedPath, encodedPath,
@@ -424,7 +436,7 @@ const getRevisionFileById = cache({
) => { ) => {
try { try {
const response = await (async () => { const response = await (async () => {
return api().spaces.getFileInRevisionById( return api().client.spaces.getFileInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
fileId, fileId,
@@ -453,6 +465,7 @@ const getRevisionReusableContentById = cache({
name: 'api.getRevisionReusableContentById.v1', name: 'api.getRevisionReusableContentById.v1',
tag: (spaceId, revisionId) => tag: (spaceId, revisionId) =>
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }), getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
spaceId: string, spaceId: string,
revisionId: string, revisionId: string,
@@ -461,7 +474,7 @@ const getRevisionReusableContentById = cache({
) => { ) => {
try { try {
const response = await (async () => { const response = await (async () => {
return api().spaces.getReusableContentInRevisionById( return api().client.spaces.getReusableContentInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
reusableContentId, reusableContentId,
@@ -497,7 +510,7 @@ const getRevisionAllFiles = cache({
get: async (spaceId: string, revisionId: string, options: CacheFunctionOptions) => { get: async (spaceId: string, revisionId: string, options: CacheFunctionOptions) => {
const response = await getAll( const response = await getAll(
(params) => (params) =>
api().spaces.listFilesInRevisionById( api().client.spaces.listFilesInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -608,8 +621,9 @@ export const getDocument = cache({
name: 'api.getDocument.v2', name: 'api.getDocument.v2',
tag: (spaceId, documentId) => tag: (spaceId, documentId) =>
getAPICacheTag({ tag: 'document', space: spaceId, document: documentId }), getAPICacheTag({ tag: 'document', space: spaceId, document: documentId }),
getKeySuffix: () => api().contextId,
get: async (spaceId: string, documentId: string, options: CacheFunctionOptions) => { get: async (spaceId: string, documentId: string, options: CacheFunctionOptions) => {
const response = await api().spaces.getDocumentById( const response = await api().client.spaces.getDocumentById(
spaceId, spaceId,
documentId, documentId,
{ {
@@ -629,91 +643,58 @@ export const getDocument = cache({
}); });
/** /**
* Get the customization settings for a site-space from the API. * Resolve a site redirect by its source path.
*/ */
const getSiteSpaceCustomizationFromAPI = cache({ export const getSiteRedirectBySource = cache({
name: 'api.getSiteSpaceCustomizationById', name: 'api.getSiteRedirectBySource',
tag: (organizationId, siteId, siteSpaceId) => getAPICacheTag({ tag: 'site', site: siteId }), tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
organizationId: string, args: {
siteId: string, organizationId: string;
siteSpaceId: string, siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
source: string;
},
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().orgs.getSiteSpaceCustomizationById( try {
organizationId, const response = await api().client.orgs.getSiteRedirectBySource(
siteId, args.organizationId,
siteSpaceId, args.siteId,
{}, {
{ shareKey: args.siteShareKey,
signal: options.signal, source: args.source,
...noCacheFetchOptions, },
}, {
); ...noCacheFetchOptions,
return cacheResponse(response, { signal: options.signal,
revalidateBefore: 60 * 60, },
}); );
return cacheResponse(response, cacheTtl_1day);
} catch (error) {
if ((error as GitBookAPIError).code === 404) {
return {
data: null,
...cacheTtl_1day,
};
}
throw error;
}
}, },
}); });
/**
* Get the customization settings for a site from the API.
*/
const getSiteCustomizationFromAPI = cache({
name: 'api.getSiteCustomizationById',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.getSiteCustomizationById(
organizationId,
siteId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
},
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
},
});
/**
* Get the customization settings for a site space from the API.
*/
async function getSiteSpaceCustomization(args: {
organizationId: string;
siteId: string;
siteSpaceId: string;
}): Promise<SiteCustomizationSettings> {
const raw = await getSiteSpaceCustomizationFromAPI(
args.organizationId,
args.siteId,
args.siteSpaceId,
);
return mergeCustomizationWithExtend(raw);
}
/**
* Get the customization settings for a site space from the API.
*/
async function getSiteCustomization(args: {
organizationId: string;
siteId: string;
}): Promise<SiteCustomizationSettings> {
const raw = await getSiteCustomizationFromAPI(args.organizationId, args.siteId);
return mergeCustomizationWithExtend(raw);
}
/** /**
* Get the infos about a site by its ID. * Get the infos about a site by its ID.
*/ */
export const getSite = cache({ export const getSite = cache({
name: 'api.getSite', name: 'api.getSite',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }), tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
getKeySuffix: () => api().contextId,
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => { get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.getSiteById(organizationId, siteId, { const response = await api().client.orgs.getSiteById(organizationId, siteId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -724,59 +705,25 @@ export const getSite = cache({
}); });
/** /**
* List all the site-spaces variants published in a site. * Get the published content site data for a site's published experience
*/ */
export const getSiteSpaces = cache({ export const getPublishedContentSite = cache({
name: 'api.getSiteSpaces', name: 'api.getPublishedContentSite',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }), tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
args: { args: {
organizationId: string; organizationId: string;
siteId: string; siteId: string /** Site share key that can be used as context to resolve site space published urls */;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined; siteShareKey: string | undefined;
}, },
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await getAll((params) => const response = await api().client.orgs.getPublishedContentSite(
api().orgs.listSiteSpaces(
args.organizationId,
args.siteId,
{
...params,
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}),
},
{
...noCacheFetchOptions,
signal: options.signal,
},
),
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
data: response.data.items.map((siteSpace) => siteSpace),
});
},
});
export const getSiteStructure = cache({
name: 'api.getSiteStructure',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (
args: {
organizationId: string;
siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
},
options: CacheFunctionOptions,
) => {
const response = await api().orgs.getSiteStructure(
args.organizationId, args.organizationId,
args.siteId, args.siteId,
{ {
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}), shareKey: args.siteShareKey,
}, },
{ {
...noCacheFetchOptions, ...noCacheFetchOptions,
@@ -785,89 +732,96 @@ export const getSiteStructure = cache({
); );
return cacheResponse(response, { return cacheResponse(response, {
revalidateBefore: 60 * 60, revalidateBefore: 60 * 60,
data: response.data,
}); });
}, },
}); });
/** export type SectionsList = { list: SiteSection[]; section: SiteSection; index: number };
* List the scripts to load for the site.
*/
export const getSiteIntegrationScripts = cache({
name: 'api.getSiteIntegrationScripts',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.listSiteIntegrationScripts(organizationId, siteId, {
...noCacheFetchOptions,
signal: options.signal,
});
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
},
});
/** /**
* Fetch all the data to render the current site at once. * Parse the site spaces into a list of spaces with their title and urls.
*/ */
export async function getSiteData(pointer: SiteContentPointer) { export function parseSpacesFromSiteSpaces(siteSpaces: SiteSpace[]) {
const [{ space, pages, contentTarget }, { customization, scripts }] = await Promise.all([ const spaces: Record<string, Space> = {};
getSpaceContentData(pointer, pointer.siteShareKey), siteSpaces.forEach((siteSpace) => {
getSiteLayoutData(pointer), spaces[siteSpace.space.id] = {
]); ...siteSpace.space,
title: siteSpace.title ?? siteSpace.space.title,
urls: {
...siteSpace.space.urls,
published: siteSpace.urls.published,
},
};
});
return Object.values(spaces);
}
return { function parseSiteSectionsList(siteSectionId: string, sections: SiteSection[]) {
space, const section = sections.find((section) => section.id === siteSectionId);
pages, assert(section, 'A section must be defined when there are multiple sections');
contentTarget, return { list: sections, section, index: sections.indexOf(section) } satisfies SectionsList;
customization,
scripts,
};
} }
/** /**
* Fetch all the layout data about the current site at once. * This function fetches the published content site data to render the published
* experience for the site (structure, customizations, scripts etc)
*/ */
export async function getSiteLayoutData(args: { export async function getSiteData(
organizationId: string; pointer: Pick<
siteId: string; SiteContentPointer,
siteSpaceId: string | undefined; 'organizationId' | 'siteId' | 'siteSectionId' | 'siteSpaceId' | 'siteShareKey'
}) { >,
const [customization, scripts] = await Promise.all([ ) {
getCurrentSiteCustomization(args), const {
getSiteIntegrationScripts(args.organizationId, args.siteId), site: orgSite,
]); structure: siteStructure,
customizations,
scripts,
} = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
const siteSections =
siteStructure.type === 'sections' && siteStructure.structure
? siteStructure.structure
: null;
const siteSpaces =
siteStructure.type === 'siteSpaces' && siteStructure.structure
? parseSpacesFromSiteSpaces(siteStructure.structure)
: null;
// override the title with the customization title
const site = {
...orgSite,
...(customizations.site?.title ? { title: customizations.site.title } : {}),
};
const sections =
pointer.siteSectionId && siteSections
? parseSiteSectionsList(pointer.siteSectionId, siteSections)
: null;
const spaces =
siteSpaces ?? (sections ? parseSpacesFromSiteSpaces(sections.section.siteSpaces) : []);
const customization = getActiveCustomizationSettings(
pointer.siteSpaceId ? customizations.siteSpaces[pointer.siteSpaceId] : customizations.site,
);
return { return {
customization, customization,
site,
structure: siteStructure,
sections,
spaces,
scripts, scripts,
}; };
} }
/**
* Get the customization settings for the current site from the API.
*/
export async function getCurrentSiteCustomization(args: {
organizationId: string;
siteId: string;
siteSpaceId: string | undefined;
}): Promise<SiteCustomizationSettings> {
return args.siteSpaceId
? getSiteSpaceCustomization({
organizationId: args.organizationId,
siteId: args.siteId,
siteSpaceId: args.siteSpaceId,
})
: getSiteCustomization({
organizationId: args.organizationId,
siteId: args.siteId,
});
}
/** /**
* Get the customization settings for a space from the API. * Get the customization settings for a space from the API.
*/ */
export async function getSpaceCustomization(spaceId: string): Promise<CustomizationSettings> { export function getSpaceCustomization(spaceId: string): { customization: CustomizationSettings } {
const headersList = headers(); const headersList = headers();
const raw = defaultCustomizationForSpace(); const raw = defaultCustomizationForSpace();
@@ -875,7 +829,7 @@ export async function getSpaceCustomization(spaceId: string): Promise<Customizat
if (extend) { if (extend) {
try { try {
const parsed = rison.decode_object<Partial<CustomizationSettings>>(extend); const parsed = rison.decode_object<Partial<CustomizationSettings>>(extend);
return { ...raw, ...parsed }; return { customization: { ...raw, ...parsed } };
} catch (error) { } catch (error) {
console.error( console.error(
`Failed to parse x-gitbook-customization header (ignored): ${ `Failed to parse x-gitbook-customization header (ignored): ${
@@ -885,7 +839,9 @@ export async function getSpaceCustomization(spaceId: string): Promise<Customizat
} }
} }
return raw; return {
customization: raw,
};
} }
/** /**
@@ -895,7 +851,7 @@ export const getCollection = cache({
name: 'api.getCollection', name: 'api.getCollection',
tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }), tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }),
get: async (collectionId: string, options: CacheFunctionOptions) => { get: async (collectionId: string, options: CacheFunctionOptions) => {
const response = await api().collections.getCollectionById(collectionId, { const response = await api().client.collections.getCollectionById(collectionId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -913,7 +869,7 @@ export const getCollectionSpaces = cache({
tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }), tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }),
get: async (collectionId: string, options: CacheFunctionOptions) => { get: async (collectionId: string, options: CacheFunctionOptions) => {
const response = await getAll((params) => const response = await getAll((params) =>
api().collections.listSpacesInCollectionById(collectionId, params, { api().client.collections.listSpacesInCollectionById(collectionId, params, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}), }),
@@ -946,13 +902,11 @@ export async function getSpaceContentData(
spaceId: pointer.spaceId, spaceId: pointer.spaceId,
revisionId: changeRequest?.revision ?? pointer.revisionId ?? space.revision, revisionId: changeRequest?.revision ?? pointer.revisionId ?? space.revision,
}; };
const [pages] = await Promise.all([ const pages = await getRevisionPages(space.id, contentTarget.revisionId, {
getRevisionPages(space.id, contentTarget.revisionId, { // We only care about the Git metadata when the Git sync is enabled
// We only care about the Git metadata when the Git sync is enabled // otherwise we can optimize performance by not fetching it
// otherwise we can optimize performance by not fetching it metadata: !!space.gitSync,
metadata: !!space.gitSync, });
}),
]);
return { return {
space, space,
@@ -967,6 +921,7 @@ export async function getSpaceContentData(
export const searchSpaceContent = cache({ export const searchSpaceContent = cache({
name: 'api.searchSpaceContent', name: 'api.searchSpaceContent',
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }), tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
spaceId: string, spaceId: string,
/** The revision ID is used as a cache bust key, to avoid revalidating lot of cache entries by tags */ /** The revision ID is used as a cache bust key, to avoid revalidating lot of cache entries by tags */
@@ -974,7 +929,7 @@ export const searchSpaceContent = cache({
query: string, query: string,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().spaces.searchSpaceContent( const response = await api().client.spaces.searchSpaceContent(
spaceId, spaceId,
{ query }, { query },
{ {
@@ -992,8 +947,9 @@ export const searchSpaceContent = cache({
export const searchParentContent = cache({ export const searchParentContent = cache({
name: 'api.searchParentContent', name: 'api.searchParentContent',
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }), tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
getKeySuffix: () => api().contextId,
get: async (parentId: string, query: string, options: CacheFunctionOptions) => { get: async (parentId: string, query: string, options: CacheFunctionOptions) => {
const response = await api().search.searchContent( const response = await api().client.search.searchContent(
{ query }, { query },
{ {
...noCacheFetchOptions, ...noCacheFetchOptions,
@@ -1012,6 +968,7 @@ export const searchParentContent = cache({
export const searchSiteContent = cache({ export const searchSiteContent = cache({
name: 'api.searchSiteContent', name: 'api.searchSiteContent',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }), tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
getKeySuffix: () => api().contextId,
get: async ( get: async (
organizationId: string, organizationId: string,
siteId: string, siteId: string,
@@ -1024,7 +981,7 @@ export const searchSiteContent = cache({
cacheBust?: string, cacheBust?: string,
options?: CacheFunctionOptions, options?: CacheFunctionOptions,
) => { ) => {
const response = await api().orgs.searchSiteContent( const response = await api().client.orgs.searchSiteContent(
organizationId, organizationId,
siteId, siteId,
{ {
@@ -1051,7 +1008,7 @@ export const getRecommendedQuestionsInSpace = cache({
name: 'api.getRecommendedQuestionsInSpace', name: 'api.getRecommendedQuestionsInSpace',
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }), tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
get: async (spaceId: string, options: CacheFunctionOptions) => { get: async (spaceId: string, options: CacheFunctionOptions) => {
const response = await api().spaces.getRecommendedQuestionsInSpace(spaceId, { const response = await api().client.spaces.getRecommendedQuestionsInSpace(spaceId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -1070,7 +1027,7 @@ export const renderIntegrationUi = cache({
request: RequestRenderIntegrationUI, request: RequestRenderIntegrationUI,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().integrations.renderIntegrationUiWithPost( const response = await api().client.integrations.renderIntegrationUiWithPost(
integrationName, integrationName,
request, request,
{ {
@@ -1089,7 +1046,7 @@ export const renderIntegrationUi = cache({
export const getEmbedByUrl = cache({ export const getEmbedByUrl = cache({
name: 'api.getEmbedByUrl', name: 'api.getEmbedByUrl',
get: async (url: string, options: CacheFunctionOptions) => { get: async (url: string, options: CacheFunctionOptions) => {
const response = await api().urls.getEmbedByUrl( const response = await api().client.urls.getEmbedByUrl(
{ url }, { url },
{ {
...noCacheFetchOptions, ...noCacheFetchOptions,
@@ -1107,7 +1064,7 @@ export const getEmbedByUrlInSpace = cache({
name: 'api.getEmbedByUrlInSpace', name: 'api.getEmbedByUrlInSpace',
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }), tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
get: async (spaceId: string, url: string, options: CacheFunctionOptions) => { get: async (spaceId: string, url: string, options: CacheFunctionOptions) => {
const response = await api().spaces.getEmbedByUrlInSpace( const response = await api().client.spaces.getEmbedByUrlInSpace(
spaceId, spaceId,
{ url }, { url },
{ {
@@ -1275,19 +1232,19 @@ async function getAll<T, E>(
} }
/** /**
* Merge the customization settings with the ones passed in the x-gitbook-customization header if present. * Selects the customization settings from the x-gitbook-customization header if present,
* otherwise returns the original API-provided settings.
*/ */
function mergeCustomizationWithExtend<T extends SiteCustomizationSettings | CustomizationSettings>( function getActiveCustomizationSettings(
raw: T, settings: SiteCustomizationSettings,
) { ): SiteCustomizationSettings {
const headersList = headers(); const headersList = headers();
const extend = headersList.get('x-gitbook-customization'); const extend = headersList.get('x-gitbook-customization');
if (extend) { if (extend) {
try { try {
const parsed = rison.decode_object<DeepPartial<T>>(extend); const parsedSettings = rison.decode_object<SiteCustomizationSettings>(extend);
// Merge objects and some properties deep return parsedSettings;
return mergeDeepPlainObject(raw, parsed, ['styling', 'themes']);
} catch (error) { } catch (error) {
console.error( console.error(
`Failed to parse x-gitbook-customization header (ignored): ${ `Failed to parse x-gitbook-customization header (ignored): ${
@@ -1297,35 +1254,5 @@ function mergeCustomizationWithExtend<T extends SiteCustomizationSettings | Cust
} }
} }
return raw; return settings;
}
function mergeDeepPlainObject<T>(target: T, source: DeepPartial<T>, keys: Array<keyof T>): T {
if (typeof target !== 'object' || target === null) {
return target;
}
const result = { ...target };
for (const key in source) {
const value = source[key];
if (value === undefined) {
continue;
}
if (
typeof value === 'object' &&
!Array.isArray(value) &&
value !== null &&
keys.includes(key as keyof T)
) {
// @ts-ignore
result[key] = mergeDeepPlainObject(target[key] ?? {}, value, []);
} else {
// @ts-ignore
result[key] = value;
}
}
return result;
} }
+79 -2
View File
@@ -1,6 +1,7 @@
import { Mock, beforeEach, describe, expect, it, mock } from 'bun:test'; import { beforeEach, describe, expect, it, Mock, mock } from 'bun:test';
import hash from 'object-hash';
import { CacheFunction, CacheFunctionOptions, cache } from './cache'; import { CacheDefinition, CacheFunction, CacheFunctionOptions, cache } from './cache';
describe('cache', () => { describe('cache', () => {
const impl = mock((arg: string) => 'test-' + arg); const impl = mock((arg: string) => 'test-' + arg);
@@ -69,3 +70,79 @@ describe('cache', () => {
expect(impl).toHaveBeenCalledTimes(2); expect(impl).toHaveBeenCalledTimes(2);
}); });
}); });
describe('cache with suffix key', () => {
const impl = mock((arg: string) => 'test-' + arg);
const getKeySuffixImpl: Mock<NonNullable<CacheDefinition<[string], string>['getKeySuffix']>> =
mock(() => hash({ test: 1 }));
let fn: CacheFunction<[string], string>;
let testId = 0;
let getTtl: () => number;
beforeEach(() => {
impl.mockClear();
testId += 1;
getTtl = () => 1000;
fn = cache({
name: `cache-with-suffix-${testId}`,
getKeySuffix: getKeySuffixImpl,
tag: (arg) => 'test',
get: async (arg: string, options: CacheFunctionOptions) => {
await new Promise((resolve) => setTimeout(resolve, 20));
return {
data: impl(arg),
ttl: getTtl(),
};
},
});
});
it('should execute when the key suffix changes even if the args do not change', async () => {
const result = await Promise.all([fn('a'), fn('b')]);
expect(result).toEqual(['test-a', 'test-b']);
expect(impl).toHaveBeenCalled();
expect(impl).toHaveBeenCalledTimes(2);
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(2);
getKeySuffixImpl.mockImplementation(() => hash({ test: 2 }));
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(3);
});
it('should preserve behaviour even when the returned key suffix is undefined', async () => {
// Start with the returned suffix being undefined
getKeySuffixImpl.mockImplementation(() => undefined);
const result = await fn('a');
expect(result).toEqual('test-a');
expect(impl).toHaveBeenCalled();
expect(impl).toHaveBeenCalledTimes(1);
// The returned suffix changes so we should get the value computed by the function
getKeySuffixImpl.mockImplementation(() => hash({ test: 1 }));
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(2);
// The returned suffix is undefined again so we should get the value from a previous cache entry
getKeySuffixImpl.mockImplementation(() => undefined);
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(2);
// The returned suffix goes back to a previous hash so we should the value from a previous cache entry
getKeySuffixImpl.mockImplementation(() => hash({ test: 1 }));
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(2);
});
});
+16 -5
View File
@@ -55,6 +55,9 @@ export interface CacheDefinition<Args extends any[], Result> {
/** Filter the arguments that should be taken into consideration for the cache key */ /** Filter the arguments that should be taken into consideration for the cache key */
getKeyArgs?: (args: Args) => any[]; getKeyArgs?: (args: Args) => any[];
/** Returns a precomputed hash that is used alongside arguments to generate the cache key */
getKeySuffix?: () => string | undefined;
/** Default ttl (in seconds) */ /** Default ttl (in seconds) */
defaultTtl?: number; defaultTtl?: number;
@@ -222,7 +225,8 @@ export function cache<Args extends any[], Result>(
const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs); const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs);
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args; const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
const key = getCacheKey(cacheDef.name, cacheArgs); const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
return await trace( return await trace(
{ {
@@ -239,7 +243,8 @@ export function cache<Args extends any[], Result>(
cacheFn.revalidate = async (...rawArgs: Args | [...Args, CacheFunctionOptions]) => { cacheFn.revalidate = async (...rawArgs: Args | [...Args, CacheFunctionOptions]) => {
const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs); const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs);
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args; const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
const key = getCacheKey(cacheDef.name, cacheArgs); const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
const result = await revalidate(key, signal, ...args); const result = await revalidate(key, signal, ...args);
return result.data; return result.data;
@@ -247,7 +252,8 @@ export function cache<Args extends any[], Result>(
cacheFn.hasInMemory = async (...args: Args) => { cacheFn.hasInMemory = async (...args: Args) => {
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args; const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
const key = getCacheKey(cacheDef.name, cacheArgs); const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
const tag = cacheDef.tag?.(...args); const tag = cacheDef.tag?.(...args);
const memoryEntry = await memoryCache.get({ key, tag }); const memoryEntry = await memoryCache.get({ key, tag });
@@ -275,8 +281,13 @@ export function getCache(name: string): CacheFunction<any[], any> | null {
/** /**
* Get a cache key for a function and its arguments. * Get a cache key for a function and its arguments.
*/ */
export function getCacheKey(fnName: string, args: any[]) { export function getCacheKey(fnName: string, args: any[], suffix: string | undefined) {
let innerKey = args.map((arg) => hashValue(arg)).join(','); const hashedArgs = args.map((arg) => hashValue(arg));
if (suffix) {
hashedArgs.push(suffix);
}
let innerKey = hashedArgs.join(',');
// Avoid crazy long keys, by fallbacking to a hash // Avoid crazy long keys, by fallbacking to a hash
if (innerKey.length > 400) { if (innerKey.length > 400) {
+1 -1
View File
@@ -54,7 +54,7 @@ export function getContentSecurityPolicy(scripts: SpaceIntegrationScript[], nonc
object-src 'none'; object-src 'none';
base-uri 'self' ${assetsDomain}; base-uri 'self' ${assetsDomain};
form-action 'self' ${assetsDomain}; form-action 'self' ${assetsDomain};
frame-ancestors https:; frame-ancestors https: ${process.env.NODE_ENV !== 'production' ? 'http:' : ''};
`; `;
const result = scripts const result = scripts

Some files were not shown because too many files have changed in this diff Show More