Compare commits

..

1 Commits

Author SHA1 Message Date
Valentino Hudhra 81af6bb077 Replace header link API type 2024-12-06 10:51:39 +01:00
97 changed files with 1043 additions and 2152 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix an issue with the cookie banner buttons being non responsive
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/cache-do': patch
---
Disable cloudflare observability in production
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update styling of search+ask modal
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix a regression in variant drop-down caused by missing z-index.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add scroll margin to the top when there are sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Smoother tab transition for sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the active site section indicator appeared above any dropdowns.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Don't adjust fallback font for mono font.
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Fixed scalar api client routing
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Optimize performances by using new API endpoint for fetching site data.
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Bump @scalar/api-client-react version
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Support Integers in Response example
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Restyle hint blocks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix security issue with image resizing that could be used for phishing
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
bumped the scalar api client dependency
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Bumped scalar api client pacakge
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the space dropdown was shown under the site sections in Safari.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix - whitespace added to site section tabs with icons.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add icons to sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
style: adds missing scalar css variables
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the space dropdown could appear behind the header.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix the styling of site section tabs on smaller screens.
+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@v4 uses: actions/cache@v3
id: playwright-cache id: playwright-cache
with: with:
path: '~/.cache/ms-playwright' path: '~/.cache/ms-playwright'
+10
View File
@@ -30,6 +30,16 @@ 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
BIN
View File
Binary file not shown.
-6
View File
@@ -1,11 +1,5 @@
# @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.1", "version": "0.1.0",
"dependencies": { "dependencies": {
"@msgpack/msgpack": "^3.0.0-beta2", "@msgpack/msgpack": "^3.0.0-beta2",
"lru_map": "^0.4.1" "lru_map": "^0.4.1"
-40
View File
@@ -1,45 +1,5 @@
# 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
+17 -364
View File
@@ -1,16 +1,11 @@
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';
@@ -39,18 +34,6 @@ 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' });
@@ -112,9 +95,7 @@ const testCases: TestsCase[] = [
name: 'Variants dropdown', name: 'Variants dropdown',
url: '', url: '',
run: async (page) => { run: async (page) => {
const spaceDrowpdown = page const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
.locator('[data-testid="space-dropdown-button"]')
.locator('visible=true');
await spaceDrowpdown.waitFor(); await spaceDrowpdown.waitFor();
}, },
}, },
@@ -130,9 +111,7 @@ 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 const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
.locator('[data-testid="space-dropdown-button"]')
.locator('visible=true');
await spaceDrowpdown.click(); await spaceDrowpdown.click();
const variantSelectionDropdown = page.locator( const variantSelectionDropdown = page.locator(
@@ -164,9 +143,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 const spaceDrowpdown = await page.waitForSelector(
.locator('[data-testid="space-dropdown-button"]') '[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
@@ -187,9 +166,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 const spaceDrowpdown = await page.waitForSelector(
.locator('[data-testid="space-dropdown-button"]') '[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
@@ -222,9 +201,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 const spaceDrowpdown = await page.waitForSelector(
.locator('[data-testid="space-dropdown-button"]') '[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
@@ -456,38 +435,30 @@ const testCases: TestsCase[] = [
{ {
name: 'Customization', name: 'Customization',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: allThemeModes.flatMap((theme) => [ tests: [
{ {
name: `Without header - Theme ${theme}`, name: 'Without header',
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 - Theme ${theme}`, name: 'With duotone icons',
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 - Theme ${theme}`, name: 'With header buttons',
url: getCustomizationURL({ url: getCustomizationURL({
header: { header: {
preset: CustomizationHeaderPreset.Default, preset: CustomizationHeaderPreset.Default,
@@ -504,101 +475,10 @@ 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',
@@ -934,178 +814,6 @@ 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) {
@@ -1140,62 +848,7 @@ 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);
+10 -11
View File
@@ -1,6 +1,6 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.5.0", "version": "0.4.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev", "dev": "env-cmd --silent -f ../../.env.local next dev",
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static" "clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
}, },
"dependencies": { "dependencies": {
"@gitbook/api": "^0.81.0", "@gitbook/api": "^0.80.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.3.1", "react": "^18",
"react-dom": "18.3.1", "react-dom": "^18",
"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",
@@ -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,12 +78,10 @@
"@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.13", "@types/react": "^18.3.3",
"@types/react-dom": "18.3.1", "@types/react-dom": "^18.3.0",
"@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",
@@ -91,7 +89,8 @@
"postcss": "^8", "postcss": "^8",
"psi": "^4.1.0", "psi": "^4.1.0",
"tailwindcss": "^3.4.0", "tailwindcss": "^3.4.0",
"ts-essentials": "^10.0.1", "typescript": "^5.5.3",
"typescript": "^5.5.3" "env-cmd": "^10.1.0",
"ts-essentials": "^10.0.1"
} }
} }
@@ -35,7 +35,6 @@ export default async function Page(props: {
customization, customization,
pages, pages,
page, page,
ancestors,
document, document,
} = await getPageDataWithFallback({ } = await getPageDataWithFallback({
pagePathParams: params, pagePathParams: params,
@@ -104,7 +103,6 @@ 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
@@ -152,8 +150,7 @@ export async function generateMetadata({
.join(' | '), .join(' | '),
description: page.description ?? '', description: page.description ?? '',
alternates: { alternates: {
// Trim trailing slashes in canonical URL to match the redirect behavior canonical: absoluteHref(getPagePath(pages, page), true),
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().client.endpoint); ReactDOM.preconnect(api().endpoint);
if (assetsDomain) { if (assetsDomain) {
ReactDOM.preconnect(assetsDomain); ReactDOM.preconnect(assetsDomain);
} }
@@ -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: 400, tokenizeMaxLineLength: 120,
}); });
let currentIndex = 0; let currentIndex = 0;
@@ -25,11 +25,7 @@ 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 <span className={tcls(size !== 'line' ? ['inline-flex', 'max-w-[300px]'] : null)}>
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)}
@@ -5,7 +5,7 @@
.light .scalar { .light .scalar {
--scalar-color-1: color-mix( --scalar-color-1: color-mix(
in srgb, in srgb,
rgb(var(--tint-color-300, 180 180 180)), rgb(var(--primary-base-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(--tint-color-800, 30 30 30)), rgb(var(--primary-base-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(--tint-color-800, 30 30 30)), rgb(var(--primary-base-800, 30 30 30)),
var(--scalar-background-1) 90% var(--scalar-background-1) 90%
); );
--scalar-background-accent: #007d9c1f; --scalar-background-accent: #007d9c1f;
@@ -66,7 +66,7 @@
.dark .scalar { .dark .scalar {
--scalar-color-1: color-mix( --scalar-color-1: color-mix(
in srgb, in srgb,
rgb(var(--tint-color-700, 70 70 70)), rgb(var(--primary-base-700, 70 70 70)),
rgb(var(--light-base, 255 255 255)) 100% rgb(var(--light-base, 255 255 255)) 100%
); );
--scalar-color-2: color-mix( --scalar-color-2: color-mix(
@@ -84,12 +84,12 @@
--scalar-background-1: rgb(var(--dark-base, 22 22 22)); --scalar-background-1: rgb(var(--dark-base, 22 22 22));
--scalar-background-2: color-mix( --scalar-background-2: color-mix(
in srgb, in srgb,
rgb(var(--tint-color-200, 200 200 200)), rgb(var(--primary-base-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(--tint-color-200, 200 200 200)), rgb(var(--primary-base-200, 200 200 200)),
var(--scalar-background-1) 88% var(--scalar-background-1) 88%
); );
--scalar-background-accent: #8ab4f81f; --scalar-background-accent: #8ab4f81f;
@@ -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 } from '@/components/primitives'; import { Checkbox, Emoji } 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,43 +1,44 @@
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 function RecordRow( export async function RecordRow(
props: TableViewProps<DocumentTableViewGrid> & { props: TableViewProps<DocumentTableViewGrid> & {
record: TableRecordKV; record: TableRecordKV;
autoSizedColumns: string[];
fixedColumns: string[];
}, },
) { ) {
const { view, autoSizedColumns, fixedColumns } = props; const { view } = props;
const columnsLengthThreshold = view.columns.length >= 7;
const tableTR = columnsLengthThreshold
? ['[&>*+*]:border-l', '[&>*]:px-4']
: ['[&>*+*]:border-l', '[&>*+*]:pl-4'];
return ( return (
<div className={styles.row} role="row"> <tr className={tcls(tableTR, 'border-dark/3', 'dark:border-light/2')}>
{view.columns.map((column) => { {view.columns.map((column) => {
const columnWidth = getColumnWidth({
column,
columnWidths: view.columnWidths,
autoSizedColumns,
fixedColumns,
});
return ( return (
<div <td
key={column} key={column}
role="cell" className={tcls(
className={styles.cell} 'align-middle',
style={{ 'min-w-[8rem]',
width: columnWidth, 'border-dark/2',
minWidth: columnWidth || '100px', 'py-3',
}} 'text-sm',
'lg:text-base',
'dark:border-light/2',
)}
> >
<RecordColumnValue {...props} column={column} /> <div className={tcls('pr-4 ', 'text-balance')}>
</div> <RecordColumnValue key={column} {...props} column={column} />
</div>
</td>
); );
})} })}
</div> </tr>
); );
} }
@@ -1,5 +1,4 @@
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';
@@ -8,113 +7,159 @@ 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;
/* Calculate how many columns are auto-sized vs fixed width */ const tableWrapper = columnsOverThreshold
const columnWidths = view.columnWidths; ? [
const autoSizedColumns = view.columns.filter((column) => !columnWidths?.[column]); // has over X columns
const fixedColumns = view.columns.filter((column) => columnWidths?.[column]); 'overflow-x-auto',
'overflow-y-hidden',
'mx-auto',
'rounded-md',
'border',
'border-dark/3',
'dark:border-light/2',
]
: ['overflow-x-auto', 'overflow-y-hidden', 'mx-auto'];
const tableWidth = autoSizedColumns.length > 0 ? 'w-full' : 'w-fit'; const tableTR = columnsOverThreshold
? ['[&>*+*]:border-l', '[&>*]:px-4']
: ['[&>*+*]:border-l', '[&>*+*]:px-4'];
/* Only show the header when configured and not empty */ const tableTH = columnsOverThreshold ? ['py-3'] : ['py-1', 'pt-0'];
// 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 className={tcls(style, styles.tableWrapper)}> <div
{/* Table */} className={`${tcls(style, 'relative', 'grid', tableWrapper, styles.progressContainer)}`}
<div role="table" className={tcls('flex', 'flex-col')}> >
{/* Header */} {/* ProgressScroller: */}
{withHeader && ( <div
<div className={`${styles.progressOpacitySharp} ${tcls(
role="rowgroup" 'grid',
className={tcls( 'items-center',
tableWidth, 'grid-area-1-1',
styles.rowGroup, 'w-[5rem]',
'straight-corners:rounded-none', 'h-full',
)} 'top-0',
> 'z-[1]',
<div role="row" className={tcls('flex', 'w-full')}> 'sticky',
'left-[calc(100%-5rem)]',
'pointer-events-none',
)}`}
>
<svg
className={`${styles.progressSvg} ${tcls(
'grid-area-1-1',
'relative',
'[strokeDasharray:_0_100]',
'z-[1]',
'w-7',
'mt-3',
'mr-3',
'self-start',
'justify-self-end',
'stroke-primary-600',
'shadow-1xs',
'bg-light',
'ring-1',
'ring-inset',
'rounded-full',
'ring-dark/2',
'dark:ring-light/2',
'dark:bg-dark',
'dark:stroke-primary-400',
)}`}
preserveAspectRatio="xMaxYMid meet"
width="100%"
viewBox="0 0 26 26"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle
cx="13"
className={`${styles.strokeOpacityProgressInverted}`}
cy="13"
r="12.5"
fill="none"
stroke="inherit"
strokeWidth="1.5"
pathLength="100"
strokeLinecap="round"
strokeOpacity={0}
/>
<path
strokeDasharray="none"
d="M12 10L15 13L12 16"
stroke="inherit"
fill="none"
strokeOpacity={0.64}
/>
</svg>
<div
className={`${styles.progressOpacity} ${tcls(
'bg-gradient-to-r',
'from-transparent',
'to-light',
'to-40%',
'grid-area-1-1',
'w-full',
'h-full',
'dark:from-transparent',
'dark:to-dark/10',
)}`}
></div>
</div>
{/* Table: */}
<table className={tcls('w-full', 'grid-area-1-1', 'table-auto')}>
{withHeader ? (
<thead>
<tr className={tcls(tableTR)}>
{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 (
<div <th
key={column} key={column}
role="columnheader"
className={tcls( className={tcls(
styles.columnHeader, tableTH,
'align-middle',
'text-balance',
'border-b',
'border-b-dark/5',
'text-left',
'text-xs',
'lg:text-base',
'dark:border-l-light/2',
'dark:border-b-light/4',
alignment === 'right' ? 'text-right' : null, alignment === 'right' ? 'text-right' : null,
alignment === 'center' ? 'text-center' : null, alignment === 'center' ? 'text-center' : null,
)} )}
style={{ style={columnWidth ? { width: columnWidth } : undefined}
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}
</div> </th>
); );
})} })}
</div> </tr>
</div> </thead>
)} ) : null}
<div <tbody className={tcls('[&>*+*]:border-t')}>
role="rowgroup" {records.map((record) => {
className={tcls('flex', 'flex-col', tableWidth, '[&>*+*]:border-t')} return <RecordRow key={record[0]} {...props} record={record} />;
> })}
{records.map((record) => ( </tbody>
<RecordRow </table>
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,59 +1,87 @@
/* Detect whether a scrollbar exists on the table */ /* Hide it on browsers (firefox / safari) that do not support it */
@keyframes detect-scroll { .progressOpacitySharp {
from, display: none;
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;
}
@@ -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 shrink min-w-0')}> <div className={tcls('group/dropdown', 'relative flex')}>
{button({ {button({
id: dropdownId, id: dropdownId,
tabIndex: 0, tabIndex: 0,
@@ -39,7 +39,7 @@ export function Dropdown<E extends HTMLElement>(props: {
aria-labelledby={dropdownId} aria-labelledby={dropdownId}
className={tcls( className={tcls(
'w-52', 'w-52',
'max-h-80', 'max-h-56',
'flex', 'flex',
'absolute', 'absolute',
'top-full', 'top-full',
@@ -111,38 +111,31 @@ 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 | null; href: string;
active?: boolean; active?: boolean;
className?: ClassValue;
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { children, active = false, href, className } = props; const { children, active = false, href } = 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 (
<div <Link
href={href}
prefetch={false}
className={tcls( className={tcls(
'text-xs px-3 py-1 font-medium text-dark/8 dark:text-light/8', 'flex',
className, 'flex-row',
'items-center',
'text-sm',
'px-3',
'py-1',
'rounded',
'straight-corners:rounded-sm',
active
? ['bg-primary/3', 'dark:bg-light/2', 'text-primary-600']
: ['hover:bg-dark/2', 'dark:hover:bg-light/2'],
)} )}
> >
{children} {children}
</div> </Link>
); );
} }
+85 -138
View File
@@ -15,7 +15,6 @@ 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.
*/ */
@@ -46,156 +45,104 @@ 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',
'text-sm', 'lg:z-10',
'bg-opacity-9', 'dark:shadow-light/1',
'dark:bg-opacity-9', `${isCustomizationDefault || !withTopHeader ? 'bg-light' : 'bg-header-background'}`,
'backdrop-blur-lg', `${
'contrast-more:bg-opacity-11', isCustomizationDefault || !withTopHeader
'contrast-more:dark:bg-opacity-11', ? 'dark:bg-dark'
: 'bg-header-background'
}`,
)} )}
> >
<div <div className={tcls('scroll-nojump')}>
className={tcls( <div
!isCustomizationDefault && className={tcls(
withTopHeader && [ 'gap-4',
'bg-header-background', 'grid',
'shadow-thinbottom', 'grid-flow-col',
'dark:shadow-light/2', 'auto-cols-[auto_auto_1fr_auto]',
], 'h-16',
)} 'items-center',
> 'align-center',
<div className={tcls('scroll-nojump')}> 'justify-between',
<div 'w-full',
className={tcls( CONTAINER_STYLE,
'gap-4', )}
'lg:gap-8', >
'flex', <HeaderLogo site={site} space={space} customization={customization} />
'h-16', <div className="z-20">
'items-center', {!hasSiteSections && isMultiVariants ? (
'justify-between', <SpacesDropdown space={space} spaces={spaces} />
'w-full', ) : null}
CONTAINER_STYLE, </div>
)} <HeaderLinks>
> {customization.header.links.map((link, index) => {
<div className="flex max-w-full shrink min-w-0 gap-2 lg:gap-4 justify-start items-center"> return (
<HeaderMobileMenu <HeaderLink
className={tcls( key={index}
'lg:hidden', link={link}
'-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 >
className={tcls( <Suspense fallback={null}>
'flex', <SearchButton
'md:min-w-56', style={
'grow-0', !isCustomizationDefault && withTopHeader
'shrink-0', ? [
'justify-self-end', 'bg-header-link/3',
)} 'shadow-sm',
> 'ring-header-link/3',
<Suspense fallback={null}> '[&>span]:!text-header-link/7',
<SearchButton '[&_svg]:text-header-link',
style={ 'contrast-more:bg-transparent',
!isCustomizationDefault && withTopHeader 'contrast-more:ring-header-link',
? [ 'contrast-more:[&>span]:!text-header-link',
'bg-header-link/2', 'dark:bg-header-link/3',
'dark:bg-header-link/2', 'dark:ring-header-link/3',
'hover:bg-header-link/3', '[&>span]:!text-header-link/7',
'dark:hover:bg-header-link/3', 'dark:[&_svg]:text-header-link',
'dark:contrast-more:bg-transparent',
'text-header-link/8', 'dark:contrast-more:ring-header-link',
'dark:text-header-link/8', 'dark:contrast-more:[&>span]:!text-header-link',
'hover:text-header-link', ]
'dark:hover:text-header-link', : null
}
'ring-header-link/4', >
'dark:ring-header-link/4', <span className={tcls('flex-1')}>
'hover:ring-header-link/5', {t(
'dark:hover:ring-header-link/5', getSpaceLanguage(customization),
customization.aiSearch.enabled ? 'search_or_ask' : 'search',
'[&_svg]:text-header-link/10', )}
'dark:[&_svg]:text-header-link/10', </span>
'[&_.shortcut]:text-header-link/8', </SearchButton>
'dark:[&_.shortcut]:text-header-link/8', </Suspense>
'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(
'scroll-nojump', 'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark mt-0.5',
'w-full',
// Handle long section tabs, particularly on smaller screens. // Handle long section tabs, particularly on smaller screens.
'overflow-x-auto hide-scroll', 'overflow-x-auto hide-scroll',
)} )}
@@ -33,7 +33,6 @@ export async function HeaderLink(props: {
if (link.links && link.links.length > 0) { if (link.links && link.links.length > 0) {
return ( return (
<Dropdown <Dropdown
className="shrink"
button={(buttonProps) => { button={(buttonProps) => {
if (!target) { if (!target) {
return ( return (
@@ -105,7 +104,7 @@ function HeaderItemButton(
linkStyle: 'button-secondary' | 'button-primary'; linkStyle: 'button-secondary' | 'button-primary';
}, },
) { ) {
const { linkStyle, headerPreset, title, href, isDropdown, ...rest } = props; const { linkStyle, headerPreset, title, href, ...rest } = props;
const variant = (() => { const variant = (() => {
switch (linkStyle) { switch (linkStyle) {
case 'button-secondary': case 'button-secondary':
@@ -148,9 +147,12 @@ function HeaderItemButton(
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) { function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
return tcls( return tcls(
'flex items-center shrink', 'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light', 'hover:text-header-link-400 dark:hover:text-light',
'min-w-0', 'truncate',
props.headerPreset === CustomizationHeaderPreset.Default props.headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8'] ? ['text-dark/8', 'dark:text-light/8']
@@ -162,7 +164,7 @@ function HeaderItemLink(props: HeaderLinkNavItemProps) {
const { headerPreset, title, isDropdown, href, ...rest } = props; const { headerPreset, title, isDropdown, href, ...rest } = props;
return ( return (
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}> <Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
<span className="truncate min-w-0">{title}</span> {title}
{isDropdown ? <DropdownChevron /> : null} {isDropdown ? <DropdownChevron /> : null}
</Link> </Link>
); );
@@ -1,5 +1,4 @@
import { import {
CustomizationContentLink,
CustomizationHeaderItem, CustomizationHeaderItem,
CustomizationHeaderPreset, CustomizationHeaderPreset,
CustomizationSettings, CustomizationSettings,
@@ -11,9 +10,10 @@ 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, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown'; import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
import styles from './headerLinks.module.css'; import styles from './headerLinks.module.css';
/** /**
* Dropdown menu for header links hidden at small screen size. * Dropdown menu for header links hidden at small screen size.
*/ */
@@ -31,22 +31,15 @@ export function HeaderLinkMore(props: {
const renderButton = () => ( const renderButton = () => (
<button <button
className={tcls( className={tcls(
isCustomizationDefault 'px-1',
? [ !isCustomizationDefault
'text-dark/8', ? ['text-header-link-500']
'dark:text-light/8', : ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
'hover:text-primary', 'hover:text-header-link-400',
'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('size-4')} /> <Icon icon="ellipsis" className={tcls('opacity-6', 'size-3', 'ms-1')} />
<DropdownChevron />
</button> </button>
); );
@@ -63,25 +56,14 @@ export function HeaderLinkMore(props: {
); );
} }
async function MoreMenuLink(props: { async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderItem }) {
context: ContentRefContext;
link: CustomizationHeaderItem | CustomizationContentLink;
}) {
const { context, link } = props; const { context, link } = props;
const target = link.to ? await resolveContentRef(link.to, context) : null; const target = link.to ? await resolveContentRef(link.to, context) : null;
return ( if (!target) {
<> 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,
'grow shrink flex justify-end items-center gap-x-6 lg:gap-x-8 min-w-9 z-20', 'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56 z-20',
)} )}
> >
{children} {children}
@@ -30,51 +30,65 @@ export function HeaderLogo(props: HeaderLogoProps) {
const { customization } = props; const { customization } = props;
return ( return (
<Link <div className={tcls('flex', 'flex-row', 'gap-2')}>
href={absoluteHref('')} <HeaderMobileMenu
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')} className={tcls(
> 'lg:hidden',
{customization.header.logo ? ( customization.header.preset === CustomizationHeaderPreset.Default
<Image ? ['text-dark', 'dark:text-light']
alt="Logo" : 'text-header-link',
sources={{ )}
light: { />
src: customization.header.logo.light, <Link
}, href={absoluteHref('')}
dark: customization.header.logo.dark className={tcls(
? { 'group/headerlogo',
src: customization.header.logo.dark, 'flex-1',
} 'flex',
: null, 'flex-row',
}} 'items-center',
sizes={[ 'shrink-0',
{ )}
media: '(max-width: 1024px)', >
width: 160, {customization.header.logo ? (
}, <Image
{ alt="Logo"
width: 260, sources={{
}, light: {
]} src: customization.header.logo.light,
priority="high" },
style={tcls( dark: customization.header.logo.dark
'rounded', ? {
'straight-corners:rounded-sm', src: customization.header.logo.dark,
'overflow-hidden', }
'shrink', : null,
'min-w-0', }}
'max-w-40', sizes={[
'lg:max-w-64', {
'max-h-10', media: '(max-width: 1024px)',
'lg:max-h-12', width: 128,
'h-full', },
'w-auto', {
)} width: 192,
/> },
) : ( ]}
<LogoFallback {...props} /> priority="high"
)} style={tcls(
</Link> 'max-w-[8rem]',
'lg:max-w-[12rem]',
'max-h-[3rem]',
'rounded',
'straight-corners:rounded-sm',
'overflow-hidden',
'object-contain',
'object-left',
)}
/>
) : (
<LogoFallback {...props} />
)}
</Link>
</div>
); );
} }
@@ -97,13 +111,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[]; className?: string }) { export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
const { space, spaces, className } = props; const { space, spaces } = props;
return ( return (
<Dropdown <Dropdown
@@ -20,27 +20,25 @@ export function SpacesDropdown(props: { space: Space; spaces: Space[]; className
'items-center', 'items-center',
'rounded-2xl', 'rounded-2xl',
'straight-corners:rounded-none', 'straight-corners:rounded-none',
'bg-light-2',
'hover:cursor-pointer', 'border',
'bg-dark/1', 'border-light-3',
'dark:bg-light/1',
'text-sm',
'text-dark-4', 'text-dark-4',
'dark:text-light-4', 'text-sm',
'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',
className, 'contrast-more:border-dark',
'contrast-more:bg-light',
'contrast-more:text-dark',
'dark:bg-dark-3',
'dark:border-dark-4',
'dark:text-light-4',
'contrast-more:dark:border-light',
'contrast-more:dark:bg-dark',
'contrast-more:dark:text-light',
)} )}
> >
<span className="line-clamp-2">{space.title}</span> {space.title}
<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 > a:nth-of-type(n + 5) { & div > :nth-child(n + 5) {
display: flex; display: flex;
} }
} }
} }
@container headerlinks ( width < 850px ) { @container headerlinks ( width < 900px ) {
.containerHeaderlinks > :nth-child(n + 6) { .containerHeaderlinks > :nth-child(n + 6) {
display: none; display: none;
} }
@@ -11,7 +11,6 @@ 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';
@@ -32,7 +31,6 @@ 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;
@@ -44,7 +42,6 @@ export function PageBody(props: {
customization, customization,
context, context,
page, page,
ancestors,
document, document,
withPageFeedback, withPageFeedback,
} = props; } = props;
@@ -82,7 +79,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} ancestors={ancestors} pages={context.pages} /> <PageHeader page={page} />
{document && !isNodeEmpty(document) ? ( {document && !isNodeEmpty(document) ? (
<React.Suspense <React.Suspense
fallback={ fallback={
@@ -151,7 +148,7 @@ export function PageBody(props: {
sitePointer={pointer} sitePointer={pointer}
spaceId={space.id} spaceId={space.id}
pageId={page.id} pageId={page.id}
apiHost={api().client.endpoint} apiHost={api().endpoint}
/> />
) : null} ) : null}
</> </>
@@ -1,19 +1,11 @@
import { RevisionPage, RevisionPageDocument } from '@gitbook/api'; import { 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: { export function PageHeader(props: { page: RevisionPageDocument }) {
page: RevisionPageDocument; const { page } = props;
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;
@@ -23,48 +15,6 @@ export function PageHeader(props: {
<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().client.orgs.createSitesPageFeedback( await api().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,13 +17,11 @@ 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 { emojiFontClassName } from '../primitives';
import { ClientContexts } from './ClientContexts'; import { ClientContexts } from './ClientContexts';
import { emojiFontClassName } from '../primitives';
import '@gitbook/icons/style.css';
import './globals.css'; import './globals.css';
import '@gitbook/icons/style.css';
const DEFAULT_TINT_COLOR = '#787878';
/** /**
* Layout shared between the content and the PDF renderer. * Layout shared between the content and the PDF renderer.
@@ -38,21 +36,26 @@ 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={tcls( className={
customization.header.preset === CustomizationHeaderPreset.None tcls(
? null customization.header.preset === CustomizationHeaderPreset.None
: 'scroll-pt-[76px]', // Take the sticky header in consideration for the scrolling ? null
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'
: '', : '') +
tintColor ? ' tint' : 'no-tint', (customization.styling.background === CustomizationBackground.Plain
)} ? ' plain-background'
: '')
}
> >
<head> <head>
{customization.privacyPolicy.url ? ( {customization.privacyPolicy.url ? (
@@ -84,22 +87,10 @@ export async function CustomizationRootLayout(props: {
) )
} }
${generateColorVariable('tint-color', tintColor?.light ?? DEFAULT_TINT_COLOR)} ${generateColorVariable(
${ 'primary-base',
// Generate the right contrast color for each shade of tint-color customization.styling.primaryColor.light,
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,
@@ -112,6 +103,10 @@ 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(
@@ -126,23 +121,6 @@ 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,
@@ -182,21 +160,6 @@ 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;
@@ -214,8 +177,6 @@ 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: {
@@ -233,17 +194,17 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
case CustomizationHeaderPreset.Bold: { case CustomizationHeaderPreset.Bold: {
return { return {
backgroundColor: { backgroundColor: {
light: tintColor?.light ?? customization.styling.primaryColor.light, light: customization.styling.primaryColor.light,
dark: tintColor?.dark ?? customization.styling.primaryColor.dark, dark: customization.styling.primaryColor.dark,
}, },
linkColor: { linkColor: {
light: colorContrast( light: colorContrast(
tintColor?.light ?? customization.styling.primaryColor.light, customization.styling.primaryColor.light,
[colors.white, colors.black], [colors.white, colors.black],
'aaa', 'aaa',
), ),
dark: colorContrast( dark: colorContrast(
tintColor?.dark ?? customization.styling.primaryColor.dark, customization.styling.primaryColor.dark,
[colors.white, colors.black], [colors.white, colors.black],
'aaa', 'aaa',
), ),
@@ -265,25 +226,15 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
case CustomizationHeaderPreset.Custom: { case CustomizationHeaderPreset.Custom: {
return { return {
backgroundColor: { backgroundColor: {
light: light: customization.header.backgroundColor?.light ?? colors.white,
customization.header.backgroundColor?.light ?? dark: customization.header.backgroundColor?.dark ?? colors.black,
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,19 +7,27 @@
--scrollbar-width: calc(100vw - 100%); --scrollbar-width: calc(100vw - 100%);
--dark-base: 20 20 20; --dark-base: 20 20 20;
--light-base: 251 251 251; --light-base: 251 252 252;
--light-1: color-mix(in srgb, rgb(var(--tint-color-600)), rgb(var(--light-base)) 99%); --light-1: color-mix(in srgb, rgb(var(--primary-base-600)), rgb(var(--light-base)) 99%);
--light-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 96%); --light-DEFAULT: color-mix(
--light-2: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 94%); in srgb,
--light-3: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 88%); rgb(var(--primary-base-700)),
--light-4: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 72%); rgb(var(--light-base)) 96%
);
--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(--tint-color-400)), rgb(var(--dark-base)) 96%); --dark-1: color-mix(in srgb, rgb(var(--primary-base-100)), rgb(1 1 1) 96%);
--dark-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 94%); --dark-DEFAULT: color-mix(
--dark-2: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 92%); in srgb,
--dark-3: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 91%); rgb(var(--primary-base-300)),
--dark-4: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 64%); rgb(var(--dark-base)) 94.5%
);
--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 {
@@ -28,13 +36,29 @@
html { html {
@apply gutter-stable; @apply gutter-stable;
} }
html:is(.no-tint) { html:is(.plain-background) {
--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(--tint-color-500)), rgb(var(--primary-base-700)),
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;
@@ -192,30 +216,3 @@ 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);
}
}
@@ -25,22 +25,18 @@ export function HighlightQuery(props: {
'py-0.5', 'py-0.5',
'rounded', 'rounded',
'straight-corners:rounded-sm', 'straight-corners:rounded-sm',
'group-[.is-active]:bg-primary-200',
'group-[.is-active]:text-contrast-primary-200',
'dark:group-[.is-active]:bg-primary-700',
'dark:group-[.is-active]:text-contrast-primary-700',
], ],
} = props; } = props;
const matches = matchString(text, query); const matches = matchString(text, query);
return ( return (
<span className={tcls('whitespace-break-spaces')}> <div className={tcls('whitespace-break-spaces')}>
{matches.map((entry, index) => ( {matches.map((entry, index) => (
<span key={index} className={tcls(entry.match ? highlight : null)}> <span key={index} className={tcls(entry.match ? highlight : null)}>
{entry.text} {entry.text}
</span> </span>
))} ))}
</span> </div>
); );
} }
@@ -1,5 +1,3 @@
'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';
@@ -9,30 +7,29 @@ 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; answer: AskAnswerResult | null;
} }
| { | {
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,
}); });
@@ -40,13 +37,12 @@ export const searchAskState = atom<SearchState | null>({
/** /**
* Fetch and render the answers to a question. * Fetch and render the answers to a question.
*/ */
export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: string }) { export function SearchAskAnswer(props: { spaceId: string; query: string }) {
const { pointer, query } = props; const { spaceId, 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;
@@ -56,9 +52,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
}); });
(async () => { (async () => {
const stream = iterateStreamResponse( const stream = iterateStreamResponse(streamAskQuestion(spaceId, query));
streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query),
);
setSearchState((prev) => setSearchState((prev) =>
prev prev
@@ -74,6 +68,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
if (cancelled) { if (cancelled) {
return; return;
} }
setState({ setState({
type: 'answer', type: 'answer',
answer: chunk, answer: chunk,
@@ -96,7 +91,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
cancelled = true; cancelled = true;
} }
}; };
}, [organizationId, siteId, siteSpaceId, query]); }, [spaceId, query, setSearchState, setState]);
React.useEffect(() => { React.useEffect(() => {
return () => { return () => {
@@ -113,9 +108,15 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
return ( return (
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}> <div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
{state?.type === 'answer' ? ( {state?.type === 'answer' ? (
<React.Suspense fallback={loading}> <>
<TransitionAnswerBody answer={state.answer} placeholder={loading} /> {state.answer ? (
</React.Suspense> <React.Suspense fallback={loading}>
<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>
@@ -158,7 +159,7 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
<div <div
data-test="search-ask-answer" data-test="search-ask-answer"
className={tcls( className={tcls(
'my-4', 'mt-4',
'sm:mt-6', 'sm:mt-6',
'px-4', 'px-4',
'sm:px-12', 'sm:px-12',
@@ -166,16 +167,16 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
'dark:text-light/8', 'dark:text-light/8',
)} )}
> >
{answer.body ?? t(language, 'search_ask_no_answer')} {answer.hasAnswer ? answer.body : t(language, 'search_ask_no_answer')}
{answer.followupQuestions.length > 0 ? ( {answer.followupQuestions.length > 0 ? (
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} /> <AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
) : null} ) : null}
</div> </div>
{answer.sources.length > 0 ? ( {answer.sources.length > 0 ? (
<AnswerSources <AnswerSources
hasAnswer={answer.hasAnswer}
sources={answer.sources} sources={answer.sources}
language={language} language={language}
hasAnswer={Boolean(answer.body)}
/> />
) : null} ) : null}
</> </>
@@ -232,7 +233,7 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
function AnswerSources(props: { function AnswerSources(props: {
sources: AskAnswerSource[]; sources: AskAnswerSource[];
language: TranslationLanguage; language: TranslationLanguage;
hasAnswer: boolean; hasAnswer?: boolean;
}) { }) {
const { sources, language, hasAnswer } = props; const { sources, language, hasAnswer } = props;
@@ -1,7 +1,6 @@
'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';
@@ -36,69 +35,45 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
'flex-row', 'flex-row',
'justify-center', 'justify-center',
'items-center', 'items-center',
'w-full', 'px-2',
'px-3', 'gap-3',
'py-2', 'text-dark/7',
'gap-2', 'min-h-[2.5rem]',
'w-[2.5rem]',
'bg-light',
'dark:bg-dark',
'ring-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', 'rounded-lg',
'straight-corners:rounded-sm', 'straight-corners:rounded-none',
'bg-dark/2',
'transition-colors',
'transition-opacity',
'ease-out',
'hover:opacity-8',
'ring-1',
'ring-inset',
'ring-dark/1',
'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',
'transition-all', '[&>span]:hidden',
'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,
)} )}
> >
<Icon <div className={tcls('text-dark/7', 'pt-1.5', 'pb-2', 'dark:text-light/7')}>
icon="magnifying-glass" <Icon icon="magnifying-glass" className={tcls('shrink-0', 'size-4')} />
className={tcls('text-dark/8', 'dark:text-light/8', 'shrink-0', 'size-4')} </div>
/> {children}
<div className={tcls('w-full', 'hidden', 'md:block', 'text-left')}>{children}</div>
<Shortcut /> <Shortcut />
</button> </button>
); );
@@ -121,22 +96,20 @@ const Shortcut = () => {
}, []); }, []);
return ( return (
<div <span
className={tcls( className={tcls(
'shortcut',
'hidden', 'hidden',
'md:inline', 'md:inline',
'justify-end', 'justify-end',
'text-xs', 'text-xs',
'text-dark/6', 'text-dark/5',
'contrast-more:text-dark', 'contrast-more:text-dark',
'dark:text-light/6', 'dark:text-light/5',
'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
</div> </span>
); );
}; };
@@ -1,5 +1,6 @@
'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';
@@ -55,6 +56,10 @@ export function SearchModal(props: SearchModalProps) {
}; };
}, [isSearchOpened]); }, [isSearchOpened]);
if (state === null) {
return null;
}
const onChangeQuery = (newQuery: SearchState) => { const onChangeQuery = (newQuery: SearchState) => {
setSearchState(newQuery); setSearchState(newQuery);
}; };
@@ -67,75 +72,62 @@ export function SearchModal(props: SearchModalProps) {
}; };
return ( return (
<AnimatePresence> <>
{state !== null ? ( <div
<motion.div role="dialog"
initial={{ className={tcls(
opacity: 0, 'flex',
}} 'items-start',
animate={{ 'justify-center',
opacity: 1, 'fixed',
}} 'inset-0',
exit={{ 'bg-dark/4',
opacity: 0, 'backdrop-blur-2xl',
}} 'opacity-[1]',
transition={{ 'z-30',
duration: 0.2, 'px-4',
delay: 0.1, 'pt-4',
}} 'dark:bg-dark/8',
role="dialog" 'md:pt-[min(8vw,_6rem)]',
className={tcls( )}
'fixed', onClick={() => {
'inset-0', onClose();
'bg-dark/4', }}
'backdrop-blur-2xl', >
'z-30', <AnimatePresence>
'px-4', {askState?.type === 'loading' ? (
'pt-4', <motion.div
'dark:bg-dark/8', key="loading"
'md:pt-[min(8vh,6rem)]', initial={{ opacity: 0 }}
)} animate={{ opacity: 1 }}
onClick={() => { exit={{ opacity: 0 }}
onClose(); transition={{ duration: 1 }}
}} className={tcls(
> 'w-[100vw]',
<div className="scroll-nojump"> 'h-[100vh]',
<AnimatePresence> 'fixed',
{askState?.type === 'loading' ? ( 'inset-0',
<motion.div 'z-10',
key="loading" 'pointer-events-none',
initial={{ opacity: 0 }} )}
animate={{ opacity: 1 }} >
exit={{ opacity: 0 }} <LoadingPane
transition={{ duration: 1 }} gridStyle={['h-[100vh]', 'aspect-auto', 'top-[-30%]']}
className={tcls( pulse
'w-screen', tile={96}
'h-screen', style={['grid']}
'fixed', />
'inset-0', </motion.div>
'z-10', ) : null}
'pointer-events-none', </AnimatePresence>
)} <SearchModalBody
> {...props}
<LoadingPane state={state}
gridStyle={['h-screen', 'aspect-auto', 'top-[-30%]']} onChangeQuery={onChangeQuery}
pulse onClose={onClose}
tile={96} />
style={['grid']} </div>
/> </>
</motion.div>
) : null}
</AnimatePresence>
<SearchModalBody
{...props}
state={state}
onChangeQuery={onChangeQuery}
onClose={onClose}
/>
</div>
</motion.div>
) : null}
</AnimatePresence>
); );
} }
@@ -166,21 +158,10 @@ 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 === 'ArrowUp') { if (event.key === 'Escape') {
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') {
@@ -202,34 +183,15 @@ function SearchModalBody(
return ( return (
<motion.div <motion.div
transition={{
duration: 0.2,
delay: 0.1,
ease: 'easeOut',
}}
initial={{
scale: 0.95,
opacity: 0,
}}
animate={{
scale: 1,
opacity: 1,
}}
exit={{
scale: 0.95,
opacity: 0,
}}
role="dialog" role="dialog"
aria-label={tString(language, 'search')} aria-label={tString(language, 'search')}
className={tcls( className={tcls(
'z-40', 'z-40',
'relative',
'flex', 'flex',
'flex-col', 'flex-col',
'bg-white', 'bg-white',
'max-w-prose', 'max-w-[768px]',
'mx-auto', 'mt-[-1px]',
'max-h-[70dvh]',
'w-full', 'w-full',
'rounded-lg', 'rounded-lg',
'straight-corners:rounded-sm', 'straight-corners:rounded-sm',
@@ -241,6 +203,14 @@ function SearchModalBody(
'dark:bg-dark-3', 'dark:bg-dark-3',
'dark:ring-light/2', 'dark:ring-light/2',
)} )}
initial={{
scale: 0.95,
opacity: 0,
}}
animate={{
scale: 1,
opacity: 1,
}}
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
}} }}
@@ -321,7 +291,7 @@ function SearchModalBody(
></SearchResults> ></SearchResults>
) : null} ) : null}
{state.query && state.ask && withAsk ? ( {state.query && state.ask && withAsk ? (
<SearchAskAnswer pointer={pointer} query={state.query} /> <SearchAskAnswer spaceId={spaceId} query={state.query} />
) : null} ) : null}
</motion.div> </motion.div>
); );
@@ -23,38 +23,26 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
href={item.href} href={item.href}
className={tcls( className={tcls(
'flex', 'flex',
'gap-4',
'flex-row', 'flex-row',
'items-center', 'items-center',
'p-4', 'px-4',
'sm:px-12',
'py-4',
'sm:py-6',
'border-t', 'border-t',
'first:border-t-0',
'border-dark/2', 'border-dark/2',
'dark:border-light/1', 'dark:border-light/2',
'first:border-none', 'hover:bg-dark-4/2',
'text-base', 'text-base',
'text-dark',
'font-medium', 'font-medium',
'hover:bg-dark/1', 'first:mt-0',
'dark:hover:bg-light/1', 'dark:text-light',
'group', 'dark:hover:bg-light-4/2',
active 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,
)} )}
> >
<div className="size-4">
<Icon
icon="file-lines"
className={tcls('size-4', active ? 'text-primary' : 'opacity-5')}
/>
</div>
<div className={tcls('flex', 'flex-col', 'w-full')}> <div className={tcls('flex', 'flex-col', 'w-full')}>
{item.spaceTitle ? ( {item.spaceTitle ? (
<div <div
@@ -72,19 +60,10 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
) : null} ) : null}
<HighlightQuery query={query} text={item.title} /> <HighlightQuery query={query} text={item.title} />
</div> </div>
<div <Icon
className={tcls( icon="chevron-right"
'p-2', className={tcls('size-4', 'text-dark', 'dark:text-light', 'opacity-6')}
'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,21 +26,16 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
onClick={onClick} onClick={onClick}
className={tcls( className={tcls(
'flex', 'flex',
'flex-row',
'px-4', 'px-4',
recommended ? ['py-2', 'text-dark/7', 'dark:text-light/8'] : 'py-4', 'py-2',
'hover:bg-dark/1', 'hover:bg-dark-4/2',
'dark:hover:bg-light/1', 'text-dark/7',
'first:mt-0', 'first:mt-0',
'last:pb-3', 'last:pb-3',
active && [ 'dark:text-light/8',
'is-active', 'dark:hover:bg-light-4/2',
'bg-primary-50', active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
'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,
@@ -48,41 +43,18 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
})} })}
> >
<Icon <Icon
icon={recommended ? 'search' : 'sparkles'} icon="magnifying-glass"
className={tcls( className={tcls(
'size-4', 'size-4',
'shrink-0', 'shrink-0',
'mt-1.5', 'mt-0.5',
'mr-4', 'mr-4',
active ? ['text-primary'] : ['text-dark/5', 'dark:text-light/5'], 'mt-1',
'text-dark/5',
'dark:text-light/5',
)} )}
/> />
<div className="w-full"> {recommended ? question : t(language, 'search_ask', [question])}
{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,6 +5,7 @@ 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';
@@ -91,6 +92,8 @@ 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));
@@ -107,16 +110,6 @@ 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]) {
@@ -181,7 +174,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
} }
return ( return (
<div className={tcls('overflow-auto')}> <div className={tcls('max-h-[70vh]', 'overflow-auto', 'relative')}>
{children} {children}
{results.length === 0 ? ( {results.length === 0 ? (
<div <div
@@ -263,13 +256,10 @@ 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 (query.length === 0) { if (!isQuestion(query)) {
return without; return without;
} }
@@ -1,4 +1,3 @@
import { Icon } from '@gitbook/icons';
import React from 'react'; import React from 'react';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
@@ -22,39 +21,27 @@ 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',
'items-center', 'flex-col',
'pl-6', 'mb-2',
'sm:pl-12', 'px-4',
'pr-4', 'sm:px-12',
'hover:bg-dark-4/2',
'dark:hover:bg-light-4/2',
'text-dark/8', 'text-dark/8',
'dark:text-light/8', 'dark:text-light/8',
'hover:bg-dark/1',
'dark:hover:bg-light/1',
'font-normal', 'font-normal',
'py-2', 'transition-colors',
'group', active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
active && [
'is-active',
'bg-primary-50',
'text-contrast-primary-50',
'dark:bg-primary-800',
'dark:text-contrast-primary-800',
'hover:bg-primary-100/8',
'dark:hover:bg-primary-700/7',
],
)} )}
> >
<div <div
className={tcls( className={tcls(
'border-l-2', 'border-l-2',
'px-4', 'px-4',
'py-1', 'py-2',
'flex',
'flex-1',
'overflow-hidden',
'flex-col',
'border-dark/2', 'border-dark/2',
'dark:border-light/2', 'dark:border-light/2',
)} )}
@@ -65,25 +52,18 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
</p> </p>
) : null} ) : null}
{item.body ? ( {item.body ? (
<p className={tcls('text-sm', 'line-clamp-3', 'relative')}> <p
className={tcls(
'text-sm',
'line-clamp-3',
'z-[-1]', //to force stacking order
'relative',
)}
>
<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;
} }
/** /**
@@ -152,53 +152,16 @@ 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* ( export const streamAskQuestion = streamResponse(async function* (spaceId: string, query: string) {
organizationId: string, const stream = api
siteId: string, .api()
siteSpaceId: string | null, .spaces.streamAskInSpace(spaceId, { query, format: 'document', details: true });
question: string, const pagesPromise = api.getSpaceContentData({ spaceId }, undefined);
) {
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) {
const answer = chunk.answer; // We run the AI search and fetch the pages in parallel
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);
} }
}); });
@@ -212,28 +175,26 @@ export async function getRecommendedQuestions(spaceId: string): Promise<string[]
} }
function transformAnswer( function transformAnswer(
answer: SearchAIAnswer, answer: SearchAIAnswer | undefined,
spacePages: Map<string, RevisionPage[]>, pages: RevisionPage[],
): AskAnswerResult { ): AskAnswerResult | null {
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: source.page, id: page.page.id,
title: page.page.title, title: page.page.title,
href: pageHref(pages, page.page), href: pageHref(pages, page.page),
}; };
@@ -256,6 +217,7 @@ function transformAnswer(
) : null, ) : null,
followupQuestions: answer.followupQuestions, followupQuestions: answer.followupQuestions,
sources, sources,
hasAnswer: !!answer.answer && 'document' in answer.answer,
}; };
} }
@@ -321,70 +283,3 @@ 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>());
}
}
@@ -106,13 +106,9 @@ export function SpaceLayout(props: {
) )
} }
innerHeader={ innerHeader={
withVariants && ( (sections || !withTopHeader) && withVariants ? (
<SpacesDropdown <SpacesDropdown space={space} spaces={spaces} />
className={withTopHeader && !sections ? 'sm:hidden' : undefined} ) : null
space={space}
spaces={spaces}
/>
)
} }
headerOffset={headerOffset} headerOffset={headerOffset}
/> />
@@ -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-sm', 'px-3', 'py-1'], medium: ['text-base', 'px-3', 'py-1'],
small: ['text-xs', 'px-3 py-2'], small: ['text-xs', 'px-3 py-2'],
}; };
@@ -3,38 +3,24 @@ 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.
- lightweight, top quality /* Load the 3 variants of the font as CSS variables and let the emoji.css decide on the best one to use */
- widely supported by modern browsers
- currently not by Safari (or iOS) const svgFont = localFont({
*/ src: './svg.woff2',
const colrv1Font = localFont({
src: './joypixels-colrv1.woff2',
preload: false, preload: false,
variable: '--font-emojis-colrv1', variable: '--font-emojis-svg',
}); });
/**
SBIX font.
- narrowly supported
- currently required for Safari (or iOS)
- provide alternative font-family name (see below)
*/
const sbixFont = localFont({ const sbixFont = localFont({
src: './joypixels-sbix.woff2', src: './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: './joypixels-cbdt.woff2', src: './cbdt.woff2',
preload: false, preload: false,
variable: '--font-emojis-cbdt', variable: '--font-emojis-cbdt',
}); });
@@ -42,7 +28,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 = [colrv1Font.variable, sbixFont.variable, cbdtFont.variable].join( export const emojiFontClassName = [svgFont.variable, sbixFont.variable, cbdtFont.variable].join(
' ', ' ',
); );
@@ -54,5 +40,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={tcls('emoji', style)}>{fallback}</span>; return <span className={'emoji ' + tcls(style)}>{fallback}</span>;
} }
@@ -0,0 +1,24 @@
[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);
}
}
@@ -13,7 +13,6 @@ export const de = {
search_scope_space: '${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:
+1 -2
View File
@@ -6,14 +6,13 @@ 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: '${1}', search_scope_space: '${1}',
search_scope_all: 'All 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:
@@ -15,7 +15,6 @@ export const es: TranslationLanguage = {
search_scope_space: '${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:
@@ -15,7 +15,6 @@ export const fr: TranslationLanguage = {
search_scope_space: '${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:
@@ -15,7 +15,6 @@ export const ja: TranslationLanguage = {
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:
@@ -15,7 +15,6 @@ export const nl: TranslationLanguage = {
search_scope_space: '${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:
@@ -15,7 +15,6 @@ export const no: TranslationLanguage = {
search_scope_space: '${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:
@@ -13,7 +13,6 @@ export const pt_br = {
search_scope_space: '${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:
@@ -15,7 +15,6 @@ export const zh: TranslationLanguage = {
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: '无法找到您的问题的答案。您可以尝试改述问题或提供更具体的信息。',
+68 -66
View File
@@ -87,30 +87,14 @@ const cacheTtl_1day = {
ttl: 24 * 60 * 60, ttl: 24 * 60 * 60,
}; };
export type GitBookAPIContext = { const apiSyncStorage = new AsyncLocalStorage<GitBookAPI>();
/**
* 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, contextId: string | undefined): GitBookAPIContext { export function apiWithToken(apiToken: string): GitBookAPI {
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;
@@ -120,13 +104,13 @@ export function apiWithToken(apiToken: string, contextId: string | undefined): G
userAgent: userAgent(), userAgent: userAgent(),
}); });
return { client: gitbook, contextId }; return gitbook;
} }
/** /**
* Create an API client for the current request. * Create an API client for the current request.
*/ */
export function api(): GitBookAPIContext { export function api(): GitBookAPI {
const existing = apiSyncStorage.getStore(); const existing = apiSyncStorage.getStore();
if (existing) { if (existing) {
return existing; return existing;
@@ -134,7 +118,6 @@ export function api(): GitBookAPIContext {
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(
@@ -142,13 +125,13 @@ export function api(): GitBookAPIContext {
); );
} }
return apiWithToken(apiToken, contextId); return apiWithToken(apiToken);
} }
/** /**
* Use an API client for an async function. * Use an API client for an async function.
*/ */
export function withAPI<T>(client: GitBookAPIContext, fn: () => Promise<T>): Promise<T> { export function withAPI<T>(client: GitBookAPI, fn: () => Promise<T>): Promise<T> {
return apiSyncStorage.run(client, fn); return apiSyncStorage.run(client, fn);
} }
@@ -181,7 +164,7 @@ export const getUserById = cache({
}), }),
get: async (userId: string, options: CacheFunctionOptions) => { get: async (userId: string, options: CacheFunctionOptions) => {
try { try {
const response = await api().client.users.getUserById(userId, { const response = await api().users.getUserById(userId, {
signal: options.signal, signal: options.signal,
...noCacheFetchOptions, ...noCacheFetchOptions,
}); });
@@ -217,7 +200,7 @@ export const getPublishedContentByUrl = cache({
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
try { try {
const response = await api().client.urls.getPublishedContentByUrl( const response = await api().urls.getPublishedContentByUrl(
{ {
url, url,
visitorAuthToken, visitorAuthToken,
@@ -266,7 +249,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().client.spaces.getSpaceById( const response = await api().spaces.getSpaceById(
spaceId, spaceId,
{ {
shareKey, shareKey,
@@ -290,7 +273,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().client.spaces.getChangeRequestById(spaceId, changeRequestId, { const response = await api().spaces.getChangeRequestById(spaceId, changeRequestId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -318,14 +301,13 @@ 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().client.spaces.getRevisionById( const response = await api().spaces.getRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -349,14 +331,13 @@ 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().client.spaces.listPagesInRevisionById( const response = await api().spaces.listPagesInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -383,7 +364,6 @@ 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,
@@ -393,7 +373,7 @@ export const getRevisionPageByPath = cache({
const encodedPath = encodeURIComponent(pagePath); const encodedPath = encodeURIComponent(pagePath);
try { try {
const response = await api().client.spaces.getPageInRevisionByPath( const response = await api().spaces.getPageInRevisionByPath(
spaceId, spaceId,
revisionId, revisionId,
encodedPath, encodedPath,
@@ -436,7 +416,7 @@ const getRevisionFileById = cache({
) => { ) => {
try { try {
const response = await (async () => { const response = await (async () => {
return api().client.spaces.getFileInRevisionById( return api().spaces.getFileInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
fileId, fileId,
@@ -465,7 +445,6 @@ 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,
@@ -474,7 +453,7 @@ const getRevisionReusableContentById = cache({
) => { ) => {
try { try {
const response = await (async () => { const response = await (async () => {
return api().client.spaces.getReusableContentInRevisionById( return api().spaces.getReusableContentInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
reusableContentId, reusableContentId,
@@ -510,7 +489,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().client.spaces.listFilesInRevisionById( api().spaces.listFilesInRevisionById(
spaceId, spaceId,
revisionId, revisionId,
{ {
@@ -621,9 +600,8 @@ 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().client.spaces.getDocumentById( const response = await api().spaces.getDocumentById(
spaceId, spaceId,
documentId, documentId,
{ {
@@ -648,7 +626,6 @@ export const getDocument = cache({
export const getSiteRedirectBySource = cache({ export const getSiteRedirectBySource = cache({
name: 'api.getSiteRedirectBySource', name: 'api.getSiteRedirectBySource',
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;
@@ -660,7 +637,7 @@ export const getSiteRedirectBySource = cache({
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
try { try {
const response = await api().client.orgs.getSiteRedirectBySource( const response = await api().orgs.getSiteRedirectBySource(
args.organizationId, args.organizationId,
args.siteId, args.siteId,
{ {
@@ -692,9 +669,8 @@ export const getSiteRedirectBySource = cache({
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().client.orgs.getSiteById(organizationId, siteId, { const response = await api().orgs.getSiteById(organizationId, siteId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -710,7 +686,6 @@ export const getSite = cache({
export const getPublishedContentSite = cache({ export const getPublishedContentSite = cache({
name: 'api.getPublishedContentSite', 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;
@@ -719,7 +694,7 @@ export const getPublishedContentSite = cache({
}, },
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().client.orgs.getPublishedContentSite( const response = await api().orgs.getPublishedContentSite(
args.organizationId, args.organizationId,
args.siteId, args.siteId,
{ {
@@ -804,7 +779,7 @@ export async function getSiteData(
const spaces = const spaces =
siteSpaces ?? (sections ? parseSpacesFromSiteSpaces(sections.section.siteSpaces) : []); siteSpaces ?? (sections ? parseSpacesFromSiteSpaces(sections.section.siteSpaces) : []);
const customization = getActiveCustomizationSettings( const customization = mergeCustomizationWithExtend(
pointer.siteSpaceId ? customizations.siteSpaces[pointer.siteSpaceId] : customizations.site, pointer.siteSpaceId ? customizations.siteSpaces[pointer.siteSpaceId] : customizations.site,
); );
@@ -851,7 +826,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().client.collections.getCollectionById(collectionId, { const response = await api().collections.getCollectionById(collectionId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -869,7 +844,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().client.collections.listSpacesInCollectionById(collectionId, params, { api().collections.listSpacesInCollectionById(collectionId, params, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}), }),
@@ -921,7 +896,6 @@ 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 */
@@ -929,7 +903,7 @@ export const searchSpaceContent = cache({
query: string, query: string,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().client.spaces.searchSpaceContent( const response = await api().spaces.searchSpaceContent(
spaceId, spaceId,
{ query }, { query },
{ {
@@ -947,9 +921,8 @@ 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().client.search.searchContent( const response = await api().search.searchContent(
{ query }, { query },
{ {
...noCacheFetchOptions, ...noCacheFetchOptions,
@@ -968,7 +941,6 @@ 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,
@@ -981,7 +953,7 @@ export const searchSiteContent = cache({
cacheBust?: string, cacheBust?: string,
options?: CacheFunctionOptions, options?: CacheFunctionOptions,
) => { ) => {
const response = await api().client.orgs.searchSiteContent( const response = await api().orgs.searchSiteContent(
organizationId, organizationId,
siteId, siteId,
{ {
@@ -1008,7 +980,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().client.spaces.getRecommendedQuestionsInSpace(spaceId, { const response = await api().spaces.getRecommendedQuestionsInSpace(spaceId, {
...noCacheFetchOptions, ...noCacheFetchOptions,
signal: options.signal, signal: options.signal,
}); });
@@ -1027,7 +999,7 @@ export const renderIntegrationUi = cache({
request: RequestRenderIntegrationUI, request: RequestRenderIntegrationUI,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
const response = await api().client.integrations.renderIntegrationUiWithPost( const response = await api().integrations.renderIntegrationUiWithPost(
integrationName, integrationName,
request, request,
{ {
@@ -1046,7 +1018,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().client.urls.getEmbedByUrl( const response = await api().urls.getEmbedByUrl(
{ url }, { url },
{ {
...noCacheFetchOptions, ...noCacheFetchOptions,
@@ -1064,7 +1036,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().client.spaces.getEmbedByUrlInSpace( const response = await api().spaces.getEmbedByUrlInSpace(
spaceId, spaceId,
{ url }, { url },
{ {
@@ -1232,19 +1204,19 @@ async function getAll<T, E>(
} }
/** /**
* Selects the customization settings from the x-gitbook-customization header if present, * Merge the customization settings with the ones passed in the x-gitbook-customization header if present.
* otherwise returns the original API-provided settings.
*/ */
function getActiveCustomizationSettings( function mergeCustomizationWithExtend<T extends SiteCustomizationSettings | CustomizationSettings>(
settings: SiteCustomizationSettings, raw: T,
): 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 parsedSettings = rison.decode_object<SiteCustomizationSettings>(extend); const parsed = rison.decode_object<DeepPartial<T>>(extend);
return parsedSettings; // Merge objects and some properties deep
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): ${
@@ -1254,5 +1226,35 @@ function getActiveCustomizationSettings(
} }
} }
return settings; return raw;
}
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;
} }
+2 -79
View File
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, it, Mock, mock } from 'bun:test'; import { Mock, beforeEach, describe, expect, it, mock } from 'bun:test';
import hash from 'object-hash';
import { CacheDefinition, CacheFunction, CacheFunctionOptions, cache } from './cache'; import { CacheFunction, CacheFunctionOptions, cache } from './cache';
describe('cache', () => { describe('cache', () => {
const impl = mock((arg: string) => 'test-' + arg); const impl = mock((arg: string) => 'test-' + arg);
@@ -70,79 +69,3 @@ 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);
});
});
+5 -16
View File
@@ -55,9 +55,6 @@ 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;
@@ -225,8 +222,7 @@ 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 cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined; const key = getCacheKey(cacheDef.name, cacheArgs);
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
return await trace( return await trace(
{ {
@@ -243,8 +239,7 @@ 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 cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined; const key = getCacheKey(cacheDef.name, cacheArgs);
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;
@@ -252,8 +247,7 @@ 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 cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined; const key = getCacheKey(cacheDef.name, cacheArgs);
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 });
@@ -281,13 +275,8 @@ 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[], suffix: string | undefined) { export function getCacheKey(fnName: string, args: any[]) {
const hashedArgs = args.map((arg) => hashValue(arg)); let innerKey = args.map((arg) => hashValue(arg)).join(',');
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 -74
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'bun:test'; import { describe, expect, it } from 'bun:test';
import { getBlockTitle, isNodeEmpty } from './document'; import { isNodeEmpty } from './document';
describe('isNodeEmpty', () => { describe('isNodeEmpty', () => {
it('should return true for a document with an empty paragraph', () => { it('should return true for a document with an empty paragraph', () => {
@@ -54,76 +54,3 @@ describe('isNodeEmpty', () => {
).toEqual(false); ).toEqual(false);
}); });
}); });
describe('#getBlockTitle', () => {
it('should return the title of an expandable block', () => {
expect(
getBlockTitle({
object: 'block',
type: 'expandable',
isVoid: true,
data: {},
key: 'OX8znB9VmbgK',
fragments: [
{
object: 'fragment',
nodes: [
{
object: 'block',
type: 'paragraph',
isVoid: false,
data: {},
nodes: [
{
object: 'text',
leaves: [
{
object: 'leaf',
text: 'Title of expandable block',
marks: [],
},
],
key: '7sZdCBHTw6Si',
},
],
key: 'msYtjdwNmiAB',
},
],
key: 'cNhmBygbrP8N',
fragment: 'expandable-title',
type: 'expandable-title',
},
{
object: 'fragment',
nodes: [
{
object: 'block',
type: 'paragraph',
isVoid: false,
data: {},
nodes: [
{
object: 'text',
leaves: [
{
object: 'leaf',
text: 'And content of the expandable',
marks: [],
},
],
key: '0GEghVKyWRBt',
},
],
key: '9iEwdHdZ5y0S',
},
],
key: 'newg71i9Ujjl',
fragment: 'expandable-body',
type: 'expandable-body',
},
],
meta: { id: 'expandable-block' },
}),
).toEqual('Title of expandable block');
});
});
+1 -1
View File
@@ -154,7 +154,7 @@ export function isNodeEmpty(
export function getBlockTitle(block: DocumentBlock): string { export function getBlockTitle(block: DocumentBlock): string {
switch (block.type) { switch (block.type) {
case 'expandable': { case 'expandable': {
const titleFragment = getNodeFragmentByType(block, 'expandable-title'); const titleFragment = getNodeFragmentByType(block, 'title');
if (titleFragment) { if (titleFragment) {
return getNodeText(titleFragment); return getNodeText(titleFragment);
} }
-2
View File
@@ -9,8 +9,6 @@ describe('getEmojiForCode', () => {
it('should handle complex codes', () => { it('should handle complex codes', () => {
expect(getEmojiForCode('1f935-2642')).toEqual('🤵‍♂️'); expect(getEmojiForCode('1f935-2642')).toEqual('🤵‍♂️');
expect(getEmojiForCode('1f3c3-2642')).toEqual('🏃‍♂️');
expect(getEmojiForCode('1f468-2696')).toEqual('👨‍⚖️');
}); });
it('should return an empty string if invalid', () => { it('should return an empty string if invalid', () => {
+1 -1
View File
@@ -67,7 +67,7 @@ export function checkIsSizableImageURL(input: string): boolean {
} }
const parsed = new URL(input); const parsed = new URL(input);
if (parsed.pathname.endsWith('.svg') || parsed.pathname.endsWith('.avif')) { if (parsed.pathname.endsWith('.svg')) {
return false; return false;
} }
if (!checkIsHttpURL(parsed)) { if (!checkIsHttpURL(parsed)) {
+31 -95
View File
@@ -1,10 +1,9 @@
import { ContentAPITokenPayload, GitBookAPI } from '@gitbook/api'; import { GitBookAPI, ContentAPITokenPayload } from '@gitbook/api';
import { setTag, setContext } from '@sentry/nextjs'; import { setTag, setContext } from '@sentry/nextjs';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import type { ResponseCookie } from 'next/dist/compiled/@edge-runtime/cookies'; import type { ResponseCookie } from 'next/dist/compiled/@edge-runtime/cookies';
import { NextResponse, NextRequest } from 'next/server'; import { NextResponse, NextRequest } from 'next/server';
import hash from 'object-hash';
import { import {
PublishedContentWithCache, PublishedContentWithCache,
@@ -44,12 +43,6 @@ type URLLookupMode =
* This mode is useful when self-hosting a single space. * This mode is useful when self-hosting a single space.
*/ */
| 'single' | 'single'
/**
* Mode when a site is being proxied on a different base URL.
* - x-gitbook-site-url is used to determine the site to serve.
* - host / x-forwarded-host / x-gitbook-host + x-gitbook-basepath is used to determine the base URL.
*/
| 'proxy'
/** /**
* Spaces are located using the incoming URL (using forwarded host headers). * Spaces are located using the incoming URL (using forwarded host headers).
* This mode is the default one when serving on the GitBook infrastructure. * This mode is the default one when serving on the GitBook infrastructure.
@@ -83,14 +76,11 @@ export type LookupResult = PublishedContentWithCache & {
}; };
/** /**
* Middleware to lookup the site to render. * Middleware to lookup the space to render.
* It takes as input a request with an URL, and a set of headers: * It takes as input a request with an URL, and a set of headers:
* - x-gitbook-api: the API endpoint to use, if undefined, the default one is used * - x-gitbook-api: the API endpoint to use, if undefined, the default one is used
* - x-gitbook-basepath: base in the path that should be ignored for routing * - x-gitbook-basepath: base in the path that should be ignored for routing
* *
* Once the site has been looked-up, the middleware passes the info to the rendering
* using a rewrite with a set of headers. This is the only way in next.js to do this (basically similar to AsyncLocalStorage).
*
* The middleware also takes care of persisting the visitor authentication state. * The middleware also takes care of persisting the visitor authentication state.
*/ */
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
@@ -115,18 +105,15 @@ export async function middleware(request: NextRequest) {
let apiEndpoint = request.headers.get('x-gitbook-api') ?? DEFAULT_API_ENDPOINT; let apiEndpoint = request.headers.get('x-gitbook-api') ?? DEFAULT_API_ENDPOINT;
const originBasePath = request.headers.get('x-gitbook-basepath') ?? ''; const originBasePath = request.headers.get('x-gitbook-basepath') ?? '';
const inputURL = mode === 'proxy' ? url : stripURLBasePath(url, originBasePath); const inputURL = stripURLBasePath(url, originBasePath);
const resolved = await withAPI( const resolved = await withAPI(
{ new GitBookAPI({
client: new GitBookAPI({ endpoint: apiEndpoint,
endpoint: apiEndpoint, authToken: getDefaultAPIToken(apiEndpoint),
authToken: getDefaultAPIToken(apiEndpoint), userAgent: userAgent(),
userAgent: userAgent(), }),
}), () => lookupSpaceForURL(mode, request, inputURL),
contextId: undefined,
},
() => lookupSiteForURL(mode, request, inputURL),
); );
if ('error' in resolved) { if ('error' in resolved) {
return new NextResponse(resolved.error.message, { return new NextResponse(resolved.error.message, {
@@ -166,17 +153,13 @@ export async function middleware(request: NextRequest) {
// Resolution might have changed the API endpoint // Resolution might have changed the API endpoint
apiEndpoint = resolved.apiEndpoint ?? apiEndpoint; apiEndpoint = resolved.apiEndpoint ?? apiEndpoint;
const contextId = 'site' in resolved ? resolved.contextId : undefined;
const nonce = createContentSecurityPolicyNonce(); const nonce = createContentSecurityPolicyNonce();
const csp = await withAPI( const csp = await withAPI(
{ new GitBookAPI({
client: new GitBookAPI({ endpoint: apiEndpoint,
endpoint: apiEndpoint, authToken: resolved.apiToken,
authToken: resolved.apiToken, userAgent: userAgent(),
userAgent: userAgent(), }),
}),
contextId,
},
async () => { async () => {
const [siteData] = await Promise.all([ const [siteData] = await Promise.all([
'site' in resolved 'site' in resolved
@@ -215,15 +198,9 @@ export async function middleware(request: NextRequest) {
headers.set('x-forwarded-host', inputURL.host); headers.set('x-forwarded-host', inputURL.host);
headers.set('origin', inputURL.origin); headers.set('origin', inputURL.origin);
headers.set('x-gitbook-token', resolved.apiToken); headers.set('x-gitbook-token', resolved.apiToken);
if (contextId) {
headers.set('x-gitbook-token-context', contextId);
}
headers.set('x-gitbook-mode', mode); headers.set('x-gitbook-mode', mode);
headers.set('x-gitbook-origin-basepath', originBasePath); headers.set('x-gitbook-origin-basepath', originBasePath);
headers.set( headers.set('x-gitbook-basepath', joinPath(originBasePath, resolved.basePath));
'x-gitbook-basepath',
mode === 'proxy' ? originBasePath : joinPath(originBasePath, resolved.basePath),
);
headers.set('x-gitbook-content-space', resolved.space); headers.set('x-gitbook-content-space', resolved.space);
if ('site' in resolved) { if ('site' in resolved) {
headers.set('x-gitbook-content-organization', resolved.organization); headers.set('x-gitbook-content-organization', resolved.organization);
@@ -314,10 +291,7 @@ export async function middleware(request: NextRequest) {
/** /**
* Compute the input URL the user is trying to access. * Compute the input URL the user is trying to access.
*/ */
function getInputURL(request: NextRequest): { function getInputURL(request: NextRequest): { url: URL; mode: URLLookupMode } {
url: URL;
mode: URLLookupMode;
} {
const url = new URL(request.url); const url = new URL(request.url);
let mode: URLLookupMode = let mode: URLLookupMode =
(process.env.GITBOOK_MODE as URLLookupMode | undefined) ?? 'multi-path'; (process.env.GITBOOK_MODE as URLLookupMode | undefined) ?? 'multi-path';
@@ -347,36 +321,27 @@ function getInputURL(request: NextRequest): {
mode = 'multi-id'; mode = 'multi-id';
} }
// When passing a x-gitbook-site-url header, this URL is used instead of the request URL
// to determine the site to serve.
const xGitbookSite = request.headers.get('x-gitbook-site-url');
if (xGitbookSite) {
mode = 'proxy';
}
return { url, mode }; return { url, mode };
} }
async function lookupSiteForURL( async function lookupSpaceForURL(
mode: URLLookupMode, mode: URLLookupMode,
request: NextRequest, request: NextRequest,
url: URL, url: URL,
): Promise<LookupResult> { ): Promise<LookupResult> {
switch (mode) { switch (mode) {
case 'single': { case 'single': {
return await lookupSiteInSingleMode(url); return await lookupSpaceInSingleMode(url);
} }
case 'multi': { case 'multi': {
return await lookupSiteInMultiMode(request, url); return await lookupSpaceInMultiMode(request, url);
} }
case 'multi-path': { case 'multi-path': {
return await lookupSiteInMultiPathMode(request, url); return await lookupSpaceInMultiPathMode(request, url);
} }
case 'multi-id': { case 'multi-id': {
return await lookupSiteOrSpaceInMultiIdMode(request, url); return await lookupSiteOrSpaceInMultiIdMode(request, url);
} }
case 'proxy':
return await lookupSiteInProxy(request, url);
default: default:
assertNever(mode); assertNever(mode);
} }
@@ -386,7 +351,7 @@ async function lookupSiteForURL(
* GITBOOK_MODE=single * GITBOOK_MODE=single
* When serving a single space, configured using GITBOOK_SPACE_ID and GITBOOK_TOKEN. * When serving a single space, configured using GITBOOK_SPACE_ID and GITBOOK_TOKEN.
*/ */
async function lookupSiteInSingleMode(url: URL): Promise<LookupResult> { async function lookupSpaceInSingleMode(url: URL): Promise<LookupResult> {
const spaceId = process.env.GITBOOK_SPACE_ID; const spaceId = process.env.GITBOOK_SPACE_ID;
if (!spaceId) { if (!spaceId) {
throw new Error( throw new Error(
@@ -394,7 +359,7 @@ async function lookupSiteInSingleMode(url: URL): Promise<LookupResult> {
); );
} }
const apiToken = getDefaultAPIToken(api().client.endpoint); const apiToken = getDefaultAPIToken(api().endpoint);
if (!apiToken) { if (!apiToken) {
throw new Error( throw new Error(
`Missing GITBOOK_TOKEN environment variable. It should be passed when using GITBOOK_MODE=single.`, `Missing GITBOOK_TOKEN environment variable. It should be passed when using GITBOOK_MODE=single.`,
@@ -410,31 +375,13 @@ async function lookupSiteInSingleMode(url: URL): Promise<LookupResult> {
}; };
} }
/**
* GITBOOK_MODE=proxy
* When proxying a site on a different base URL.
*/
async function lookupSiteInProxy(request: NextRequest, url: URL): Promise<LookupResult> {
const rawSiteUrl = request.headers.get('x-gitbook-site-url');
if (!rawSiteUrl) {
throw new Error(
`Missing x-gitbook-site-url header. It should be passed when using GITBOOK_MODE=proxy.`,
);
}
const siteUrl = new URL(rawSiteUrl);
siteUrl.pathname = joinPath(siteUrl.pathname, url.pathname);
return await lookupSiteInMultiMode(request, siteUrl);
}
/** /**
* GITBOOK_MODE=multi * GITBOOK_MODE=multi
* When serving multi spaces based on the current URL. * When serving multi spaces based on the current URL.
*/ */
async function lookupSiteInMultiMode(request: NextRequest, url: URL): Promise<LookupResult> { async function lookupSpaceInMultiMode(request: NextRequest, url: URL): Promise<LookupResult> {
const visitorAuthToken = getVisitorAuthToken(request, url); const visitorAuthToken = getVisitorAuthToken(request, url);
const lookup = await lookupSiteByAPI(url, visitorAuthToken); const lookup = await lookupSpaceByAPI(url, visitorAuthToken);
return { return {
...lookup, ...lookup,
...('basePath' in lookup && visitorAuthToken ...('basePath' in lookup && visitorAuthToken
@@ -523,16 +470,8 @@ async function lookupSiteOrSpaceInMultiIdMode(
throw new Error('Collection is not supported in multi-id mode'); throw new Error('Collection is not supported in multi-id mode');
} }
// The claims property in the content API token is included when
// visitor attributes/assertions are passed to the site preview URL.
//
// When it's present, we generate a hash using the same method as
// getPublishedContentByURL to get the context ID so the cache can be
// invalidated when trying to preview the site with different visitor
// attributes.
const contextId = decoded.claims ? hash(decoded.claims) : undefined;
const gitbookAPI = new GitBookAPI({ const gitbookAPI = new GitBookAPI({
endpoint: apiEndpoint ?? api().client.endpoint, endpoint: apiEndpoint ?? api().endpoint,
authToken: apiToken, authToken: apiToken,
userAgent: userAgent(), userAgent: userAgent(),
}); });
@@ -540,15 +479,13 @@ async function lookupSiteOrSpaceInMultiIdMode(
// Verify access to the space to avoid leaking cached data in this mode // Verify access to the space to avoid leaking cached data in this mode
// (the cache is not dependend on the auth token, so it could leak data) // (the cache is not dependend on the auth token, so it could leak data)
if (source.kind === 'space') { if (source.kind === 'space') {
await withAPI({ client: gitbookAPI, contextId }, () => await withAPI(gitbookAPI, () => getSpace.revalidate(source.id, undefined));
getSpace.revalidate(source.id, undefined),
);
} }
// Verify access to the site to avoid leaking cached data in this mode // Verify access to the site to avoid leaking cached data in this mode
// (the cache is not dependend on the auth token, so it could leak data) // (the cache is not dependend on the auth token, so it could leak data)
if (source.kind === 'site') { if (source.kind === 'site') {
await withAPI({ client: gitbookAPI, contextId }, () => await withAPI(gitbookAPI, () =>
getPublishedContentSite.revalidate({ getPublishedContentSite.revalidate({
organizationId: decoded.organization, organizationId: decoded.organization,
siteId: source.id, siteId: source.id,
@@ -599,7 +536,7 @@ async function lookupSiteOrSpaceInMultiIdMode(
* GITBOOK_MODE=multi-path * GITBOOK_MODE=multi-path
* When serving multi spaces with the url passed in the path. * When serving multi spaces with the url passed in the path.
*/ */
async function lookupSiteInMultiPathMode(request: NextRequest, url: URL): Promise<LookupResult> { async function lookupSpaceInMultiPathMode(request: NextRequest, url: URL): Promise<LookupResult> {
// Skip useless requests // Skip useless requests
if ( if (
url.pathname === '/favicon.ico' || url.pathname === '/favicon.ico' ||
@@ -638,7 +575,7 @@ async function lookupSiteInMultiPathMode(request: NextRequest, url: URL): Promis
const visitorAuthToken = getVisitorAuthToken(request, target); const visitorAuthToken = getVisitorAuthToken(request, target);
const lookup = await lookupSiteByAPI(target, visitorAuthToken); const lookup = await lookupSpaceByAPI(target, visitorAuthToken);
if ('error' in lookup) { if ('error' in lookup) {
return lookup; return lookup;
} }
@@ -674,7 +611,7 @@ async function lookupSiteInMultiPathMode(request: NextRequest, url: URL): Promis
* Lookup a space by its URL using the GitBook API. * Lookup a space by its URL using the GitBook API.
* To optimize caching, we try multiple lookup alternatives and return the first one that matches. * To optimize caching, we try multiple lookup alternatives and return the first one that matches.
*/ */
async function lookupSiteByAPI( async function lookupSpaceByAPI(
lookupURL: URL, lookupURL: URL,
visitorAuthToken: ReturnType<typeof getVisitorAuthToken>, visitorAuthToken: ReturnType<typeof getVisitorAuthToken>,
): Promise<LookupResult> { ): Promise<LookupResult> {
@@ -764,7 +701,6 @@ async function lookupSiteByAPI(
siteSpace: data.siteSpace, siteSpace: data.siteSpace,
organization: data.organization, organization: data.organization,
shareKey: data.shareKey, shareKey: data.shareKey,
...(data.contextId ? { contextId: data.contextId } : {}),
} }
: {}), : {}),
} as PublishedContentWithCache; } as PublishedContentWithCache;
@@ -812,7 +748,7 @@ function getLookupResultForVisitorAuth(
), ),
options: { options: {
httpOnly: true, httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined, sameSite: 'none',
secure: process.env.NODE_ENV === 'production', secure: process.env.NODE_ENV === 'production',
maxAge: 7 * 24 * 60 * 60, maxAge: 7 * 24 * 60 * 60,
}, },
+5 -13
View File
@@ -6,7 +6,7 @@ import plugin from 'tailwindcss/plugin';
import { hexToRgb, shadesOfColor } from './src/lib/colors'; import { hexToRgb, shadesOfColor } from './src/lib/colors';
export const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]; export const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
export const opacities = [0, 4, 8, 12, 16, 24, 40, 64, 72, 88, 96, 100]; export const opacities = [0, 4, 8, 12, 16, 24, 40, 64, 72, 88, 96];
/** /**
* Generate a Tailwind color shades from a variable. * Generate a Tailwind color shades from a variable.
@@ -72,8 +72,9 @@ const config: Config = {
/** primary-color used to accent elements, these colors remain unchanged when toggling between the CustomizationBackground options**/ /** primary-color used to accent elements, these colors remain unchanged when toggling between the CustomizationBackground options**/
primary: generateVarShades('primary-color'), primary: generateVarShades('primary-color'),
'contrast-primary': generateVarShades('contrast-primary'), 'contrast-primary': generateVarShades('contrast-primary'),
tint: generateVarShades('primary-color'),
'contrast-tint': generateVarShades('contrast-primary'), /** primary-base is an internal color that generates the same colors as primary-color. But it's shades will change into a grayscale if CustomizationBackground.Plain is selected. (globals.css) **/
primarybase: generateVarShades('primary-base'),
'header-background': generateVarShades('header-background'), 'header-background': generateVarShades('header-background'),
'header-link': generateVarShades('header-link'), 'header-link': generateVarShades('header-link'),
@@ -208,10 +209,6 @@ const config: Config = {
thintop: '0px -1px 0px rgba(0, 0, 0, 0.05)', thintop: '0px -1px 0px rgba(0, 0, 0, 0.05)',
'1xs': '0px 1px 1px rgba(0, 0, 0, 0.09), 0px 3.267px 2.754px rgb(0, 0, 0, 0.05), 0px 6.278px 6.63px rgb(0, 0, 0, 0.05), 0px 14px 22px rgb(0, 0, 0, 0.04)', '1xs': '0px 1px 1px rgba(0, 0, 0, 0.09), 0px 3.267px 2.754px rgb(0, 0, 0, 0.05), 0px 6.278px 6.63px rgb(0, 0, 0, 0.05), 0px 14px 22px rgb(0, 0, 0, 0.04)',
}, },
scale: {
'98': '0.98',
'102': '1.02',
},
}, },
opacity: opacity(), opacity: opacity(),
}, },
@@ -235,12 +232,7 @@ const config: Config = {
/** /**
* Variant when the space is configured with a theme matching background. * Variant when the space is configured with a theme matching background.
*/ */
addVariant('tint', 'html.tint &'); addVariant('plain-background', 'html.plain-background &');
/**
* Variant when the space is configured without a theme matching background.
*/
addVariant('no-tint', 'html.no-tint &');
/** /**
* Variant when the page contains a block that will be rendered in full-width mode. * Variant when the page contains a block that will be rendered in full-width mode.
-1
View File
@@ -1 +0,0 @@
dist/
-7
View File
@@ -1,7 +0,0 @@
# @gitbook/proxy
## 0.1.0
### Minor Changes
- 53b9f10: First version
-28
View File
@@ -1,28 +0,0 @@
# `@gitbook/proxy`
Host a GitBook site on your own domain as a subpath.
## Usage
```ts
import { proxyToGitBook } from '@gitbook/proxy';
const site = proxyToGitBook(event.request, {
site: 'mycompany.gitbook.io/site/',
basePath: '/docs',
});
export default {
async fetch(request) {
// If the requst matches the basePath /docs, we serve from GitBook
if (site.match(request)) {
return site.fetch(request);
}
// Otherwise we do something else.
return new Response('Not found', {
statusCode: 404,
});
},
};
```
-28
View File
@@ -1,28 +0,0 @@
{
"name": "@gitbook/proxy",
"description": "Host a GitBook site on your own domain as a subpath",
"version": "0.1.0",
"exports": {
".": {
"types": "./dist/index.d.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
}
},
"dependencies": {},
"devDependencies": {
"typescript": "^5.5.3"
},
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"clean": "rm -rf ./dist",
"unit": "bun test"
},
"files": [
"dist",
"src",
"README.md",
"CHANGELOG.md"
]
}
-59
View File
@@ -1,59 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { proxyToGitBook } from '.';
describe('.match', () => {
it('should return true if the request is below the base path', () => {
const site = proxyToGitBook({ site: 'https://org.gitbook.io/example/', basePath: '/docs' });
expect(site.match('/docs')).toBe(true);
expect(site.match('/docs/')).toBe(true);
expect(site.match('/docs/hello')).toBe(true);
expect(site.match('/docs/hello/world')).toBe(true);
expect(site.match('/hello/world')).toBe(false);
expect(site.match('/')).toBe(false);
});
});
describe('.request', () => {
it('should compute a proper request for a sub-path', () => {
const site = proxyToGitBook({ site: 'https://org.gitbook.io/example/', basePath: '/docs' });
const request = new Request('https://example.com/docs/hello/world');
const proxiedRequest = site.request(request);
expect(proxiedRequest.url).toBe('https://hosting.gitbook.io/docs/hello/world');
expect(proxiedRequest.headers.get('Host')).toBe('hosting.gitbook.io');
expect(proxiedRequest.headers.get('X-Forwarded-Host')).toBe('example.com');
expect(proxiedRequest.headers.get('X-GitBook-BasePath')).toBe('/docs');
expect(proxiedRequest.headers.get('X-GitBook-Site-URL')).toBe(
'https://org.gitbook.io/example/',
);
});
it('should compute a proper request on the root', () => {
const site = proxyToGitBook({ site: 'https://org.gitbook.io/example/', basePath: '/docs' });
const request = new Request('https://example.com/docs');
const proxiedRequest = site.request(request);
expect(proxiedRequest.url).toBe('https://hosting.gitbook.io/docs');
expect(proxiedRequest.headers.get('Host')).toBe('hosting.gitbook.io');
expect(proxiedRequest.headers.get('X-Forwarded-Host')).toBe('example.com');
expect(proxiedRequest.headers.get('X-GitBook-BasePath')).toBe('/docs');
expect(proxiedRequest.headers.get('X-GitBook-Site-URL')).toBe(
'https://org.gitbook.io/example/',
);
});
it('should normalize the basepath', () => {
const site = proxyToGitBook({ site: 'https://org.gitbook.io/example/', basePath: 'docs/' });
const request = new Request('https://example.com/docs/hello/world');
const proxiedRequest = site.request(request);
expect(proxiedRequest.url).toBe('https://hosting.gitbook.io/docs/hello/world');
expect(proxiedRequest.headers.get('Host')).toBe('hosting.gitbook.io');
expect(proxiedRequest.headers.get('X-Forwarded-Host')).toBe('example.com');
expect(proxiedRequest.headers.get('X-GitBook-BasePath')).toBe('/docs');
expect(proxiedRequest.headers.get('X-GitBook-Site-URL')).toBe(
'https://org.gitbook.io/example/',
);
});
});
-97
View File
@@ -1,97 +0,0 @@
export interface ProxyToGitBookOptions {
/**
* The URL of the published site.
* @example "https://mycompany.gitbook.io/docs"
*/
site: string;
/**
* Base path to serve the site on.
* @example "/docs"
*/
basePath: string;
/**
* Hostname used by GitBook to serve content.
* Do not set this option unless you know what you are doing.
*/
gitbookHost?: string;
}
export interface ProxySite {
/**
* Test if the request should be proxied to this site.
*/
match(request: Request | string): boolean;
/**
* Get the proxied request for a given request.
*/
request(request: Request): Request;
/**
* Fetch the request from the site.
*/
fetch(request: Request): Promise<Response>;
}
/**
* Proxies requests to a GitBook site.
*/
export function proxyToGitBook(options: ProxyToGitBookOptions): ProxySite {
const { gitbookHost = 'hosting.gitbook.io' } = options;
const siteUrl = new URL(options.site);
const rawSiteUrl = siteUrl.toString();
const basePath = normalizeBasePath(options.basePath);
const site: ProxySite = {
match: (request) => {
const pathname = typeof request === 'string' ? request : new URL(request.url).pathname;
return pathname === basePath || pathname.startsWith(basePath + '/');
},
request: (originRequest) => {
const originUrl = new URL(originRequest.url);
const url = new URL(originUrl);
url.hostname = gitbookHost;
const proxyRequest = new Request(url, originRequest);
proxyRequest.headers.set('Host', gitbookHost);
// Pass the original host and protocol
proxyRequest.headers.set('X-Forwarded-Host', originUrl.hostname);
proxyRequest.headers.set('X-Forwarded-Proto', 'https');
// Pass the basepath on the original URL
proxyRequest.headers.set('X-GitBook-BasePath', basePath);
// Pass the site URL
proxyRequest.headers.set('X-GitBook-Site-URL', rawSiteUrl);
return proxyRequest;
},
fetch: async (originRequest) => {
return fetch(site.request(originRequest));
},
};
return site;
}
function normalizeBasePath(basePath: string): string {
let result = withLeadingSlash(basePath);
result = withoutTrailingSlash(result);
return result;
}
function withLeadingSlash(path: string): string {
return path.startsWith('/') ? path : '/' + path;
}
function withoutTrailingSlash(path: string): string {
return path.endsWith('/') ? path.slice(0, -1) : path;
}
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": false,
"declaration": true,
"outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"types": [
"bun-types" // add Bun global
]
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
-10
View File
@@ -1,15 +1,5 @@
# @gitbook/react-openapi # @gitbook/react-openapi
## 0.7.1
### Patch Changes
- 4771c78: Fixed scalar api client routing
- ff50ac2: Bump @scalar/api-client-react version
- 867481c: Support Integers in Response example
- 7ba67fd: bumped the scalar api client dependency
- a78c1ec: Bumped scalar api client pacakge
## 0.7.0 ## 0.7.0
### Minor Changes ### Minor Changes
+1 -1
View File
@@ -8,7 +8,7 @@
"default": "./dist/index.js" "default": "./dist/index.js"
} }
}, },
"version": "0.7.1", "version": "0.7.0",
"dependencies": { "dependencies": {
"@scalar/api-client-react": "1.0.87", "@scalar/api-client-react": "1.0.87",
"classnames": "^2.5.1", "classnames": "^2.5.1",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://turbo.build/schema.json", "$schema": "https://turbo.build/schema.json",
"ui": "tui", "ui": "tui",
"globalEnv": ["NODE_ENV", "CI", "ARGOS_*", "GITHUB_*", "GITBOOK_*", "SENTRY_*"], "globalEnv": ["NODE_ENV", "CI", "ARGOS_*", "GITHUB_*"],
"tasks": { "tasks": {
// Prepare the package for all other tasks // Prepare the package for all other tasks
"generate": { "generate": {