mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-16 07:35:16 +00:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b06ad7c241 | |||
| 0c51189ce1 | |||
| 8d039d1348 | |||
| 87eea73081 | |||
| 67a6fb4c87 | |||
| 23584c9862 | |||
| 2f767125c4 | |||
| c73e07d42d | |||
| 6b5d7e6057 | |||
| 076dc48e89 | |||
| bb208ab36a | |||
| 60e35001b6 | |||
| 29a0d7ea02 | |||
| 1f2b7f7acf | |||
| 39e5cb63ef | |||
| 5b5928fb8d | |||
| 08068743a5 | |||
| 35eae1adcf | |||
| e85d357abd | |||
| 31396d8109 | |||
| 664debc0bc | |||
| 56c31c76b3 | |||
| 2d1a71f3d1 | |||
| c67cd73058 | |||
| 2572cb4352 | |||
| c9f6c7ccac | |||
| b6520b0dbc | |||
| 9fe8142117 | |||
| 57cdd25b5f |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix expandable block anchore resolution
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Update the site header with new styling, a new search button, and refactored layout
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add support for tint color
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add breadcrumbs above page title
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
GitBook Open now supports Ask AI in sites. When asking a question to Ask AI, GitBook will use context from across your site sections and variants to provide the best answer.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Fix margin and image resolution of header logo
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Fix an issue where Ask AI was erroring due to an object being passed as a param.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Increase token max length to fix code not highlighted
|
||||
@@ -12,7 +12,7 @@ runs:
|
||||
|
||||
# Cache browser binaries, cache key is based on Playwright version and OS
|
||||
- name: 🧰 Cache Playwright browser binaries
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: '~/.cache/ms-playwright'
|
||||
|
||||
@@ -30,16 +30,6 @@ jobs:
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||
- name: Cache Next.js build
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
${{ github.workspace }}/.next/cache
|
||||
# Generate a new cache whenever packages or source files change.
|
||||
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
# If source files changed but packages didn't, rebuild from a prior cache.
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-
|
||||
- name: Sets env vars for production
|
||||
run: |
|
||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { argosScreenshot } from '@argos-ci/playwright';
|
||||
import {
|
||||
CustomizationBackground,
|
||||
CustomizationCorners,
|
||||
CustomizationFont,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationIconsStyle,
|
||||
CustomizationLocale,
|
||||
CustomizationThemeMode,
|
||||
SiteCustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import deepMerge from 'deepmerge';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import rison from 'rison';
|
||||
import { DeepPartial } from 'ts-essentials';
|
||||
@@ -34,6 +39,18 @@ const allLocales: CustomizationLocale[] = [
|
||||
CustomizationLocale.Zh,
|
||||
];
|
||||
|
||||
const allThemeModes: CustomizationThemeMode[] = [
|
||||
CustomizationThemeMode.Light,
|
||||
CustomizationThemeMode.Dark,
|
||||
];
|
||||
|
||||
const allThemePresets: CustomizationHeaderPreset[] = [
|
||||
CustomizationHeaderPreset.Default,
|
||||
CustomizationHeaderPreset.Bold,
|
||||
CustomizationHeaderPreset.Contrast,
|
||||
CustomizationHeaderPreset.Custom,
|
||||
];
|
||||
|
||||
async function waitForCookiesDialog(page: Page) {
|
||||
const dialog = page.getByRole('dialog', { name: 'Cookies' });
|
||||
const accept = dialog.getByRole('button', { name: 'Accept' });
|
||||
@@ -95,7 +112,9 @@ const testCases: TestsCase[] = [
|
||||
name: 'Variants dropdown',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
|
||||
const spaceDrowpdown = page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.waitFor();
|
||||
},
|
||||
},
|
||||
@@ -111,7 +130,9 @@ const testCases: TestsCase[] = [
|
||||
name: 'Customized variant titles are displayed',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
|
||||
const spaceDrowpdown = page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
const variantSelectionDropdown = page.locator(
|
||||
@@ -143,9 +164,9 @@ const testCases: TestsCase[] = [
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -166,9 +187,9 @@ const testCases: TestsCase[] = [
|
||||
url: 'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -201,9 +222,9 @@ const testCases: TestsCase[] = [
|
||||
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
const spaceDrowpdown = await page
|
||||
.locator('[data-testid="space-dropdown-button"]')
|
||||
.locator('visible=true');
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
@@ -435,30 +456,38 @@ const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'Customization',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
tests: [
|
||||
tests: allThemeModes.flatMap((theme) => [
|
||||
{
|
||||
name: 'Without header',
|
||||
name: `Without header - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.None,
|
||||
links: [],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With duotone icons',
|
||||
name: `With duotone icons - Theme ${theme}`,
|
||||
url:
|
||||
'page-options/page-with-icon' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
icons: CustomizationIconsStyle.Duotone,
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With header buttons',
|
||||
name: `With header buttons - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
@@ -475,10 +504,101 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
{
|
||||
name: `Without tint - Default preset - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
...allThemePresets.flatMap((preset) => ({
|
||||
name: `With tint - Preset ${preset} - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
header: {
|
||||
preset,
|
||||
...(preset === CustomizationHeaderPreset.Custom
|
||||
? {
|
||||
backgroundColor: { light: '#C62C68', dark: '#EF96B8' },
|
||||
linkColor: { light: '#4DDE98', dark: '#0C693D' },
|
||||
}
|
||||
: {}),
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
})),
|
||||
{
|
||||
name: `With tint - Legacy background match - Theme ${theme}`,
|
||||
url: getCustomizationURL({
|
||||
styling: {
|
||||
background: CustomizationBackground.Match,
|
||||
},
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [
|
||||
{
|
||||
title: 'Secondary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-secondary',
|
||||
},
|
||||
{
|
||||
title: 'Primary button',
|
||||
to: { kind: 'url', url: 'https://www.gitbook.com' },
|
||||
style: 'button-primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
]),
|
||||
},
|
||||
{
|
||||
name: 'Ads',
|
||||
@@ -814,6 +934,178 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Adaptive Content - VA',
|
||||
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-va/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'isAlphaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
await expect(betaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isBetaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
await expect(alphaUserPage).toHaveCount(0);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isAlphaUser & isBetaUser',
|
||||
url: (() => {
|
||||
const privateKey = 'afe09cdf-0f43-480a-b54c-8b1f62f174f9';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
isAlphaUser: true,
|
||||
isBetaUser: true,
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const alphaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Alpha users' });
|
||||
const betaUserPage = page
|
||||
.locator('a[class*="group\\/toclink"]')
|
||||
.filter({ hasText: 'Beta users' });
|
||||
await expect(alphaUserPage).toBeVisible();
|
||||
await expect(betaUserPage).toBeVisible();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Tables',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Default table',
|
||||
url: 'blocks/tables',
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Table with straight corners',
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
corners: CustomizationCorners.Straight,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Table with primary color',
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
// Test dark mode for each variant
|
||||
...allThemeModes.flatMap((theme) => [
|
||||
{
|
||||
name: `Table in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: `Table with straight corners in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
corners: CustomizationCorners.Straight,
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: `Table with primary color in ${theme} mode`,
|
||||
url:
|
||||
'blocks/tables' +
|
||||
getCustomizationURL({
|
||||
styling: {
|
||||
tint: { color: { light: '#346DDB', dark: '#346DDB' } },
|
||||
},
|
||||
themes: {
|
||||
default: theme,
|
||||
toggeable: false,
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
for (const testCase of testCases) {
|
||||
@@ -848,7 +1140,62 @@ for (const testCase of testCases) {
|
||||
* Create a URL with customization settings.
|
||||
*/
|
||||
function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): string {
|
||||
const encoded = rison.encode_object(partial);
|
||||
/**
|
||||
* Default customization settings.
|
||||
*
|
||||
* The customization object passed to the URL should be a valid API settings object. Hence we extend the test with necessary defaults.
|
||||
*/
|
||||
const DEFAULT_CUSTOMIZATION: SiteCustomizationSettings = {
|
||||
styling: {
|
||||
primaryColor: { light: '#346DDB', dark: '#346DDB' },
|
||||
corners: CustomizationCorners.Rounded,
|
||||
font: CustomizationFont.Inter,
|
||||
background: CustomizationBackground.Plain,
|
||||
icons: CustomizationIconsStyle.Regular,
|
||||
},
|
||||
internationalization: {
|
||||
locale: CustomizationLocale.En,
|
||||
},
|
||||
favicon: {},
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.Default,
|
||||
links: [],
|
||||
},
|
||||
footer: {
|
||||
groups: [],
|
||||
},
|
||||
themes: {
|
||||
default: CustomizationThemeMode.Light,
|
||||
toggeable: true,
|
||||
},
|
||||
pdf: {
|
||||
enabled: true,
|
||||
},
|
||||
feedback: {
|
||||
enabled: false,
|
||||
},
|
||||
aiSearch: {
|
||||
enabled: true,
|
||||
},
|
||||
advancedCustomization: {
|
||||
enabled: true,
|
||||
},
|
||||
git: {
|
||||
showEditLink: false,
|
||||
},
|
||||
pagination: {
|
||||
enabled: true,
|
||||
},
|
||||
trademark: {
|
||||
enabled: true,
|
||||
},
|
||||
privacyPolicy: {
|
||||
url: 'https://www.gitbook.com/privacy',
|
||||
},
|
||||
socialPreview: {},
|
||||
};
|
||||
|
||||
const encoded = rison.encode_object(deepMerge(DEFAULT_CUSTOMIZATION, partial));
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('customization', encoded);
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gitbook/api": "^0.80.0",
|
||||
"@gitbook/api": "^0.81.0",
|
||||
"@gitbook/cache-do": "workspace:*",
|
||||
"@gitbook/emoji-codepoints": "workspace:*",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
@@ -49,8 +49,8 @@
|
||||
"p-map": "^7.0.0",
|
||||
"parse-cache-control": "^1.0.1",
|
||||
"postcss-color-contrast": "^1.1.0",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1",
|
||||
"react-hotkeys-hook": "^4.4.1",
|
||||
"recoil": "^0.7.7",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
@@ -68,9 +68,9 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^2.0.0",
|
||||
"@playwright/test": "^1.42.1",
|
||||
"@cloudflare/next-on-pages": "^1.13.5",
|
||||
"@cloudflare/workers-types": "^4.20240725.0",
|
||||
"@playwright/test": "^1.42.1",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
@@ -78,10 +78,12 @@
|
||||
"@types/object-hash": "^3.0.6",
|
||||
"@types/parse-cache-control": "^1.0.4",
|
||||
"@types/psi": "^4.1.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@types/react": "18.3.13",
|
||||
"@types/react-dom": "18.3.1",
|
||||
"@types/rison": "^0.0.9",
|
||||
"autoprefixer": "^10",
|
||||
"deepmerge": "^4.3.1",
|
||||
"env-cmd": "^10.1.0",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "^14.2.5",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
@@ -89,8 +91,7 @@
|
||||
"postcss": "^8",
|
||||
"psi": "^4.1.0",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"typescript": "^5.5.3",
|
||||
"env-cmd": "^10.1.0",
|
||||
"ts-essentials": "^10.0.1"
|
||||
"ts-essentials": "^10.0.1",
|
||||
"typescript": "^5.5.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export default async function Page(props: {
|
||||
customization,
|
||||
pages,
|
||||
page,
|
||||
ancestors,
|
||||
document,
|
||||
} = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
@@ -103,6 +104,7 @@ export default async function Page(props: {
|
||||
customization={customization}
|
||||
context={contentRefContext}
|
||||
page={page}
|
||||
ancestors={ancestors}
|
||||
document={document}
|
||||
withPageFeedback={
|
||||
// Display the page feedback in the page footer if the aside is not visible
|
||||
@@ -150,7 +152,8 @@ export async function generateMetadata({
|
||||
.join(' | '),
|
||||
description: page.description ?? '',
|
||||
alternates: {
|
||||
canonical: absoluteHref(getPagePath(pages, page), true),
|
||||
// Trim trailing slashes in canonical URL to match the redirect behavior
|
||||
canonical: absoluteHref(getPagePath(pages, page), true).replace(/\/+$/, ''),
|
||||
},
|
||||
openGraph: {
|
||||
images: [
|
||||
|
||||
@@ -42,7 +42,7 @@ export default async function ContentLayout(props: { children: React.ReactNode }
|
||||
sections,
|
||||
} = await fetchContentData();
|
||||
|
||||
ReactDOM.preconnect(api().endpoint);
|
||||
ReactDOM.preconnect(api().client.endpoint);
|
||||
if (assetsDomain) {
|
||||
ReactDOM.preconnect(assetsDomain);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export async function highlight(block: DocumentBlockCode): Promise<HighlightLine
|
||||
|
||||
const lines = highlighter.codeToTokensBase(code, {
|
||||
lang: langName,
|
||||
tokenizeMaxLineLength: 120,
|
||||
tokenizeMaxLineLength: 400,
|
||||
});
|
||||
|
||||
let currentIndex = 0;
|
||||
|
||||
@@ -25,7 +25,11 @@ export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
|
||||
|
||||
return (
|
||||
/* Ensure images dont expand to the size of the container where this Image may be nested in. Now it's always nested in a size-restricted container */
|
||||
<span className={tcls(size !== 'line' ? ['inline-flex', 'max-w-[300px]'] : null)}>
|
||||
<span
|
||||
className={tcls(
|
||||
size !== 'line' ? ['inline-flex', 'max-w-[300px]', 'align-middle'] : null,
|
||||
)}
|
||||
>
|
||||
<Image
|
||||
alt={inline.data.caption ?? ''}
|
||||
sizes={await getImageSizes(size, src)}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
.light .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-300, 180 180 180)),
|
||||
rgb(var(--tint-color-300, 180 180 180)),
|
||||
rgb(var(--dark-base, 23 23 23)) 96%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
@@ -23,12 +23,12 @@
|
||||
--scalar-background-1: rgb(var(--light-base, 255 255 255));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-800, 30 30 30)),
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 96%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-800, 30 30 30)),
|
||||
rgb(var(--tint-color-800, 30 30 30)),
|
||||
var(--scalar-background-1) 90%
|
||||
);
|
||||
--scalar-background-accent: #007d9c1f;
|
||||
@@ -66,7 +66,7 @@
|
||||
.dark .scalar {
|
||||
--scalar-color-1: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700, 70 70 70)),
|
||||
rgb(var(--tint-color-700, 70 70 70)),
|
||||
rgb(var(--light-base, 255 255 255)) 100%
|
||||
);
|
||||
--scalar-color-2: color-mix(
|
||||
@@ -84,12 +84,12 @@
|
||||
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
|
||||
--scalar-background-2: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-200, 200 200 200)),
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 92%
|
||||
);
|
||||
--scalar-background-3: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-200, 200 200 200)),
|
||||
rgb(var(--tint-color-200, 200 200 200)),
|
||||
var(--scalar-background-1) 88%
|
||||
);
|
||||
--scalar-background-accent: #8ab4f81f;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ContentRef, DocumentBlockTable } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import assertNever from 'assert-never';
|
||||
|
||||
import { Checkbox, Emoji } from '@/components/primitives';
|
||||
import { Checkbox } from '@/components/primitives';
|
||||
import { StyledLink } from '@/components/primitives';
|
||||
import { Image } from '@/components/utils';
|
||||
import { getNodeFragmentByName } from '@/lib/document';
|
||||
|
||||
@@ -1,44 +1,43 @@
|
||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import React from 'react';
|
||||
|
||||
import { RecordColumnValue } from './RecordColumnValue';
|
||||
import { TableRecordKV, TableViewProps } from './Table';
|
||||
import styles from './table.module.css';
|
||||
import { getColumnWidth } from './ViewGrid';
|
||||
|
||||
export async function RecordRow(
|
||||
export function RecordRow(
|
||||
props: TableViewProps<DocumentTableViewGrid> & {
|
||||
record: TableRecordKV;
|
||||
autoSizedColumns: string[];
|
||||
fixedColumns: string[];
|
||||
},
|
||||
) {
|
||||
const { view } = props;
|
||||
const columnsLengthThreshold = view.columns.length >= 7;
|
||||
|
||||
const tableTR = columnsLengthThreshold
|
||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
||||
: ['[&>*+*]:border-l', '[&>*+*]:pl-4'];
|
||||
const { view, autoSizedColumns, fixedColumns } = props;
|
||||
|
||||
return (
|
||||
<tr className={tcls(tableTR, 'border-dark/3', 'dark:border-light/2')}>
|
||||
<div className={styles.row} role="row">
|
||||
{view.columns.map((column) => {
|
||||
const columnWidth = getColumnWidth({
|
||||
column,
|
||||
columnWidths: view.columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
});
|
||||
return (
|
||||
<td
|
||||
<div
|
||||
key={column}
|
||||
className={tcls(
|
||||
'align-middle',
|
||||
'min-w-[8rem]',
|
||||
'border-dark/2',
|
||||
'py-3',
|
||||
'text-sm',
|
||||
'lg:text-base',
|
||||
'dark:border-light/2',
|
||||
)}
|
||||
role="cell"
|
||||
className={styles.cell}
|
||||
style={{
|
||||
width: columnWidth,
|
||||
minWidth: columnWidth || '100px',
|
||||
}}
|
||||
>
|
||||
<div className={tcls('pr-4 ', 'text-balance')}>
|
||||
<RecordColumnValue key={column} {...props} column={column} />
|
||||
</div>
|
||||
</td>
|
||||
<RecordColumnValue {...props} column={column} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { DocumentTableViewGrid } from '@gitbook/api';
|
||||
import * as React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
@@ -7,159 +8,113 @@ import { TableViewProps } from './Table';
|
||||
import styles from './table.module.css';
|
||||
import { getColumnAlignment } from './utils';
|
||||
|
||||
/* Columns are sized in 3 ways:
|
||||
1. Set to auto-size by default, these columns share the available width
|
||||
2. Explicitly set by the user by dragging column separator (we then turn off auto-size)
|
||||
3. Auto-size is turned off without setting a width, we then default to a fixed width of 100px
|
||||
*/
|
||||
export function ViewGrid(props: TableViewProps<DocumentTableViewGrid>) {
|
||||
const { block, view, records, style } = props;
|
||||
const columnsOverThreshold = view.columns.length >= 7;
|
||||
|
||||
const tableWrapper = columnsOverThreshold
|
||||
? [
|
||||
// has over X columns
|
||||
'overflow-x-auto',
|
||||
'overflow-y-hidden',
|
||||
'mx-auto',
|
||||
'rounded-md',
|
||||
'border',
|
||||
'border-dark/3',
|
||||
'dark:border-light/2',
|
||||
]
|
||||
: ['overflow-x-auto', 'overflow-y-hidden', 'mx-auto'];
|
||||
/* Calculate how many columns are auto-sized vs fixed width */
|
||||
const columnWidths = view.columnWidths;
|
||||
const autoSizedColumns = view.columns.filter((column) => !columnWidths?.[column]);
|
||||
const fixedColumns = view.columns.filter((column) => columnWidths?.[column]);
|
||||
|
||||
const tableTR = columnsOverThreshold
|
||||
? ['[&>*+*]:border-l', '[&>*]:px-4']
|
||||
: ['[&>*+*]:border-l', '[&>*+*]:px-4'];
|
||||
const tableWidth = autoSizedColumns.length > 0 ? 'w-full' : 'w-fit';
|
||||
|
||||
const tableTH = columnsOverThreshold ? ['py-3'] : ['py-1', 'pt-0'];
|
||||
|
||||
// Only show the header when configured and not empty
|
||||
/* Only show the header when configured and not empty */
|
||||
const withHeader =
|
||||
!view.hideHeader &&
|
||||
view.columns.some((columnId) => block.data.definition[columnId].title.trim().length > 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${tcls(style, 'relative', 'grid', tableWrapper, styles.progressContainer)}`}
|
||||
>
|
||||
{/* ProgressScroller: */}
|
||||
<div
|
||||
className={`${styles.progressOpacitySharp} ${tcls(
|
||||
'grid',
|
||||
'items-center',
|
||||
'grid-area-1-1',
|
||||
'w-[5rem]',
|
||||
'h-full',
|
||||
'top-0',
|
||||
'z-[1]',
|
||||
'sticky',
|
||||
'left-[calc(100%-5rem)]',
|
||||
'pointer-events-none',
|
||||
)}`}
|
||||
>
|
||||
<svg
|
||||
className={`${styles.progressSvg} ${tcls(
|
||||
'grid-area-1-1',
|
||||
'relative',
|
||||
'[strokeDasharray:_0_100]',
|
||||
'z-[1]',
|
||||
'w-7',
|
||||
'mt-3',
|
||||
'mr-3',
|
||||
'self-start',
|
||||
'justify-self-end',
|
||||
'stroke-primary-600',
|
||||
'shadow-1xs',
|
||||
'bg-light',
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'rounded-full',
|
||||
'ring-dark/2',
|
||||
'dark:ring-light/2',
|
||||
'dark:bg-dark',
|
||||
'dark:stroke-primary-400',
|
||||
)}`}
|
||||
preserveAspectRatio="xMaxYMid meet"
|
||||
width="100%"
|
||||
viewBox="0 0 26 26"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<circle
|
||||
cx="13"
|
||||
className={`${styles.strokeOpacityProgressInverted}`}
|
||||
cy="13"
|
||||
r="12.5"
|
||||
fill="none"
|
||||
stroke="inherit"
|
||||
strokeWidth="1.5"
|
||||
pathLength="100"
|
||||
strokeLinecap="round"
|
||||
strokeOpacity={0}
|
||||
/>
|
||||
|
||||
<path
|
||||
strokeDasharray="none"
|
||||
d="M12 10L15 13L12 16"
|
||||
stroke="inherit"
|
||||
fill="none"
|
||||
strokeOpacity={0.64}
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<div
|
||||
className={`${styles.progressOpacity} ${tcls(
|
||||
'bg-gradient-to-r',
|
||||
'from-transparent',
|
||||
'to-light',
|
||||
'to-40%',
|
||||
'grid-area-1-1',
|
||||
'w-full',
|
||||
'h-full',
|
||||
'dark:from-transparent',
|
||||
'dark:to-dark/10',
|
||||
)}`}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
{/* Table: */}
|
||||
<table className={tcls('w-full', 'grid-area-1-1', 'table-auto')}>
|
||||
{withHeader ? (
|
||||
<thead>
|
||||
<tr className={tcls(tableTR)}>
|
||||
<div className={tcls(style, styles.tableWrapper)}>
|
||||
{/* Table */}
|
||||
<div role="table" className={tcls('flex', 'flex-col')}>
|
||||
{/* Header */}
|
||||
{withHeader && (
|
||||
<div
|
||||
role="rowgroup"
|
||||
className={tcls(
|
||||
tableWidth,
|
||||
styles.rowGroup,
|
||||
'straight-corners:rounded-none',
|
||||
)}
|
||||
>
|
||||
<div role="row" className={tcls('flex', 'w-full')}>
|
||||
{view.columns.map((column) => {
|
||||
const columnWidth = view.columnWidths?.[column];
|
||||
const alignment = getColumnAlignment(block.data.definition[column]);
|
||||
|
||||
return (
|
||||
<th
|
||||
<div
|
||||
key={column}
|
||||
role="columnheader"
|
||||
className={tcls(
|
||||
tableTH,
|
||||
'align-middle',
|
||||
'text-balance',
|
||||
'border-b',
|
||||
'border-b-dark/5',
|
||||
'text-left',
|
||||
'text-xs',
|
||||
'lg:text-base',
|
||||
'dark:border-l-light/2',
|
||||
'dark:border-b-light/4',
|
||||
styles.columnHeader,
|
||||
alignment === 'right' ? 'text-right' : null,
|
||||
alignment === 'center' ? 'text-center' : null,
|
||||
)}
|
||||
style={columnWidth ? { width: columnWidth } : undefined}
|
||||
style={{
|
||||
width: getColumnWidth({
|
||||
column,
|
||||
columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
}),
|
||||
minWidth: columnWidths?.[column] || '100px',
|
||||
}}
|
||||
title={block.data.definition[column].title}
|
||||
>
|
||||
{block.data.definition[column].title}
|
||||
</th>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
) : null}
|
||||
<tbody className={tcls('[&>*+*]:border-t')}>
|
||||
{records.map((record) => {
|
||||
return <RecordRow key={record[0]} {...props} record={record} />;
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
role="rowgroup"
|
||||
className={tcls('flex', 'flex-col', tableWidth, '[&>*+*]:border-t')}
|
||||
>
|
||||
{records.map((record) => (
|
||||
<RecordRow
|
||||
key={record[0]}
|
||||
record={record}
|
||||
autoSizedColumns={autoSizedColumns}
|
||||
fixedColumns={fixedColumns}
|
||||
{...props}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const getColumnWidth = ({
|
||||
column,
|
||||
columnWidths,
|
||||
autoSizedColumns,
|
||||
fixedColumns,
|
||||
}: {
|
||||
column: string;
|
||||
columnWidths: Record<string, number> | undefined;
|
||||
autoSizedColumns: string[];
|
||||
fixedColumns: string[];
|
||||
}) => {
|
||||
const columnWidth = columnWidths?.[column];
|
||||
|
||||
/* Column was explicitly set by user or user turned off auto-sizing (in that case, columnWidth should've also been set to 100px) */
|
||||
if (columnWidth) return `${columnWidth}px`;
|
||||
|
||||
/* Fallback minimum width for columns, so the columns don't become unreadable from being too narrow and instead table will become scrollable. */
|
||||
const minAutoColumnWidth = '100px';
|
||||
|
||||
const totalFixedWidth = fixedColumns.reduce((sum, col) => {
|
||||
return sum + (columnWidths?.[col] || 0);
|
||||
}, 0);
|
||||
|
||||
/* Column should use auto-sizing, which means it grows to fill available space */
|
||||
const availableWidth = `calc((100% - ${totalFixedWidth}px) / ${autoSizedColumns.length})`;
|
||||
return `clamp(${minAutoColumnWidth}, ${availableWidth}, 100%)`;
|
||||
};
|
||||
|
||||
@@ -1,87 +1,59 @@
|
||||
/* Hide it on browsers (firefox / safari) that do not support it */
|
||||
.progressOpacitySharp {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@supports (animation-timeline: scroll()) {
|
||||
.progressContainer {
|
||||
scroll-timeline-name: --squareTimeline;
|
||||
scroll-timeline-axis: x;
|
||||
}
|
||||
|
||||
.progressOpacity {
|
||||
animation-name: opacityProgress;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.progressOpacitySharp {
|
||||
display: grid;
|
||||
opacity: 0;
|
||||
animation-name: opacityProgressSharp;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.strokeOpacityProgressInverted {
|
||||
animation-name: strokeOpacityProgressInverted;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
.progressSvg {
|
||||
animation-name: svgProgress;
|
||||
animation-duration: 1ms;
|
||||
animation-direction: alternate;
|
||||
animation-timeline: --squareTimeline;
|
||||
animation-timing-function: linear;
|
||||
}
|
||||
|
||||
@keyframes opacityProgress {
|
||||
0%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes opacityProgressSharp {
|
||||
0%,
|
||||
98% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes strokeOpacityProgressInverted {
|
||||
0%,
|
||||
10% {
|
||||
stroke-opacity: 0;
|
||||
}
|
||||
30% {
|
||||
stroke-opacity: 0.88;
|
||||
}
|
||||
100% {
|
||||
stroke-opacity: 0.88;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes svgProgress {
|
||||
from {
|
||||
stroke-dasharray: 0 100;
|
||||
}
|
||||
to {
|
||||
stroke-dasharray: 100 100;
|
||||
}
|
||||
/* Detect whether a scrollbar exists on the table */
|
||||
@keyframes detect-scroll {
|
||||
from,
|
||||
to {
|
||||
--can-scroll: ;
|
||||
}
|
||||
}
|
||||
|
||||
/* Apply styles to the Table if scrollbar exists */
|
||||
.tableWrapper {
|
||||
animation: detect-scroll linear;
|
||||
animation-timeline: scroll(self x);
|
||||
|
||||
--border-radius-if-can-scroll: var(--can-scroll) 0.375rem;
|
||||
--border-radius-if-cant-scroll: 0;
|
||||
border-radius: var(--border-radius-if-can-scroll, var(--border-radius-if-cant-scroll));
|
||||
|
||||
--border-width-if-can-scroll: var(--can-scroll) 1px;
|
||||
--border-width-if-cant-scroll: 0;
|
||||
border-width: var(--border-width-if-can-scroll, var(--border-width-if-cant-scroll));
|
||||
|
||||
@apply relative grid w-full overflow-x-auto overflow-y-hidden mx-auto border-dark/3;
|
||||
}
|
||||
|
||||
:global(.dark) .tableWrapper {
|
||||
@apply border-tint-50;
|
||||
}
|
||||
|
||||
.columnHeader {
|
||||
@apply text-sm font-medium py-3 px-4 text-tint-900;
|
||||
}
|
||||
|
||||
:global(.dark) .columnHeader {
|
||||
@apply text-white;
|
||||
}
|
||||
|
||||
.row {
|
||||
@apply flex border-tint-700/2;
|
||||
}
|
||||
|
||||
:global(.dark) .row {
|
||||
@apply border-tint-300/3;
|
||||
}
|
||||
|
||||
.rowGroup {
|
||||
@apply flex flex-col border rounded-lg bg-tint-800/1 border-tint-700/2;
|
||||
}
|
||||
|
||||
:global(.dark) .rowGroup {
|
||||
@apply bg-tint-300/2 border-tint-300/3;
|
||||
}
|
||||
|
||||
.cell {
|
||||
@apply flex-1 align-middle border-dark/2 py-2 px-4 text-sm;
|
||||
}
|
||||
|
||||
:global(.dark) .cell {
|
||||
@apply border-light/2;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export function Dropdown<E extends HTMLElement>(props: {
|
||||
const dropdownId = useId();
|
||||
|
||||
return (
|
||||
<div className={tcls('group/dropdown', 'relative flex')}>
|
||||
<div className={tcls('group/dropdown', 'relative flex shrink min-w-0')}>
|
||||
{button({
|
||||
id: dropdownId,
|
||||
tabIndex: 0,
|
||||
@@ -39,7 +39,7 @@ export function Dropdown<E extends HTMLElement>(props: {
|
||||
aria-labelledby={dropdownId}
|
||||
className={tcls(
|
||||
'w-52',
|
||||
'max-h-56',
|
||||
'max-h-80',
|
||||
'flex',
|
||||
'absolute',
|
||||
'top-full',
|
||||
@@ -111,31 +111,38 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
|
||||
* Menu item in a dropdown.
|
||||
*/
|
||||
export function DropdownMenuItem(props: {
|
||||
href: string;
|
||||
href: string | null;
|
||||
active?: boolean;
|
||||
className?: ClassValue;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { children, active = false, href } = props;
|
||||
const { children, active = false, href, className } = props;
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
prefetch={false}
|
||||
className={tcls(
|
||||
'px-3 py-1 text-sm rounded straight-corners:rounded-sm',
|
||||
active ? 'bg-primary/3 dark:bg-light/2 text-primary-600' : null,
|
||||
'hover:bg-dark/2 dark:hover:bg-light/2',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
prefetch={false}
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'text-sm',
|
||||
'px-3',
|
||||
'py-1',
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
active
|
||||
? ['bg-primary/3', 'dark:bg-light/2', 'text-primary-600']
|
||||
: ['hover:bg-dark/2', 'dark:hover:bg-light/2'],
|
||||
'text-xs px-3 py-1 font-medium text-dark/8 dark:text-light/8',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { HeaderLogo } from './HeaderLogo';
|
||||
import { SpacesDropdown } from './SpacesDropdown';
|
||||
import { SearchButton } from '../Search';
|
||||
import { SiteSectionTabs } from '../SiteSectionTabs';
|
||||
import { HeaderMobileMenu } from './HeaderMobileMenu';
|
||||
/**
|
||||
* Render the header for the space.
|
||||
*/
|
||||
@@ -45,104 +46,156 @@ export function Header(props: {
|
||||
'w-full',
|
||||
'flex-none',
|
||||
'shadow-thinbottom',
|
||||
'dark:shadow-light/2',
|
||||
'bg-light',
|
||||
'dark:bg-dark',
|
||||
withTopHeader ? null : 'lg:hidden',
|
||||
'lg:z-10',
|
||||
'dark:shadow-light/1',
|
||||
`${isCustomizationDefault || !withTopHeader ? 'bg-light' : 'bg-header-background'}`,
|
||||
`${
|
||||
isCustomizationDefault || !withTopHeader
|
||||
? 'dark:bg-dark'
|
||||
: 'bg-header-background'
|
||||
}`,
|
||||
'text-sm',
|
||||
'bg-opacity-9',
|
||||
'dark:bg-opacity-9',
|
||||
'backdrop-blur-lg',
|
||||
'contrast-more:bg-opacity-11',
|
||||
'contrast-more:dark:bg-opacity-11',
|
||||
)}
|
||||
>
|
||||
<div className={tcls('scroll-nojump')}>
|
||||
<div
|
||||
className={tcls(
|
||||
'gap-4',
|
||||
'grid',
|
||||
'grid-flow-col',
|
||||
'auto-cols-[auto_auto_1fr_auto]',
|
||||
'h-16',
|
||||
'items-center',
|
||||
'align-center',
|
||||
'justify-between',
|
||||
'w-full',
|
||||
CONTAINER_STYLE,
|
||||
)}
|
||||
>
|
||||
<HeaderLogo site={site} space={space} customization={customization} />
|
||||
<div className="z-20">
|
||||
{!hasSiteSections && isMultiVariants ? (
|
||||
<SpacesDropdown space={space} spaces={spaces} />
|
||||
) : null}
|
||||
</div>
|
||||
<HeaderLinks>
|
||||
{customization.header.links.map((link, index) => {
|
||||
return (
|
||||
<HeaderLink
|
||||
key={index}
|
||||
link={link}
|
||||
<div
|
||||
className={tcls(
|
||||
!isCustomizationDefault &&
|
||||
withTopHeader && [
|
||||
'bg-header-background',
|
||||
'shadow-thinbottom',
|
||||
'dark:shadow-light/2',
|
||||
],
|
||||
)}
|
||||
>
|
||||
<div className={tcls('scroll-nojump')}>
|
||||
<div
|
||||
className={tcls(
|
||||
'gap-4',
|
||||
'lg:gap-8',
|
||||
'flex',
|
||||
'h-16',
|
||||
'items-center',
|
||||
'justify-between',
|
||||
'w-full',
|
||||
CONTAINER_STYLE,
|
||||
)}
|
||||
>
|
||||
<div className="flex max-w-full shrink min-w-0 gap-2 lg:gap-4 justify-start items-center">
|
||||
<HeaderMobileMenu
|
||||
className={tcls(
|
||||
'lg:hidden',
|
||||
'-ml-2',
|
||||
customization.header.preset ===
|
||||
CustomizationHeaderPreset.Default
|
||||
? ['text-dark', 'dark:text-light']
|
||||
: 'text-header-link',
|
||||
)}
|
||||
/>
|
||||
<HeaderLogo site={site} space={space} customization={customization} />
|
||||
{!hasSiteSections && isMultiVariants ? (
|
||||
<div className="z-20 shrink hidden sm:block">
|
||||
<SpacesDropdown space={space} spaces={spaces} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{customization.header.links.length > 0 && (
|
||||
<HeaderLinks>
|
||||
{customization.header.links.map((link, index) => {
|
||||
return (
|
||||
<HeaderLink
|
||||
key={index}
|
||||
link={link}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<HeaderLinkMore
|
||||
label={t(getSpaceLanguage(customization), 'more')}
|
||||
links={customization.header.links}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<HeaderLinkMore
|
||||
label={t(getSpaceLanguage(customization), 'more')}
|
||||
links={customization.header.links}
|
||||
context={context}
|
||||
customization={customization}
|
||||
/>
|
||||
</HeaderLinks>
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'md:w-56',
|
||||
'grow-0',
|
||||
'shrink-0',
|
||||
'justify-self-end',
|
||||
</HeaderLinks>
|
||||
)}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<SearchButton
|
||||
style={
|
||||
!isCustomizationDefault && withTopHeader
|
||||
? [
|
||||
'bg-header-link/3',
|
||||
'shadow-sm',
|
||||
'ring-header-link/3',
|
||||
'[&>span]:!text-header-link/7',
|
||||
'[&_svg]:text-header-link',
|
||||
'contrast-more:bg-transparent',
|
||||
'contrast-more:ring-header-link',
|
||||
'contrast-more:[&>span]:!text-header-link',
|
||||
'dark:bg-header-link/3',
|
||||
'dark:ring-header-link/3',
|
||||
'[&>span]:!text-header-link/7',
|
||||
'dark:[&_svg]:text-header-link',
|
||||
'dark:contrast-more:bg-transparent',
|
||||
'dark:contrast-more:ring-header-link',
|
||||
'dark:contrast-more:[&>span]:!text-header-link',
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<span className={tcls('flex-1')}>
|
||||
{t(
|
||||
getSpaceLanguage(customization),
|
||||
customization.aiSearch.enabled ? 'search_or_ask' : 'search',
|
||||
)}
|
||||
</span>
|
||||
</SearchButton>
|
||||
</Suspense>
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'md:min-w-56',
|
||||
'grow-0',
|
||||
'shrink-0',
|
||||
'justify-self-end',
|
||||
)}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<SearchButton
|
||||
style={
|
||||
!isCustomizationDefault && withTopHeader
|
||||
? [
|
||||
'bg-header-link/2',
|
||||
'dark:bg-header-link/2',
|
||||
'hover:bg-header-link/3',
|
||||
'dark:hover:bg-header-link/3',
|
||||
|
||||
'text-header-link/8',
|
||||
'dark:text-header-link/8',
|
||||
'hover:text-header-link',
|
||||
'dark:hover:text-header-link',
|
||||
|
||||
'ring-header-link/4',
|
||||
'dark:ring-header-link/4',
|
||||
'hover:ring-header-link/5',
|
||||
'dark:hover:ring-header-link/5',
|
||||
|
||||
'[&_svg]:text-header-link/10',
|
||||
'dark:[&_svg]:text-header-link/10',
|
||||
'[&_.shortcut]:text-header-link/8',
|
||||
'dark:[&_.shortcut]:text-header-link/8',
|
||||
|
||||
'contrast-more:bg-header-background',
|
||||
'contrast-more:text-header-link',
|
||||
'contrast-more:ring-header-link',
|
||||
'contrast-more:hover:bg-header-background',
|
||||
'contrast-more:hover:ring-header-link',
|
||||
'contrast-more:focus:text-header-link',
|
||||
'contrast-more:focus:bg-header-background',
|
||||
'contrast-more:focus:ring-header-link',
|
||||
'dark:contrast-more:bg-header-background',
|
||||
'dark:contrast-more:text-header-link',
|
||||
'dark:contrast-more:ring-header-link',
|
||||
'dark:contrast-more:hover:bg-header-background',
|
||||
'dark:contrast-more:hover:ring-header-link',
|
||||
'dark:contrast-more:focus:text-header-link',
|
||||
'dark:contrast-more:focus:bg-header-background',
|
||||
'dark:contrast-more:focus:ring-header-link',
|
||||
|
||||
'shadow-none',
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<span className={tcls('flex-1')}>
|
||||
{t(
|
||||
getSpaceLanguage(customization),
|
||||
customization.aiSearch.enabled
|
||||
? 'search_or_ask'
|
||||
: 'search',
|
||||
)}
|
||||
...
|
||||
</span>
|
||||
</SearchButton>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{sections ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark mt-0.5',
|
||||
'scroll-nojump',
|
||||
'w-full',
|
||||
// Handle long section tabs, particularly on smaller screens.
|
||||
'overflow-x-auto hide-scroll',
|
||||
)}
|
||||
|
||||
@@ -33,6 +33,7 @@ export async function HeaderLink(props: {
|
||||
if (link.links && link.links.length > 0) {
|
||||
return (
|
||||
<Dropdown
|
||||
className="shrink"
|
||||
button={(buttonProps) => {
|
||||
if (!target) {
|
||||
return (
|
||||
@@ -104,7 +105,7 @@ function HeaderItemButton(
|
||||
linkStyle: 'button-secondary' | 'button-primary';
|
||||
},
|
||||
) {
|
||||
const { linkStyle, headerPreset, title, href, ...rest } = props;
|
||||
const { linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
|
||||
const variant = (() => {
|
||||
switch (linkStyle) {
|
||||
case 'button-secondary':
|
||||
@@ -147,12 +148,9 @@ function HeaderItemButton(
|
||||
|
||||
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
|
||||
return tcls(
|
||||
'overflow-hidden',
|
||||
'text-sm lg:text-base',
|
||||
'flex flex-row items-center',
|
||||
'whitespace-nowrap',
|
||||
'flex items-center shrink',
|
||||
'hover:text-header-link-400 dark:hover:text-light',
|
||||
'truncate',
|
||||
'min-w-0',
|
||||
|
||||
props.headerPreset === CustomizationHeaderPreset.Default
|
||||
? ['text-dark/8', 'dark:text-light/8']
|
||||
@@ -164,7 +162,7 @@ function HeaderItemLink(props: HeaderLinkNavItemProps) {
|
||||
const { headerPreset, title, isDropdown, href, ...rest } = props;
|
||||
return (
|
||||
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
|
||||
{title}
|
||||
<span className="truncate min-w-0">{title}</span>
|
||||
{isDropdown ? <DropdownChevron /> : null}
|
||||
</Link>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
CustomizationContentLink,
|
||||
CustomizationHeaderItem,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationSettings,
|
||||
@@ -10,10 +11,9 @@ import React from 'react';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||
import { Dropdown, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||
import styles from './headerLinks.module.css';
|
||||
|
||||
|
||||
/**
|
||||
* Dropdown menu for header links hidden at small screen size.
|
||||
*/
|
||||
@@ -31,15 +31,22 @@ export function HeaderLinkMore(props: {
|
||||
const renderButton = () => (
|
||||
<button
|
||||
className={tcls(
|
||||
'px-1',
|
||||
!isCustomizationDefault
|
||||
? ['text-header-link-500']
|
||||
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
|
||||
'hover:text-header-link-400',
|
||||
isCustomizationDefault
|
||||
? [
|
||||
'text-dark/8',
|
||||
'dark:text-light/8',
|
||||
'hover:text-primary',
|
||||
'dark:hover:text-primary',
|
||||
]
|
||||
: ['text-header-link', 'hover:text-header-link/8'],
|
||||
'flex',
|
||||
'gap-1',
|
||||
'items-center',
|
||||
)}
|
||||
>
|
||||
<span className="sr-only">{label}</span>
|
||||
<Icon icon="ellipsis" className={tcls('opacity-6', 'size-3', 'ms-1')} />
|
||||
<Icon icon="ellipsis" className={tcls('size-4')} />
|
||||
<DropdownChevron />
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -56,14 +63,25 @@ export function HeaderLinkMore(props: {
|
||||
);
|
||||
}
|
||||
|
||||
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderItem }) {
|
||||
async function MoreMenuLink(props: {
|
||||
context: ContentRefContext;
|
||||
link: CustomizationHeaderItem | CustomizationContentLink;
|
||||
}) {
|
||||
const { context, link } = props;
|
||||
|
||||
const target = link.to ? await resolveContentRef(link.to, context) : null;
|
||||
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <DropdownMenuItem href={target.href}>{link.title}</DropdownMenuItem>;
|
||||
return (
|
||||
<>
|
||||
{'links' in link && link.links.length > 0 && (
|
||||
<hr className="first:hidden border-t border-light-3 dark:border-dark-3 my-1 -mx-2" />
|
||||
)}
|
||||
<DropdownMenuItem href={target?.href ?? null}>{link.title}</DropdownMenuItem>
|
||||
{'links' in link
|
||||
? link.links.map((subLink, index) => (
|
||||
<MoreMenuLink key={index} {...props} link={subLink} />
|
||||
))
|
||||
: null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export async function HeaderLinks({ children }: HeaderLinksProps) {
|
||||
<div
|
||||
className={tcls(
|
||||
styles.containerHeaderlinks,
|
||||
'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56 z-20',
|
||||
'grow shrink flex justify-end items-center gap-x-6 min-w-9 z-20',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -30,65 +30,51 @@ export function HeaderLogo(props: HeaderLogoProps) {
|
||||
const { customization } = props;
|
||||
|
||||
return (
|
||||
<div className={tcls('flex', 'flex-row', 'gap-2')}>
|
||||
<HeaderMobileMenu
|
||||
className={tcls(
|
||||
'lg:hidden',
|
||||
customization.header.preset === CustomizationHeaderPreset.Default
|
||||
? ['text-dark', 'dark:text-light']
|
||||
: 'text-header-link',
|
||||
)}
|
||||
/>
|
||||
<Link
|
||||
href={absoluteHref('')}
|
||||
className={tcls(
|
||||
'group/headerlogo',
|
||||
'flex-1',
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'shrink-0',
|
||||
)}
|
||||
>
|
||||
{customization.header.logo ? (
|
||||
<Image
|
||||
alt="Logo"
|
||||
sources={{
|
||||
light: {
|
||||
src: customization.header.logo.light,
|
||||
},
|
||||
dark: customization.header.logo.dark
|
||||
? {
|
||||
src: customization.header.logo.dark,
|
||||
}
|
||||
: null,
|
||||
}}
|
||||
sizes={[
|
||||
{
|
||||
media: '(max-width: 1024px)',
|
||||
width: 128,
|
||||
},
|
||||
{
|
||||
width: 192,
|
||||
},
|
||||
]}
|
||||
priority="high"
|
||||
style={tcls(
|
||||
'max-w-[8rem]',
|
||||
'lg:max-w-[12rem]',
|
||||
'max-h-[3rem]',
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
'overflow-hidden',
|
||||
'object-contain',
|
||||
'object-left',
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<LogoFallback {...props} />
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
<Link
|
||||
href={absoluteHref('')}
|
||||
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')}
|
||||
>
|
||||
{customization.header.logo ? (
|
||||
<Image
|
||||
alt="Logo"
|
||||
sources={{
|
||||
light: {
|
||||
src: customization.header.logo.light,
|
||||
},
|
||||
dark: customization.header.logo.dark
|
||||
? {
|
||||
src: customization.header.logo.dark,
|
||||
}
|
||||
: null,
|
||||
}}
|
||||
sizes={[
|
||||
{
|
||||
media: '(max-width: 1024px)',
|
||||
width: 160,
|
||||
},
|
||||
{
|
||||
width: 260,
|
||||
},
|
||||
]}
|
||||
priority="high"
|
||||
style={tcls(
|
||||
'rounded',
|
||||
'straight-corners:rounded-sm',
|
||||
'overflow-hidden',
|
||||
'shrink',
|
||||
'min-w-0',
|
||||
'max-w-40',
|
||||
'lg:max-w-64',
|
||||
'max-h-10',
|
||||
'lg:max-h-12',
|
||||
'h-full',
|
||||
'w-auto',
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<LogoFallback {...props} />
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -111,13 +97,13 @@ function LogoFallback(props: HeaderLogoProps) {
|
||||
className={tcls(
|
||||
'text-pretty',
|
||||
'line-clamp-3',
|
||||
'leading-[1.1]',
|
||||
'tracking-tight',
|
||||
'max-w-[18ch]',
|
||||
'lg:max-w-[24ch]',
|
||||
'lg:text-lg/tight',
|
||||
'font-semibold',
|
||||
'ms-3',
|
||||
'text-base/tight',
|
||||
'lg:text-lg/tight',
|
||||
customization.header.preset === CustomizationHeaderPreset.Default ||
|
||||
customization.header.preset === CustomizationHeaderPreset.None
|
||||
? ['text-dark', 'dark:text-light']
|
||||
|
||||
@@ -5,8 +5,8 @@ import { tcls } from '@/lib/tailwind';
|
||||
import { Dropdown, DropdownChevron, DropdownMenu } from './Dropdown';
|
||||
import { SpacesDropdownMenuItem } from './SpacesDropdownMenuItem';
|
||||
|
||||
export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
const { space, spaces } = props;
|
||||
export function SpacesDropdown(props: { space: Space; spaces: Space[]; className?: string }) {
|
||||
const { space, spaces, className } = props;
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
@@ -20,25 +20,27 @@ export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
'items-center',
|
||||
'rounded-2xl',
|
||||
'straight-corners:rounded-none',
|
||||
'bg-light-2',
|
||||
'border',
|
||||
'border-light-3',
|
||||
'text-dark-4',
|
||||
|
||||
'hover:cursor-pointer',
|
||||
'bg-dark/1',
|
||||
'dark:bg-light/1',
|
||||
|
||||
'text-sm',
|
||||
'text-dark-4',
|
||||
'dark:text-light-4',
|
||||
|
||||
'contrast-more:bg-light',
|
||||
'contrast-more:ring-1',
|
||||
'contrast-more:ring-dark',
|
||||
'dark:contrast-more:ring-light',
|
||||
'dark:contrast-more:bg-dark',
|
||||
|
||||
'px-3',
|
||||
'py-1',
|
||||
'contrast-more:border-dark',
|
||||
'contrast-more:bg-light',
|
||||
'contrast-more:text-dark',
|
||||
'dark:bg-dark-3',
|
||||
'dark:border-dark-4',
|
||||
'dark:text-light-4',
|
||||
'contrast-more:dark:border-light',
|
||||
'contrast-more:dark:bg-dark',
|
||||
'contrast-more:dark:text-light',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{space.title}
|
||||
<span className="line-clamp-2">{space.title}</span>
|
||||
<DropdownChevron />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -60,12 +60,12 @@
|
||||
}
|
||||
.containerHeaderlinks > :nth-child(n + 5) ~ .linkEllipsis {
|
||||
display: flex;
|
||||
& div > :nth-child(n + 5) {
|
||||
& div > a:nth-of-type(n + 5) {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@container headerlinks ( width < 900px ) {
|
||||
@container headerlinks ( width < 850px ) {
|
||||
.containerHeaderlinks > :nth-child(n + 6) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getSpaceLanguage } from '@/intl/server';
|
||||
import { t } from '@/intl/translate';
|
||||
import { ContentTarget, SiteContentPointer, api } from '@/lib/api';
|
||||
import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
|
||||
import { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { shouldTrackPageViews } from '@/lib/tracking';
|
||||
@@ -31,6 +32,7 @@ export function PageBody(props: {
|
||||
contentTarget: ContentTarget;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
page: RevisionPageDocument;
|
||||
ancestors: AncestorRevisionPage[];
|
||||
document: JSONDocument | null;
|
||||
context: ContentRefContext;
|
||||
withPageFeedback: boolean;
|
||||
@@ -42,6 +44,7 @@ export function PageBody(props: {
|
||||
customization,
|
||||
context,
|
||||
page,
|
||||
ancestors,
|
||||
document,
|
||||
withPageFeedback,
|
||||
} = props;
|
||||
@@ -79,7 +82,7 @@ export function PageBody(props: {
|
||||
<PageCover as="hero" page={page} cover={page.cover} context={context} />
|
||||
) : null}
|
||||
|
||||
<PageHeader page={page} />
|
||||
<PageHeader page={page} ancestors={ancestors} pages={context.pages} />
|
||||
{document && !isNodeEmpty(document) ? (
|
||||
<React.Suspense
|
||||
fallback={
|
||||
@@ -148,7 +151,7 @@ export function PageBody(props: {
|
||||
sitePointer={pointer}
|
||||
spaceId={space.id}
|
||||
pageId={page.id}
|
||||
apiHost={api().endpoint}
|
||||
apiHost={api().client.endpoint}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
import { RevisionPageDocument } from '@gitbook/api';
|
||||
import { RevisionPage, RevisionPageDocument } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
|
||||
import { pageHref } from '@/lib/links';
|
||||
import { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { PageIcon } from '../PageIcon';
|
||||
import { StyledLink } from '../primitives';
|
||||
|
||||
export function PageHeader(props: { page: RevisionPageDocument }) {
|
||||
const { page } = props;
|
||||
export function PageHeader(props: {
|
||||
page: RevisionPageDocument;
|
||||
ancestors: AncestorRevisionPage[];
|
||||
pages: RevisionPage[];
|
||||
}) {
|
||||
const { page, ancestors, pages } = props;
|
||||
|
||||
if (!page.layout.title && !page.layout.description) {
|
||||
return null;
|
||||
@@ -15,6 +23,48 @@ export function PageHeader(props: { page: RevisionPageDocument }) {
|
||||
<header
|
||||
className={tcls('max-w-3xl', 'mx-auto', 'mb-6', 'space-y-3', 'page-api-block:ml-0')}
|
||||
>
|
||||
{ancestors.length > 0 && (
|
||||
<nav>
|
||||
<ol className={tcls('flex', 'flex-wrap', 'items-center', 'gap-2')}>
|
||||
{ancestors.map((breadcrumb, index) => (
|
||||
<>
|
||||
<li key={breadcrumb.id}>
|
||||
<StyledLink
|
||||
href={pageHref(pages, breadcrumb)}
|
||||
style={tcls(
|
||||
'no-underline',
|
||||
'hover:underline',
|
||||
'text-xs',
|
||||
'tracking-wide',
|
||||
'font-semibold',
|
||||
'uppercase',
|
||||
'flex',
|
||||
'items-center',
|
||||
'gap-1',
|
||||
)}
|
||||
>
|
||||
<PageIcon
|
||||
page={breadcrumb}
|
||||
style={tcls('size-4', 'text-base', 'leading-none')}
|
||||
/>
|
||||
{breadcrumb.title}
|
||||
</StyledLink>
|
||||
</li>
|
||||
{index != ancestors.length - 1 && (
|
||||
<Icon
|
||||
icon="chevron-right"
|
||||
className={tcls(
|
||||
'size-3',
|
||||
'text-light-4',
|
||||
'dark:text-dark-4',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
)}
|
||||
{page.layout.title ? (
|
||||
<h1 className={tcls('text-4xl', 'font-bold', 'flex', 'items-center', 'gap-4')}>
|
||||
<PageIcon page={page} style={['text-dark/6', 'dark:text-light/6']} />
|
||||
|
||||
@@ -18,7 +18,7 @@ export async function postPageFeedback(args: {
|
||||
`No siteSpaceId in pointer. organizationId: ${organizationId}, siteId: ${siteId}, pageId: ${args.pageId}`,
|
||||
);
|
||||
|
||||
await api().orgs.createSitesPageFeedback(
|
||||
await api().client.orgs.createSitesPageFeedback(
|
||||
organizationId,
|
||||
siteId,
|
||||
siteSpaceId,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {
|
||||
CustomizationBackground,
|
||||
CustomizationCorners,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationIconsStyle,
|
||||
CustomizationSettings,
|
||||
CustomizationTint,
|
||||
SiteCustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import { IconsProvider, IconStyle } from '@gitbook/icons';
|
||||
@@ -17,11 +17,13 @@ import { getStaticFileURL } from '@/lib/assets';
|
||||
import { hexToRgb, shadesOfColor } from '@/lib/colors';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { ClientContexts } from './ClientContexts';
|
||||
import { emojiFontClassName } from '../primitives';
|
||||
import { ClientContexts } from './ClientContexts';
|
||||
|
||||
import './globals.css';
|
||||
import '@gitbook/icons/style.css';
|
||||
import './globals.css';
|
||||
|
||||
const DEFAULT_TINT_COLOR = '#787878';
|
||||
|
||||
/**
|
||||
* Layout shared between the content and the PDF renderer.
|
||||
@@ -36,26 +38,21 @@ export async function CustomizationRootLayout(props: {
|
||||
const headerTheme = generateHeaderTheme(customization);
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
const tintColor = getTintColor(customization);
|
||||
|
||||
return (
|
||||
<html
|
||||
suppressHydrationWarning
|
||||
lang={customization.internationalization.locale}
|
||||
className={
|
||||
tcls(
|
||||
customization.header.preset === CustomizationHeaderPreset.None
|
||||
? null
|
||||
: [
|
||||
// Take the sticky header in consideration for the scrolling
|
||||
`scroll-pt-[76px]`,
|
||||
],
|
||||
) +
|
||||
(customization.styling.corners === CustomizationCorners.Straight
|
||||
className={tcls(
|
||||
customization.header.preset === CustomizationHeaderPreset.None
|
||||
? null
|
||||
: 'scroll-pt-[76px]', // Take the sticky header in consideration for the scrolling
|
||||
customization.styling.corners === CustomizationCorners.Straight
|
||||
? ' straight-corners'
|
||||
: '') +
|
||||
(customization.styling.background === CustomizationBackground.Plain
|
||||
? ' plain-background'
|
||||
: '')
|
||||
}
|
||||
: '',
|
||||
tintColor ? ' tint' : 'no-tint',
|
||||
)}
|
||||
>
|
||||
<head>
|
||||
{customization.privacyPolicy.url ? (
|
||||
@@ -87,10 +84,22 @@ export async function CustomizationRootLayout(props: {
|
||||
)
|
||||
}
|
||||
|
||||
${generateColorVariable(
|
||||
'primary-base',
|
||||
customization.styling.primaryColor.light,
|
||||
)}
|
||||
${generateColorVariable('tint-color', tintColor?.light ?? DEFAULT_TINT_COLOR)}
|
||||
${
|
||||
// Generate the right contrast color for each shade of tint-color
|
||||
generateColorVariable(
|
||||
'contrast-tint',
|
||||
Object.fromEntries(
|
||||
Object.entries(
|
||||
shadesOfColor(tintColor?.light || DEFAULT_TINT_COLOR),
|
||||
).map(([index, color]) => [
|
||||
index,
|
||||
colorContrast(color, ['#000', '#fff']),
|
||||
]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
${generateColorVariable(
|
||||
'header-background',
|
||||
headerTheme.backgroundColor.light,
|
||||
@@ -103,10 +112,6 @@ export async function CustomizationRootLayout(props: {
|
||||
'primary-color',
|
||||
customization.styling.primaryColor.dark,
|
||||
)}
|
||||
${generateColorVariable(
|
||||
'primary-base',
|
||||
customization.styling.primaryColor.dark,
|
||||
)}
|
||||
${
|
||||
// Generate the right contrast color for each shade of primary-color
|
||||
generateColorVariable(
|
||||
@@ -121,6 +126,23 @@ export async function CustomizationRootLayout(props: {
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
${generateColorVariable('tint-color', tintColor?.dark ?? DEFAULT_TINT_COLOR)}
|
||||
${
|
||||
// Generate the right contrast color for each shade of tint-color
|
||||
generateColorVariable(
|
||||
'contrast-tint',
|
||||
Object.fromEntries(
|
||||
Object.entries(
|
||||
shadesOfColor(tintColor?.dark || DEFAULT_TINT_COLOR),
|
||||
).map(([index, color]) => [
|
||||
index,
|
||||
colorContrast(color, ['#000', '#fff']),
|
||||
]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
${generateColorVariable(
|
||||
'header-background',
|
||||
headerTheme.backgroundColor.dark,
|
||||
@@ -160,6 +182,21 @@ export async function CustomizationRootLayout(props: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tint color from the customization settings.
|
||||
* If the tint color is not set or it is a space customization, it will return the default color.
|
||||
*/
|
||||
export function getTintColor(
|
||||
customization: CustomizationSettings | SiteCustomizationSettings,
|
||||
): CustomizationTint['color'] | undefined {
|
||||
if ('tint' in customization.styling && customization.styling.tint) {
|
||||
return {
|
||||
light: customization.styling.tint?.color.light ?? DEFAULT_TINT_COLOR,
|
||||
dark: customization.styling.tint?.color.dark ?? DEFAULT_TINT_COLOR,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type ColorInput = string | Record<string, string>;
|
||||
function generateColorVariable(name: string, color: ColorInput) {
|
||||
const shades: Record<string, string> = typeof color === 'string' ? shadesOfColor(color) : color;
|
||||
@@ -177,6 +214,8 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
||||
backgroundColor: { light: ColorInput; dark: ColorInput };
|
||||
linkColor: { light: ColorInput; dark: ColorInput };
|
||||
} {
|
||||
const tintColor = getTintColor(customization);
|
||||
|
||||
switch (customization.header.preset) {
|
||||
case CustomizationHeaderPreset.None:
|
||||
case CustomizationHeaderPreset.Default: {
|
||||
@@ -194,17 +233,17 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
||||
case CustomizationHeaderPreset.Bold: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: customization.styling.primaryColor.light,
|
||||
dark: customization.styling.primaryColor.dark,
|
||||
light: tintColor?.light ?? customization.styling.primaryColor.light,
|
||||
dark: tintColor?.dark ?? customization.styling.primaryColor.dark,
|
||||
},
|
||||
linkColor: {
|
||||
light: colorContrast(
|
||||
customization.styling.primaryColor.light,
|
||||
tintColor?.light ?? customization.styling.primaryColor.light,
|
||||
[colors.white, colors.black],
|
||||
'aaa',
|
||||
),
|
||||
dark: colorContrast(
|
||||
customization.styling.primaryColor.dark,
|
||||
tintColor?.dark ?? customization.styling.primaryColor.dark,
|
||||
[colors.white, colors.black],
|
||||
'aaa',
|
||||
),
|
||||
@@ -226,15 +265,25 @@ function generateHeaderTheme(customization: CustomizationSettings | SiteCustomiz
|
||||
case CustomizationHeaderPreset.Custom: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: customization.header.backgroundColor?.light ?? colors.white,
|
||||
dark: customization.header.backgroundColor?.dark ?? colors.black,
|
||||
light:
|
||||
customization.header.backgroundColor?.light ??
|
||||
tintColor?.light ??
|
||||
colors.white,
|
||||
dark:
|
||||
customization.header.backgroundColor?.dark ??
|
||||
tintColor?.dark ??
|
||||
colors.black,
|
||||
},
|
||||
linkColor: {
|
||||
light:
|
||||
customization.header.linkColor?.light ??
|
||||
(tintColor?.light &&
|
||||
colorContrast(tintColor.light, [colors.white, colors.black], 'aaa')) ??
|
||||
customization.styling.primaryColor.light,
|
||||
dark:
|
||||
customization.header.linkColor?.dark ??
|
||||
(tintColor?.dark &&
|
||||
colorContrast(tintColor.dark, [colors.white, colors.black], 'aaa')) ??
|
||||
customization.styling.primaryColor.dark,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -7,27 +7,19 @@
|
||||
--scrollbar-width: calc(100vw - 100%);
|
||||
|
||||
--dark-base: 20 20 20;
|
||||
--light-base: 251 252 252;
|
||||
--light-base: 251 251 251;
|
||||
|
||||
--light-1: color-mix(in srgb, rgb(var(--primary-base-600)), rgb(var(--light-base)) 99%);
|
||||
--light-DEFAULT: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700)),
|
||||
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%);
|
||||
--light-1: color-mix(in srgb, rgb(var(--tint-color-600)), rgb(var(--light-base)) 99%);
|
||||
--light-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 96%);
|
||||
--light-2: color-mix(in srgb, rgb(var(--tint-color-700)), rgb(var(--light-base)) 94%);
|
||||
--light-3: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 88%);
|
||||
--light-4: color-mix(in srgb, rgb(var(--tint-color-800)), rgb(var(--light-base)) 72%);
|
||||
|
||||
--dark-1: color-mix(in srgb, rgb(var(--primary-base-100)), rgb(1 1 1) 96%);
|
||||
--dark-DEFAULT: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-300)),
|
||||
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%);
|
||||
--dark-1: color-mix(in srgb, rgb(var(--tint-color-400)), rgb(var(--dark-base)) 96%);
|
||||
--dark-DEFAULT: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 94%);
|
||||
--dark-2: color-mix(in srgb, rgb(var(--tint-color-300)), rgb(var(--dark-base)) 92%);
|
||||
--dark-3: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 91%);
|
||||
--dark-4: color-mix(in srgb, rgb(var(--tint-color-200)), rgb(var(--dark-base)) 64%);
|
||||
@apply leading-relaxed;
|
||||
}
|
||||
body {
|
||||
@@ -36,29 +28,13 @@
|
||||
html {
|
||||
@apply gutter-stable;
|
||||
}
|
||||
html:is(.plain-background) {
|
||||
--dark-base: 22 22 22;
|
||||
html:is(.no-tint) {
|
||||
--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(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700)),
|
||||
rgb(var(--tint-color-500)),
|
||||
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 {
|
||||
@apply tracking-[-0.025em] text-dark dark:text-light text-balance;
|
||||
@@ -216,3 +192,30 @@ html {
|
||||
html.dark {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +30,13 @@ export function HighlightQuery(props: {
|
||||
const matches = matchString(text, query);
|
||||
|
||||
return (
|
||||
<div className={tcls('whitespace-break-spaces')}>
|
||||
<span className={tcls('whitespace-break-spaces')}>
|
||||
{matches.map((entry, index) => (
|
||||
<span key={index} className={tcls(entry.match ? highlight : null)}>
|
||||
{entry.text}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import React from 'react';
|
||||
import { atom, useRecoilState } from 'recoil';
|
||||
@@ -7,29 +9,30 @@ import { useLanguage } from '@/intl/client';
|
||||
import { t } from '@/intl/translate';
|
||||
import { TranslationLanguage } from '@/intl/translations';
|
||||
import { iterateStreamResponse } from '@/lib/actions';
|
||||
import { SiteContentPointer } from '@/lib/api';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
|
||||
import { useSearch, useSearchLink } from './useSearch';
|
||||
import { Link } from '../primitives';
|
||||
|
||||
/**
|
||||
* 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 SearchState =
|
||||
| {
|
||||
type: 'answer';
|
||||
answer: AskAnswerResult | null;
|
||||
answer: AskAnswerResult;
|
||||
}
|
||||
| {
|
||||
type: 'error';
|
||||
}
|
||||
| {
|
||||
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',
|
||||
default: null,
|
||||
});
|
||||
@@ -37,12 +40,13 @@ export const searchAskState = atom<
|
||||
/**
|
||||
* Fetch and render the answers to a question.
|
||||
*/
|
||||
export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
const { spaceId, query } = props;
|
||||
export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: string }) {
|
||||
const { pointer, query } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
const [, setSearchState] = useSearch();
|
||||
const [state, setState] = useRecoilState(searchAskState);
|
||||
const { organizationId, siteId, siteSpaceId } = pointer;
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -52,7 +56,9 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
});
|
||||
|
||||
(async () => {
|
||||
const stream = iterateStreamResponse(streamAskQuestion(spaceId, query));
|
||||
const stream = iterateStreamResponse(
|
||||
streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query),
|
||||
);
|
||||
|
||||
setSearchState((prev) =>
|
||||
prev
|
||||
@@ -68,7 +74,6 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState({
|
||||
type: 'answer',
|
||||
answer: chunk,
|
||||
@@ -91,7 +96,7 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
cancelled = true;
|
||||
}
|
||||
};
|
||||
}, [spaceId, query, setSearchState, setState]);
|
||||
}, [organizationId, siteId, siteSpaceId, query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
@@ -108,15 +113,9 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
return (
|
||||
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
|
||||
{state?.type === 'answer' ? (
|
||||
<>
|
||||
{state.answer ? (
|
||||
<React.Suspense fallback={loading}>
|
||||
<TransitionAnswerBody answer={state.answer} placeholder={loading} />
|
||||
</React.Suspense>
|
||||
) : (
|
||||
<div className={tcls('p-4')}>{t(language, 'search_ask_no_answer')}</div>
|
||||
)}
|
||||
</>
|
||||
<React.Suspense fallback={loading}>
|
||||
<TransitionAnswerBody answer={state.answer} placeholder={loading} />
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
{state?.type === 'error' ? (
|
||||
<div className={tcls('p-4')}>{t(language, 'search_ask_error')}</div>
|
||||
@@ -159,7 +158,7 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
|
||||
<div
|
||||
data-test="search-ask-answer"
|
||||
className={tcls(
|
||||
'mt-4',
|
||||
'my-4',
|
||||
'sm:mt-6',
|
||||
'px-4',
|
||||
'sm:px-12',
|
||||
@@ -167,16 +166,16 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
|
||||
'dark:text-light/8',
|
||||
)}
|
||||
>
|
||||
{answer.hasAnswer ? answer.body : t(language, 'search_ask_no_answer')}
|
||||
{answer.body ?? t(language, 'search_ask_no_answer')}
|
||||
{answer.followupQuestions.length > 0 ? (
|
||||
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
|
||||
) : null}
|
||||
</div>
|
||||
{answer.sources.length > 0 ? (
|
||||
<AnswerSources
|
||||
hasAnswer={answer.hasAnswer}
|
||||
sources={answer.sources}
|
||||
language={language}
|
||||
hasAnswer={Boolean(answer.body)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
@@ -233,7 +232,7 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
|
||||
function AnswerSources(props: {
|
||||
sources: AskAnswerSource[];
|
||||
language: TranslationLanguage;
|
||||
hasAnswer?: boolean;
|
||||
hasAnswer: boolean;
|
||||
}) {
|
||||
const { sources, language, hasAnswer } = props;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useLanguage, tString } from '@/intl/client';
|
||||
@@ -35,45 +36,69 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
||||
'flex-row',
|
||||
'justify-center',
|
||||
'items-center',
|
||||
'px-2',
|
||||
'gap-3',
|
||||
'text-dark/7',
|
||||
'min-h-[2.5rem]',
|
||||
'w-[2.5rem]',
|
||||
'rounded-lg',
|
||||
'straight-corners:rounded-none',
|
||||
'bg-dark/2',
|
||||
'transition-colors',
|
||||
'transition-opacity',
|
||||
'ease-out',
|
||||
'hover:opacity-8',
|
||||
'w-full',
|
||||
'px-3',
|
||||
'py-2',
|
||||
'gap-2',
|
||||
|
||||
'bg-light',
|
||||
'dark:bg-dark',
|
||||
|
||||
'ring-1',
|
||||
'ring-inset',
|
||||
'ring-dark/1',
|
||||
'dark:ring-light/2',
|
||||
|
||||
'shadow-sm',
|
||||
'shadow-dark/4',
|
||||
'dark:shadow-none',
|
||||
|
||||
'text-dark/6',
|
||||
'dark:text-light/6',
|
||||
|
||||
'rounded-lg',
|
||||
'straight-corners:rounded-sm',
|
||||
|
||||
'contrast-more:ring-dark',
|
||||
'contrast-more:bg-light',
|
||||
'contrast-more:text-dark',
|
||||
'dark:bg-light/1',
|
||||
'dark:ring-light/1',
|
||||
'dark:text-light/7',
|
||||
'contrast-more:dark:ring-light',
|
||||
'contrast-more:dark:bg-dark',
|
||||
'contrast-more:dark:text-light',
|
||||
'[&>p]:hidden',
|
||||
'[&>span]:hidden',
|
||||
|
||||
'transition-all',
|
||||
'hover:shadow-md',
|
||||
'hover:scale-102',
|
||||
'hover:ring-dark/2',
|
||||
'hover:text-dark/10',
|
||||
'focus:shadow-md',
|
||||
'focus:scale-102',
|
||||
'focus:ring-dark/2',
|
||||
'focus:text-dark/10',
|
||||
'dark:hover:bg-dark-3',
|
||||
'dark:hover:ring-light/4',
|
||||
'dark:hover:text-light',
|
||||
'dark:focus:bg-dark-3',
|
||||
'dark:focus:ring-light/4',
|
||||
'dark:focus:text-light',
|
||||
|
||||
'contrast-more:hover:ring-2',
|
||||
'contrast-more:hover:ring-dark',
|
||||
'dark:contrast-more:hover:ring-light',
|
||||
'contrast-more:focus:ring-2',
|
||||
'contrast-more:focus:ring-dark',
|
||||
'dark:contrast-more:focus:ring-light',
|
||||
|
||||
'active:shadow-sm',
|
||||
'active:scale-98',
|
||||
|
||||
'md:justify-start',
|
||||
'md:[&>p]:flex',
|
||||
'md:[&>span]:flex',
|
||||
'md:w-full',
|
||||
'md:px-3.5',
|
||||
'text-base',
|
||||
style,
|
||||
)}
|
||||
>
|
||||
<div className={tcls('text-dark/7', 'pt-1.5', 'pb-2', 'dark:text-light/7')}>
|
||||
<Icon icon="magnifying-glass" className={tcls('shrink-0', 'size-4')} />
|
||||
</div>
|
||||
{children}
|
||||
<Icon
|
||||
icon="magnifying-glass"
|
||||
className={tcls('text-dark/8', 'dark:text-light/8', 'shrink-0', 'size-4')}
|
||||
/>
|
||||
<div className={tcls('w-full', 'hidden', 'md:block', 'text-left')}>{children}</div>
|
||||
<Shortcut />
|
||||
</button>
|
||||
);
|
||||
@@ -96,20 +121,22 @@ const Shortcut = () => {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<span
|
||||
<div
|
||||
className={tcls(
|
||||
'shortcut',
|
||||
'hidden',
|
||||
'md:inline',
|
||||
'justify-end',
|
||||
'text-xs',
|
||||
'text-dark/5',
|
||||
'text-dark/6',
|
||||
'contrast-more:text-dark',
|
||||
'dark:text-light/5',
|
||||
'dark:text-light/6',
|
||||
'whitespace-nowrap',
|
||||
'contrast-more:dark:text-light',
|
||||
`[font-feature-settings:"calt",_"case"]`,
|
||||
)}
|
||||
>
|
||||
{operatingSystem === 'mac' ? '⌘' : 'Ctrl +'} K
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { Collection, Site } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useRouter } from 'next/navigation';
|
||||
@@ -56,9 +55,9 @@ export function SearchModal(props: SearchModalProps) {
|
||||
};
|
||||
}, [isSearchOpened]);
|
||||
|
||||
if (state === null) {
|
||||
return null;
|
||||
}
|
||||
// if (state === null) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
const onChangeQuery = (newQuery: SearchState) => {
|
||||
setSearchState(newQuery);
|
||||
@@ -72,62 +71,75 @@ export function SearchModal(props: SearchModalProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
role="dialog"
|
||||
className={tcls(
|
||||
'flex',
|
||||
'items-start',
|
||||
'justify-center',
|
||||
'fixed',
|
||||
'inset-0',
|
||||
'bg-dark/4',
|
||||
'backdrop-blur-2xl',
|
||||
'opacity-[1]',
|
||||
'z-30',
|
||||
'px-4',
|
||||
'pt-4',
|
||||
'dark:bg-dark/8',
|
||||
'md:pt-[min(8vw,_6rem)]',
|
||||
)}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{askState?.type === 'loading' ? (
|
||||
<motion.div
|
||||
key="loading"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 1 }}
|
||||
className={tcls(
|
||||
'w-[100vw]',
|
||||
'h-[100vh]',
|
||||
'fixed',
|
||||
'inset-0',
|
||||
'z-10',
|
||||
'pointer-events-none',
|
||||
)}
|
||||
>
|
||||
<LoadingPane
|
||||
gridStyle={['h-[100vh]', 'aspect-auto', 'top-[-30%]']}
|
||||
pulse
|
||||
tile={96}
|
||||
style={['grid']}
|
||||
/>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
<SearchModalBody
|
||||
{...props}
|
||||
state={state}
|
||||
onChangeQuery={onChangeQuery}
|
||||
onClose={onClose}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
<AnimatePresence>
|
||||
{state !== null ? (
|
||||
<motion.div
|
||||
initial={{
|
||||
opacity: 0,
|
||||
}}
|
||||
animate={{
|
||||
opacity: 1,
|
||||
}}
|
||||
exit={{
|
||||
opacity: 0,
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
delay: 0.1,
|
||||
}}
|
||||
role="dialog"
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'inset-0',
|
||||
'bg-dark/4',
|
||||
'backdrop-blur-2xl',
|
||||
'z-30',
|
||||
'px-4',
|
||||
'pt-4',
|
||||
'dark:bg-dark/8',
|
||||
'md:pt-[min(8vh,6rem)]',
|
||||
)}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<div className="scroll-nojump">
|
||||
<AnimatePresence>
|
||||
{askState?.type === 'loading' ? (
|
||||
<motion.div
|
||||
key="loading"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 1 }}
|
||||
className={tcls(
|
||||
'w-screen',
|
||||
'h-screen',
|
||||
'fixed',
|
||||
'inset-0',
|
||||
'z-10',
|
||||
'pointer-events-none',
|
||||
)}
|
||||
>
|
||||
<LoadingPane
|
||||
gridStyle={['h-screen', 'aspect-auto', 'top-[-30%]']}
|
||||
pulse
|
||||
tile={96}
|
||||
style={['grid']}
|
||||
/>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
<SearchModalBody
|
||||
{...props}
|
||||
state={state}
|
||||
onChangeQuery={onChangeQuery}
|
||||
onClose={onClose}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,15 +195,34 @@ function SearchModalBody(
|
||||
|
||||
return (
|
||||
<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"
|
||||
aria-label={tString(language, 'search')}
|
||||
className={tcls(
|
||||
'z-40',
|
||||
'relative',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'bg-white',
|
||||
'max-w-[768px]',
|
||||
'mt-[-1px]',
|
||||
'max-w-prose',
|
||||
'mx-auto',
|
||||
'max-h-[70dvh]',
|
||||
'w-full',
|
||||
'rounded-lg',
|
||||
'straight-corners:rounded-sm',
|
||||
@@ -203,14 +234,6 @@ function SearchModalBody(
|
||||
'dark:bg-dark-3',
|
||||
'dark:ring-light/2',
|
||||
)}
|
||||
initial={{
|
||||
scale: 0.95,
|
||||
opacity: 0,
|
||||
}}
|
||||
animate={{
|
||||
scale: 1,
|
||||
opacity: 1,
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
@@ -291,7 +314,7 @@ function SearchModalBody(
|
||||
></SearchResults>
|
||||
) : null}
|
||||
{state.query && state.ask && withAsk ? (
|
||||
<SearchAskAnswer spaceId={spaceId} query={state.query} />
|
||||
<SearchAskAnswer pointer={pointer} query={state.query} />
|
||||
) : null}
|
||||
</motion.div>
|
||||
);
|
||||
|
||||
@@ -174,7 +174,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={tcls('max-h-[70vh]', 'overflow-auto', 'relative')}>
|
||||
<div className={tcls('overflow-auto')}>
|
||||
{children}
|
||||
{results.length === 0 ? (
|
||||
<div
|
||||
|
||||
@@ -52,14 +52,7 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
|
||||
</p>
|
||||
) : null}
|
||||
{item.body ? (
|
||||
<p
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'line-clamp-3',
|
||||
'z-[-1]', //to force stacking order
|
||||
'relative',
|
||||
)}
|
||||
>
|
||||
<p className={tcls('text-sm', 'line-clamp-3', 'relative')}>
|
||||
<HighlightQuery query={query} text={item.body} />
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
@@ -39,10 +39,10 @@ export interface AskAnswerSource {
|
||||
}
|
||||
|
||||
export interface AskAnswerResult {
|
||||
/** Undefined if no answer. */
|
||||
body?: React.ReactNode;
|
||||
followupQuestions: string[];
|
||||
sources: AskAnswerSource[];
|
||||
hasAnswer: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,16 +152,53 @@ export async function searchSiteSpaceContent(
|
||||
/**
|
||||
* Server action to ask a question in a space.
|
||||
*/
|
||||
export const streamAskQuestion = streamResponse(async function* (spaceId: string, query: string) {
|
||||
const stream = api
|
||||
.api()
|
||||
.spaces.streamAskInSpace(spaceId, { query, format: 'document', details: true });
|
||||
const pagesPromise = api.getSpaceContentData({ spaceId }, undefined);
|
||||
export const streamAskQuestion = streamResponse(async function* (
|
||||
organizationId: string,
|
||||
siteId: string,
|
||||
siteSpaceId: string | null,
|
||||
question: string,
|
||||
) {
|
||||
const stream = api.api().client.orgs.streamAskInSite(
|
||||
organizationId,
|
||||
siteId,
|
||||
{
|
||||
question,
|
||||
context: siteSpaceId
|
||||
? {
|
||||
siteSpaceId,
|
||||
}
|
||||
: undefined,
|
||||
scope: {
|
||||
mode: 'default',
|
||||
|
||||
// Include the current site space regardless.
|
||||
includedSiteSpaces: siteSpaceId ? [siteSpaceId] : undefined,
|
||||
},
|
||||
},
|
||||
{ format: 'document' },
|
||||
);
|
||||
|
||||
const spaceData = new PromiseQueue<string, RevisionPage[]>();
|
||||
for await (const chunk of stream) {
|
||||
// We run the AI search and fetch the pages in parallel
|
||||
const { pages } = await pagesPromise;
|
||||
const answer = chunk.answer;
|
||||
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
@@ -175,26 +212,28 @@ export async function getRecommendedQuestions(spaceId: string): Promise<string[]
|
||||
}
|
||||
|
||||
function transformAnswer(
|
||||
answer: SearchAIAnswer | undefined,
|
||||
pages: RevisionPage[],
|
||||
): AskAnswerResult | null {
|
||||
if (!answer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
answer: SearchAIAnswer,
|
||||
spacePages: Map<string, RevisionPage[]>,
|
||||
): AskAnswerResult {
|
||||
const sources = answer.sources
|
||||
.map((source) => {
|
||||
if (source.type !== 'page') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pages = spacePages.get(source.space);
|
||||
|
||||
if (!pages) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const page = resolvePageId(pages, source.page);
|
||||
if (!page) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: page.page.id,
|
||||
id: source.page,
|
||||
title: page.page.title,
|
||||
href: pageHref(pages, page.page),
|
||||
};
|
||||
@@ -217,7 +256,6 @@ function transformAnswer(
|
||||
) : null,
|
||||
followupQuestions: answer.followupQuestions,
|
||||
sources,
|
||||
hasAnswer: !!answer.answer && 'document' in answer.answer,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -283,3 +321,70 @@ function transformPageResult(item: SearchPageResult, space?: Space) {
|
||||
|
||||
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,9 +106,13 @@ export function SpaceLayout(props: {
|
||||
)
|
||||
}
|
||||
innerHeader={
|
||||
(sections || !withTopHeader) && withVariants ? (
|
||||
<SpacesDropdown space={space} spaces={spaces} />
|
||||
) : null
|
||||
withVariants && (
|
||||
<SpacesDropdown
|
||||
className={withTopHeader && !sections ? 'sm:hidden' : undefined}
|
||||
space={space}
|
||||
spaces={spaces}
|
||||
/>
|
||||
)
|
||||
}
|
||||
headerOffset={headerOffset}
|
||||
/>
|
||||
|
||||
@@ -35,7 +35,6 @@ export function Button({
|
||||
]
|
||||
: // SECONDARY
|
||||
[
|
||||
'bg-dark/2',
|
||||
'ring-dark/1',
|
||||
'hover:bg-dark/3',
|
||||
'dark:bg-light/2',
|
||||
@@ -45,7 +44,7 @@ export function Button({
|
||||
|
||||
const sizes = {
|
||||
default: ['text-base', 'px-4', 'py-2'],
|
||||
medium: ['text-base', 'px-3', 'py-1'],
|
||||
medium: ['text-sm', 'px-3', 'py-1'],
|
||||
small: ['text-xs', 'px-3 py-2'],
|
||||
};
|
||||
|
||||
|
||||
@@ -3,24 +3,38 @@ import localFont from 'next/font/local';
|
||||
import { getEmojiForCode } from '@/lib/emojis';
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
import './emoji.css';
|
||||
|
||||
/* Load the 3 variants of the font as CSS variables and let the emoji.css decide on the best one to use */
|
||||
|
||||
const svgFont = localFont({
|
||||
src: './svg.woff2',
|
||||
/**
|
||||
COLRv1 font.
|
||||
- lightweight, top quality
|
||||
- widely supported by modern browsers
|
||||
- currently not by Safari (or iOS)
|
||||
*/
|
||||
const colrv1Font = localFont({
|
||||
src: './joypixels-colrv1.woff2',
|
||||
preload: false,
|
||||
variable: '--font-emojis-svg',
|
||||
variable: '--font-emojis-colrv1',
|
||||
});
|
||||
|
||||
/**
|
||||
SBIX font.
|
||||
- narrowly supported
|
||||
- currently required for Safari (or iOS)
|
||||
- provide alternative font-family name (see below)
|
||||
*/
|
||||
const sbixFont = localFont({
|
||||
src: './sbix.woff2',
|
||||
src: './joypixels-sbix.woff2',
|
||||
preload: false,
|
||||
variable: '--font-emojis-sbix',
|
||||
});
|
||||
|
||||
/**
|
||||
CBDT font.
|
||||
- widely supported
|
||||
- currently not by Safari (or iOS)
|
||||
- retain for legacy browser support
|
||||
*/
|
||||
const cbdtFont = localFont({
|
||||
src: './cbdt.woff2',
|
||||
src: './joypixels-cbdt.woff2',
|
||||
preload: false,
|
||||
variable: '--font-emojis-cbdt',
|
||||
});
|
||||
@@ -28,7 +42,7 @@ const cbdtFont = localFont({
|
||||
/**
|
||||
* Class name to set on the <html> tag to use the emoji font.
|
||||
*/
|
||||
export const emojiFontClassName = [svgFont.variable, sbixFont.variable, cbdtFont.variable].join(
|
||||
export const emojiFontClassName = [colrv1Font.variable, sbixFont.variable, cbdtFont.variable].join(
|
||||
' ',
|
||||
);
|
||||
|
||||
@@ -40,5 +54,5 @@ export async function Emoji(props: { code: string; style?: ClassValue }) {
|
||||
const { code, style } = props;
|
||||
|
||||
const fallback = getEmojiForCode(code);
|
||||
return <span className={'emoji ' + tcls(style)}>{fallback}</span>;
|
||||
return <span className={tcls('emoji', style)}>{fallback}</span>;
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
[class*='emoji'] {
|
||||
font-family: var(--font-emojis-cbdt);
|
||||
}
|
||||
|
||||
/* Safari Only CSS here */
|
||||
_::-webkit-full-page-media,
|
||||
_:future,
|
||||
:root [class*='emoji'] {
|
||||
font-family: var(--font-emojis-sbix);
|
||||
}
|
||||
|
||||
/* Chrome Only CSS here */
|
||||
@media screen and (-webkit-min-device-pixel-ratio: 0) {
|
||||
.emoji {
|
||||
font-family: var(--font-emojis-svg);
|
||||
}
|
||||
}
|
||||
|
||||
/* Firefox Only CSS here */
|
||||
@-moz-document url-prefix() {
|
||||
.emoji {
|
||||
font-family: var(--font-emojis-svg);
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -6,7 +6,7 @@ export const en = {
|
||||
switch_to_light_theme: 'Switch to light theme',
|
||||
switch_to_system_theme: 'Switch to system theme',
|
||||
search: 'Search',
|
||||
search_or_ask: 'Ask or Search',
|
||||
search_or_ask: 'Ask or search',
|
||||
search_input_placeholder: 'Search content',
|
||||
search_ask_input_placeholder: 'Search content or ask a question',
|
||||
search_no_results: 'No results for "${1}".',
|
||||
|
||||
@@ -87,14 +87,30 @@ const cacheTtl_1day = {
|
||||
ttl: 24 * 60 * 60,
|
||||
};
|
||||
|
||||
const apiSyncStorage = new AsyncLocalStorage<GitBookAPI>();
|
||||
export type GitBookAPIContext = {
|
||||
/**
|
||||
* Instance of the GitBook API client.
|
||||
*/
|
||||
client: GitBookAPI;
|
||||
|
||||
/**
|
||||
* Context ID representing a hash of the visitor's attributes/assertions that are
|
||||
* included in the claims property of the content API JWT token.
|
||||
*
|
||||
* It serves as a suffix for the cache key to ensure that the content cache is invalidated
|
||||
* when these attributees/assertions change.
|
||||
*/
|
||||
contextId: string | undefined;
|
||||
};
|
||||
|
||||
const apiSyncStorage = new AsyncLocalStorage<GitBookAPIContext>();
|
||||
|
||||
export const DEFAULT_API_ENDPOINT = process.env.GITBOOK_API_URL ?? 'https://api.gitbook.com';
|
||||
|
||||
/**
|
||||
* Create a new API client with a token.
|
||||
*/
|
||||
export function apiWithToken(apiToken: string): GitBookAPI {
|
||||
export function apiWithToken(apiToken: string, contextId: string | undefined): GitBookAPIContext {
|
||||
const headersList = headers();
|
||||
const apiEndpoint = headersList.get('x-gitbook-api') ?? DEFAULT_API_ENDPOINT;
|
||||
|
||||
@@ -104,13 +120,13 @@ export function apiWithToken(apiToken: string): GitBookAPI {
|
||||
userAgent: userAgent(),
|
||||
});
|
||||
|
||||
return gitbook;
|
||||
return { client: gitbook, contextId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an API client for the current request.
|
||||
*/
|
||||
export function api(): GitBookAPI {
|
||||
export function api(): GitBookAPIContext {
|
||||
const existing = apiSyncStorage.getStore();
|
||||
if (existing) {
|
||||
return existing;
|
||||
@@ -118,6 +134,7 @@ export function api(): GitBookAPI {
|
||||
|
||||
const headersList = headers();
|
||||
const apiToken = headersList.get('x-gitbook-token');
|
||||
const contextId = headersList.get('x-gitbook-token-context') ?? undefined;
|
||||
|
||||
if (!apiToken) {
|
||||
throw new Error(
|
||||
@@ -125,13 +142,13 @@ export function api(): GitBookAPI {
|
||||
);
|
||||
}
|
||||
|
||||
return apiWithToken(apiToken);
|
||||
return apiWithToken(apiToken, contextId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Use an API client for an async function.
|
||||
*/
|
||||
export function withAPI<T>(client: GitBookAPI, fn: () => Promise<T>): Promise<T> {
|
||||
export function withAPI<T>(client: GitBookAPIContext, fn: () => Promise<T>): Promise<T> {
|
||||
return apiSyncStorage.run(client, fn);
|
||||
}
|
||||
|
||||
@@ -164,7 +181,7 @@ export const getUserById = cache({
|
||||
}),
|
||||
get: async (userId: string, options: CacheFunctionOptions) => {
|
||||
try {
|
||||
const response = await api().users.getUserById(userId, {
|
||||
const response = await api().client.users.getUserById(userId, {
|
||||
signal: options.signal,
|
||||
...noCacheFetchOptions,
|
||||
});
|
||||
@@ -200,7 +217,7 @@ export const getPublishedContentByUrl = cache({
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
try {
|
||||
const response = await api().urls.getPublishedContentByUrl(
|
||||
const response = await api().client.urls.getPublishedContentByUrl(
|
||||
{
|
||||
url,
|
||||
visitorAuthToken,
|
||||
@@ -249,7 +266,7 @@ export const getSpace = cache({
|
||||
name: 'api.getSpace',
|
||||
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
|
||||
get: async (spaceId: string, shareKey: string | undefined, options: CacheFunctionOptions) => {
|
||||
const response = await api().spaces.getSpaceById(
|
||||
const response = await api().client.spaces.getSpaceById(
|
||||
spaceId,
|
||||
{
|
||||
shareKey,
|
||||
@@ -273,7 +290,7 @@ export const getChangeRequest = cache({
|
||||
tag: (spaceId, changeRequestId) =>
|
||||
getAPICacheTag({ tag: 'change-request', space: spaceId, changeRequest: changeRequestId }),
|
||||
get: async (spaceId: string, changeRequestId: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().spaces.getChangeRequestById(spaceId, changeRequestId, {
|
||||
const response = await api().client.spaces.getChangeRequestById(spaceId, changeRequestId, {
|
||||
...noCacheFetchOptions,
|
||||
signal: options.signal,
|
||||
});
|
||||
@@ -301,13 +318,14 @@ export const getRevision = cache({
|
||||
name: 'api.getRevision.v2',
|
||||
tag: (spaceId, revisionId) =>
|
||||
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
spaceId: string,
|
||||
revisionId: string,
|
||||
fetchOptions: GetRevisionOptions,
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().spaces.getRevisionById(
|
||||
const response = await api().client.spaces.getRevisionById(
|
||||
spaceId,
|
||||
revisionId,
|
||||
{
|
||||
@@ -331,13 +349,14 @@ export const getRevisionPages = cache({
|
||||
name: 'api.getRevisionPages.v4',
|
||||
tag: (spaceId, revisionId) =>
|
||||
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
spaceId: string,
|
||||
revisionId: string,
|
||||
fetchOptions: GetRevisionOptions,
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().spaces.listPagesInRevisionById(
|
||||
const response = await api().client.spaces.listPagesInRevisionById(
|
||||
spaceId,
|
||||
revisionId,
|
||||
{
|
||||
@@ -364,6 +383,7 @@ export const getRevisionPageByPath = cache({
|
||||
name: 'api.getRevisionPageByPath.v3',
|
||||
tag: (spaceId, revisionId) =>
|
||||
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
spaceId: string,
|
||||
revisionId: string,
|
||||
@@ -373,7 +393,7 @@ export const getRevisionPageByPath = cache({
|
||||
const encodedPath = encodeURIComponent(pagePath);
|
||||
|
||||
try {
|
||||
const response = await api().spaces.getPageInRevisionByPath(
|
||||
const response = await api().client.spaces.getPageInRevisionByPath(
|
||||
spaceId,
|
||||
revisionId,
|
||||
encodedPath,
|
||||
@@ -416,7 +436,7 @@ const getRevisionFileById = cache({
|
||||
) => {
|
||||
try {
|
||||
const response = await (async () => {
|
||||
return api().spaces.getFileInRevisionById(
|
||||
return api().client.spaces.getFileInRevisionById(
|
||||
spaceId,
|
||||
revisionId,
|
||||
fileId,
|
||||
@@ -445,6 +465,7 @@ const getRevisionReusableContentById = cache({
|
||||
name: 'api.getRevisionReusableContentById.v1',
|
||||
tag: (spaceId, revisionId) =>
|
||||
getAPICacheTag({ tag: 'revision', space: spaceId, revision: revisionId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
spaceId: string,
|
||||
revisionId: string,
|
||||
@@ -453,7 +474,7 @@ const getRevisionReusableContentById = cache({
|
||||
) => {
|
||||
try {
|
||||
const response = await (async () => {
|
||||
return api().spaces.getReusableContentInRevisionById(
|
||||
return api().client.spaces.getReusableContentInRevisionById(
|
||||
spaceId,
|
||||
revisionId,
|
||||
reusableContentId,
|
||||
@@ -489,7 +510,7 @@ const getRevisionAllFiles = cache({
|
||||
get: async (spaceId: string, revisionId: string, options: CacheFunctionOptions) => {
|
||||
const response = await getAll(
|
||||
(params) =>
|
||||
api().spaces.listFilesInRevisionById(
|
||||
api().client.spaces.listFilesInRevisionById(
|
||||
spaceId,
|
||||
revisionId,
|
||||
{
|
||||
@@ -600,8 +621,9 @@ export const getDocument = cache({
|
||||
name: 'api.getDocument.v2',
|
||||
tag: (spaceId, documentId) =>
|
||||
getAPICacheTag({ tag: 'document', space: spaceId, document: documentId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (spaceId: string, documentId: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().spaces.getDocumentById(
|
||||
const response = await api().client.spaces.getDocumentById(
|
||||
spaceId,
|
||||
documentId,
|
||||
{
|
||||
@@ -626,6 +648,7 @@ export const getDocument = cache({
|
||||
export const getSiteRedirectBySource = cache({
|
||||
name: 'api.getSiteRedirectBySource',
|
||||
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
args: {
|
||||
organizationId: string;
|
||||
@@ -637,7 +660,7 @@ export const getSiteRedirectBySource = cache({
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
try {
|
||||
const response = await api().orgs.getSiteRedirectBySource(
|
||||
const response = await api().client.orgs.getSiteRedirectBySource(
|
||||
args.organizationId,
|
||||
args.siteId,
|
||||
{
|
||||
@@ -669,8 +692,9 @@ export const getSiteRedirectBySource = cache({
|
||||
export const getSite = cache({
|
||||
name: 'api.getSite',
|
||||
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().orgs.getSiteById(organizationId, siteId, {
|
||||
const response = await api().client.orgs.getSiteById(organizationId, siteId, {
|
||||
...noCacheFetchOptions,
|
||||
signal: options.signal,
|
||||
});
|
||||
@@ -686,6 +710,7 @@ export const getSite = cache({
|
||||
export const getPublishedContentSite = cache({
|
||||
name: 'api.getPublishedContentSite',
|
||||
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
args: {
|
||||
organizationId: string;
|
||||
@@ -694,7 +719,7 @@ export const getPublishedContentSite = cache({
|
||||
},
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().orgs.getPublishedContentSite(
|
||||
const response = await api().client.orgs.getPublishedContentSite(
|
||||
args.organizationId,
|
||||
args.siteId,
|
||||
{
|
||||
@@ -779,7 +804,7 @@ export async function getSiteData(
|
||||
const spaces =
|
||||
siteSpaces ?? (sections ? parseSpacesFromSiteSpaces(sections.section.siteSpaces) : []);
|
||||
|
||||
const customization = mergeCustomizationWithExtend(
|
||||
const customization = getActiveCustomizationSettings(
|
||||
pointer.siteSpaceId ? customizations.siteSpaces[pointer.siteSpaceId] : customizations.site,
|
||||
);
|
||||
|
||||
@@ -826,7 +851,7 @@ export const getCollection = cache({
|
||||
name: 'api.getCollection',
|
||||
tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }),
|
||||
get: async (collectionId: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().collections.getCollectionById(collectionId, {
|
||||
const response = await api().client.collections.getCollectionById(collectionId, {
|
||||
...noCacheFetchOptions,
|
||||
signal: options.signal,
|
||||
});
|
||||
@@ -844,7 +869,7 @@ export const getCollectionSpaces = cache({
|
||||
tag: (collectionId) => getAPICacheTag({ tag: 'collection', collection: collectionId }),
|
||||
get: async (collectionId: string, options: CacheFunctionOptions) => {
|
||||
const response = await getAll((params) =>
|
||||
api().collections.listSpacesInCollectionById(collectionId, params, {
|
||||
api().client.collections.listSpacesInCollectionById(collectionId, params, {
|
||||
...noCacheFetchOptions,
|
||||
signal: options.signal,
|
||||
}),
|
||||
@@ -896,6 +921,7 @@ export async function getSpaceContentData(
|
||||
export const searchSpaceContent = cache({
|
||||
name: 'api.searchSpaceContent',
|
||||
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
spaceId: string,
|
||||
/** The revision ID is used as a cache bust key, to avoid revalidating lot of cache entries by tags */
|
||||
@@ -903,7 +929,7 @@ export const searchSpaceContent = cache({
|
||||
query: string,
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().spaces.searchSpaceContent(
|
||||
const response = await api().client.spaces.searchSpaceContent(
|
||||
spaceId,
|
||||
{ query },
|
||||
{
|
||||
@@ -921,8 +947,9 @@ export const searchSpaceContent = cache({
|
||||
export const searchParentContent = cache({
|
||||
name: 'api.searchParentContent',
|
||||
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (parentId: string, query: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().search.searchContent(
|
||||
const response = await api().client.search.searchContent(
|
||||
{ query },
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
@@ -941,6 +968,7 @@ export const searchParentContent = cache({
|
||||
export const searchSiteContent = cache({
|
||||
name: 'api.searchSiteContent',
|
||||
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
|
||||
getKeySuffix: () => api().contextId,
|
||||
get: async (
|
||||
organizationId: string,
|
||||
siteId: string,
|
||||
@@ -953,7 +981,7 @@ export const searchSiteContent = cache({
|
||||
cacheBust?: string,
|
||||
options?: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().orgs.searchSiteContent(
|
||||
const response = await api().client.orgs.searchSiteContent(
|
||||
organizationId,
|
||||
siteId,
|
||||
{
|
||||
@@ -980,7 +1008,7 @@ export const getRecommendedQuestionsInSpace = cache({
|
||||
name: 'api.getRecommendedQuestionsInSpace',
|
||||
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
|
||||
get: async (spaceId: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().spaces.getRecommendedQuestionsInSpace(spaceId, {
|
||||
const response = await api().client.spaces.getRecommendedQuestionsInSpace(spaceId, {
|
||||
...noCacheFetchOptions,
|
||||
signal: options.signal,
|
||||
});
|
||||
@@ -999,7 +1027,7 @@ export const renderIntegrationUi = cache({
|
||||
request: RequestRenderIntegrationUI,
|
||||
options: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().integrations.renderIntegrationUiWithPost(
|
||||
const response = await api().client.integrations.renderIntegrationUiWithPost(
|
||||
integrationName,
|
||||
request,
|
||||
{
|
||||
@@ -1018,7 +1046,7 @@ export const renderIntegrationUi = cache({
|
||||
export const getEmbedByUrl = cache({
|
||||
name: 'api.getEmbedByUrl',
|
||||
get: async (url: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().urls.getEmbedByUrl(
|
||||
const response = await api().client.urls.getEmbedByUrl(
|
||||
{ url },
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
@@ -1036,7 +1064,7 @@ export const getEmbedByUrlInSpace = cache({
|
||||
name: 'api.getEmbedByUrlInSpace',
|
||||
tag: (spaceId) => getAPICacheTag({ tag: 'space', space: spaceId }),
|
||||
get: async (spaceId: string, url: string, options: CacheFunctionOptions) => {
|
||||
const response = await api().spaces.getEmbedByUrlInSpace(
|
||||
const response = await api().client.spaces.getEmbedByUrlInSpace(
|
||||
spaceId,
|
||||
{ url },
|
||||
{
|
||||
@@ -1204,19 +1232,19 @@ async function getAll<T, E>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the customization settings with the ones passed in the x-gitbook-customization header if present.
|
||||
* Selects the customization settings from the x-gitbook-customization header if present,
|
||||
* otherwise returns the original API-provided settings.
|
||||
*/
|
||||
function mergeCustomizationWithExtend<T extends SiteCustomizationSettings | CustomizationSettings>(
|
||||
raw: T,
|
||||
) {
|
||||
function getActiveCustomizationSettings(
|
||||
settings: SiteCustomizationSettings,
|
||||
): SiteCustomizationSettings {
|
||||
const headersList = headers();
|
||||
const extend = headersList.get('x-gitbook-customization');
|
||||
if (extend) {
|
||||
try {
|
||||
const parsed = rison.decode_object<DeepPartial<T>>(extend);
|
||||
const parsedSettings = rison.decode_object<SiteCustomizationSettings>(extend);
|
||||
|
||||
// Merge objects and some properties deep
|
||||
return mergeDeepPlainObject(raw, parsed, ['styling', 'themes']);
|
||||
return parsedSettings;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Failed to parse x-gitbook-customization header (ignored): ${
|
||||
@@ -1226,35 +1254,5 @@ function mergeCustomizationWithExtend<T extends SiteCustomizationSettings | Cust
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
return settings;
|
||||
}
|
||||
|
||||
+79
-2
@@ -1,6 +1,7 @@
|
||||
import { Mock, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { beforeEach, describe, expect, it, Mock, mock } from 'bun:test';
|
||||
import hash from 'object-hash';
|
||||
|
||||
import { CacheFunction, CacheFunctionOptions, cache } from './cache';
|
||||
import { CacheDefinition, CacheFunction, CacheFunctionOptions, cache } from './cache';
|
||||
|
||||
describe('cache', () => {
|
||||
const impl = mock((arg: string) => 'test-' + arg);
|
||||
@@ -69,3 +70,79 @@ describe('cache', () => {
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cache with suffix key', () => {
|
||||
const impl = mock((arg: string) => 'test-' + arg);
|
||||
const getKeySuffixImpl: Mock<NonNullable<CacheDefinition<[string], string>['getKeySuffix']>> =
|
||||
mock(() => hash({ test: 1 }));
|
||||
|
||||
let fn: CacheFunction<[string], string>;
|
||||
let testId = 0;
|
||||
let getTtl: () => number;
|
||||
|
||||
beforeEach(() => {
|
||||
impl.mockClear();
|
||||
|
||||
testId += 1;
|
||||
getTtl = () => 1000;
|
||||
|
||||
fn = cache({
|
||||
name: `cache-with-suffix-${testId}`,
|
||||
getKeySuffix: getKeySuffixImpl,
|
||||
tag: (arg) => 'test',
|
||||
get: async (arg: string, options: CacheFunctionOptions) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
return {
|
||||
data: impl(arg),
|
||||
ttl: getTtl(),
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should execute when the key suffix changes even if the args do not change', async () => {
|
||||
const result = await Promise.all([fn('a'), fn('b')]);
|
||||
|
||||
expect(result).toEqual(['test-a', 'test-b']);
|
||||
|
||||
expect(impl).toHaveBeenCalled();
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
|
||||
expect(await fn('a')).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
|
||||
getKeySuffixImpl.mockImplementation(() => hash({ test: 2 }));
|
||||
expect(await fn('a')).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should preserve behaviour even when the returned key suffix is undefined', async () => {
|
||||
// Start with the returned suffix being undefined
|
||||
getKeySuffixImpl.mockImplementation(() => undefined);
|
||||
const result = await fn('a');
|
||||
expect(result).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalled();
|
||||
expect(impl).toHaveBeenCalledTimes(1);
|
||||
|
||||
// The returned suffix changes so we should get the value computed by the function
|
||||
getKeySuffixImpl.mockImplementation(() => hash({ test: 1 }));
|
||||
expect(await fn('a')).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
|
||||
// The returned suffix is undefined again so we should get the value from a previous cache entry
|
||||
getKeySuffixImpl.mockImplementation(() => undefined);
|
||||
expect(await fn('a')).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
|
||||
// The returned suffix goes back to a previous hash so we should the value from a previous cache entry
|
||||
getKeySuffixImpl.mockImplementation(() => hash({ test: 1 }));
|
||||
expect(await fn('a')).toEqual('test-a');
|
||||
|
||||
expect(impl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
+16
-5
@@ -55,6 +55,9 @@ export interface CacheDefinition<Args extends any[], Result> {
|
||||
/** Filter the arguments that should be taken into consideration for the cache key */
|
||||
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) */
|
||||
defaultTtl?: number;
|
||||
|
||||
@@ -222,7 +225,8 @@ export function cache<Args extends any[], Result>(
|
||||
const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs);
|
||||
|
||||
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs);
|
||||
const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
|
||||
|
||||
return await trace(
|
||||
{
|
||||
@@ -239,7 +243,8 @@ export function cache<Args extends any[], Result>(
|
||||
cacheFn.revalidate = async (...rawArgs: Args | [...Args, CacheFunctionOptions]) => {
|
||||
const [args, { signal }] = extractCacheFunctionOptions<Args>(rawArgs);
|
||||
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs);
|
||||
const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
|
||||
|
||||
const result = await revalidate(key, signal, ...args);
|
||||
return result.data;
|
||||
@@ -247,7 +252,8 @@ export function cache<Args extends any[], Result>(
|
||||
|
||||
cacheFn.hasInMemory = async (...args: Args) => {
|
||||
const cacheArgs = cacheDef.getKeyArgs ? cacheDef.getKeyArgs(args) : args;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs);
|
||||
const cacheKeySuffix = cacheDef.getKeySuffix ? cacheDef.getKeySuffix() : undefined;
|
||||
const key = getCacheKey(cacheDef.name, cacheArgs, cacheKeySuffix);
|
||||
const tag = cacheDef.tag?.(...args);
|
||||
|
||||
const memoryEntry = await memoryCache.get({ key, tag });
|
||||
@@ -275,8 +281,13 @@ export function getCache(name: string): CacheFunction<any[], any> | null {
|
||||
/**
|
||||
* Get a cache key for a function and its arguments.
|
||||
*/
|
||||
export function getCacheKey(fnName: string, args: any[]) {
|
||||
let innerKey = args.map((arg) => hashValue(arg)).join(',');
|
||||
export function getCacheKey(fnName: string, args: any[], suffix: string | undefined) {
|
||||
const hashedArgs = args.map((arg) => hashValue(arg));
|
||||
|
||||
if (suffix) {
|
||||
hashedArgs.push(suffix);
|
||||
}
|
||||
let innerKey = hashedArgs.join(',');
|
||||
|
||||
// Avoid crazy long keys, by fallbacking to a hash
|
||||
if (innerKey.length > 400) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { isNodeEmpty } from './document';
|
||||
import { getBlockTitle, isNodeEmpty } from './document';
|
||||
|
||||
describe('isNodeEmpty', () => {
|
||||
it('should return true for a document with an empty paragraph', () => {
|
||||
@@ -54,3 +54,76 @@ describe('isNodeEmpty', () => {
|
||||
).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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -154,7 +154,7 @@ export function isNodeEmpty(
|
||||
export function getBlockTitle(block: DocumentBlock): string {
|
||||
switch (block.type) {
|
||||
case 'expandable': {
|
||||
const titleFragment = getNodeFragmentByType(block, 'title');
|
||||
const titleFragment = getNodeFragmentByType(block, 'expandable-title');
|
||||
if (titleFragment) {
|
||||
return getNodeText(titleFragment);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ describe('getEmojiForCode', () => {
|
||||
|
||||
it('should handle complex codes', () => {
|
||||
expect(getEmojiForCode('1f935-2642')).toEqual('🤵♂️');
|
||||
expect(getEmojiForCode('1f3c3-2642')).toEqual('🏃♂️');
|
||||
expect(getEmojiForCode('1f468-2696')).toEqual('👨⚖️');
|
||||
});
|
||||
|
||||
it('should return an empty string if invalid', () => {
|
||||
|
||||
@@ -67,7 +67,7 @@ export function checkIsSizableImageURL(input: string): boolean {
|
||||
}
|
||||
|
||||
const parsed = new URL(input);
|
||||
if (parsed.pathname.endsWith('.svg')) {
|
||||
if (parsed.pathname.endsWith('.svg') || parsed.pathname.endsWith('.avif')) {
|
||||
return false;
|
||||
}
|
||||
if (!checkIsHttpURL(parsed)) {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { GitBookAPI, ContentAPITokenPayload } from '@gitbook/api';
|
||||
import { ContentAPITokenPayload, GitBookAPI } from '@gitbook/api';
|
||||
import { setTag, setContext } from '@sentry/nextjs';
|
||||
import assertNever from 'assert-never';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import type { ResponseCookie } from 'next/dist/compiled/@edge-runtime/cookies';
|
||||
import { NextResponse, NextRequest } from 'next/server';
|
||||
import hash from 'object-hash';
|
||||
|
||||
import {
|
||||
PublishedContentWithCache,
|
||||
@@ -108,11 +109,14 @@ export async function middleware(request: NextRequest) {
|
||||
const inputURL = stripURLBasePath(url, originBasePath);
|
||||
|
||||
const resolved = await withAPI(
|
||||
new GitBookAPI({
|
||||
endpoint: apiEndpoint,
|
||||
authToken: getDefaultAPIToken(apiEndpoint),
|
||||
userAgent: userAgent(),
|
||||
}),
|
||||
{
|
||||
client: new GitBookAPI({
|
||||
endpoint: apiEndpoint,
|
||||
authToken: getDefaultAPIToken(apiEndpoint),
|
||||
userAgent: userAgent(),
|
||||
}),
|
||||
contextId: undefined,
|
||||
},
|
||||
() => lookupSpaceForURL(mode, request, inputURL),
|
||||
);
|
||||
if ('error' in resolved) {
|
||||
@@ -153,13 +157,17 @@ export async function middleware(request: NextRequest) {
|
||||
// Resolution might have changed the API endpoint
|
||||
apiEndpoint = resolved.apiEndpoint ?? apiEndpoint;
|
||||
|
||||
const contextId = 'site' in resolved ? resolved.contextId : undefined;
|
||||
const nonce = createContentSecurityPolicyNonce();
|
||||
const csp = await withAPI(
|
||||
new GitBookAPI({
|
||||
endpoint: apiEndpoint,
|
||||
authToken: resolved.apiToken,
|
||||
userAgent: userAgent(),
|
||||
}),
|
||||
{
|
||||
client: new GitBookAPI({
|
||||
endpoint: apiEndpoint,
|
||||
authToken: resolved.apiToken,
|
||||
userAgent: userAgent(),
|
||||
}),
|
||||
contextId,
|
||||
},
|
||||
async () => {
|
||||
const [siteData] = await Promise.all([
|
||||
'site' in resolved
|
||||
@@ -198,6 +206,9 @@ export async function middleware(request: NextRequest) {
|
||||
headers.set('x-forwarded-host', inputURL.host);
|
||||
headers.set('origin', inputURL.origin);
|
||||
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-origin-basepath', originBasePath);
|
||||
headers.set('x-gitbook-basepath', joinPath(originBasePath, resolved.basePath));
|
||||
@@ -359,7 +370,7 @@ async function lookupSpaceInSingleMode(url: URL): Promise<LookupResult> {
|
||||
);
|
||||
}
|
||||
|
||||
const apiToken = getDefaultAPIToken(api().endpoint);
|
||||
const apiToken = getDefaultAPIToken(api().client.endpoint);
|
||||
if (!apiToken) {
|
||||
throw new Error(
|
||||
`Missing GITBOOK_TOKEN environment variable. It should be passed when using GITBOOK_MODE=single.`,
|
||||
@@ -470,8 +481,16 @@ async function lookupSiteOrSpaceInMultiIdMode(
|
||||
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({
|
||||
endpoint: apiEndpoint ?? api().endpoint,
|
||||
endpoint: apiEndpoint ?? api().client.endpoint,
|
||||
authToken: apiToken,
|
||||
userAgent: userAgent(),
|
||||
});
|
||||
@@ -479,13 +498,15 @@ async function lookupSiteOrSpaceInMultiIdMode(
|
||||
// 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)
|
||||
if (source.kind === 'space') {
|
||||
await withAPI(gitbookAPI, () => getSpace.revalidate(source.id, undefined));
|
||||
await withAPI({ client: gitbookAPI, contextId }, () =>
|
||||
getSpace.revalidate(source.id, undefined),
|
||||
);
|
||||
}
|
||||
|
||||
// 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)
|
||||
if (source.kind === 'site') {
|
||||
await withAPI(gitbookAPI, () =>
|
||||
await withAPI({ client: gitbookAPI, contextId }, () =>
|
||||
getPublishedContentSite.revalidate({
|
||||
organizationId: decoded.organization,
|
||||
siteId: source.id,
|
||||
@@ -701,6 +722,7 @@ async function lookupSpaceByAPI(
|
||||
siteSpace: data.siteSpace,
|
||||
organization: data.organization,
|
||||
shareKey: data.shareKey,
|
||||
...(data.contextId ? { contextId: data.contextId } : {}),
|
||||
}
|
||||
: {}),
|
||||
} as PublishedContentWithCache;
|
||||
@@ -748,7 +770,7 @@ function getLookupResultForVisitorAuth(
|
||||
),
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
maxAge: 7 * 24 * 60 * 60,
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ import plugin from 'tailwindcss/plugin';
|
||||
import { hexToRgb, shadesOfColor } from './src/lib/colors';
|
||||
|
||||
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];
|
||||
export const opacities = [0, 4, 8, 12, 16, 24, 40, 64, 72, 88, 96, 100];
|
||||
|
||||
/**
|
||||
* Generate a Tailwind color shades from a variable.
|
||||
@@ -72,9 +72,8 @@ const config: Config = {
|
||||
/** primary-color used to accent elements, these colors remain unchanged when toggling between the CustomizationBackground options**/
|
||||
primary: generateVarShades('primary-color'),
|
||||
'contrast-primary': 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'),
|
||||
tint: generateVarShades('primary-color'),
|
||||
'contrast-tint': generateVarShades('contrast-primary'),
|
||||
|
||||
'header-background': generateVarShades('header-background'),
|
||||
'header-link': generateVarShades('header-link'),
|
||||
@@ -209,6 +208,10 @@ const config: Config = {
|
||||
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)',
|
||||
},
|
||||
scale: {
|
||||
'98': '0.98',
|
||||
'102': '1.02',
|
||||
},
|
||||
},
|
||||
opacity: opacity(),
|
||||
},
|
||||
@@ -232,7 +235,12 @@ const config: Config = {
|
||||
/**
|
||||
* Variant when the space is configured with a theme matching background.
|
||||
*/
|
||||
addVariant('plain-background', 'html.plain-background &');
|
||||
addVariant('tint', 'html.tint &');
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
Reference in New Issue
Block a user