Compare commits

...

19 Commits

Author SHA1 Message Date
Vib Bhardwaj 7ec64dad58 rm public 2024-12-26 20:16:02 +00:00
Vib Bhardwaj 326d674254 remove next assets 2024-12-26 20:14:00 +00:00
Vib Bhardwaj a6a78ce5ac ignore shiki 2024-12-26 14:18:38 +00:00
Vib Bhardwaj 56cb2f4c9a wip 2024-12-23 15:29:31 +00:00
Amrit Kahlon f92e90603f Prevent multiple versions of codemirror from loading (#2660)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-12-21 23:46:16 +01:00
Samy Pessé 14172791e9 Track click on links for site insights (#2659) 2024-12-21 18:18:30 +01:00
Samy Pessé e4e2f524d4 Track site insight event when opening scalar client (#2658) 2024-12-21 15:57:10 +01:00
Amrit Kahlon fc7b16f6a7 Update scalar dependency (#2652) 2024-12-20 23:16:11 +01:00
Samy Pessé 6ba3ae74d5 Workaround until referrer is accepted by API as an empty string (#2656) 2024-12-20 19:23:52 +01:00
Samy Pessé c71d1598d8 Insights site events support (#2655) 2024-12-20 19:06:50 +01:00
Greg Bergé 5950657b0e Fix emojis display (#2648) 2024-12-20 11:30:56 +01:00
Samy Pessé 0e1a48cd06 Upgrade bun and setup-bun, switch to text lockfile (#2651)
Co-authored-by: Greg Bergé <berge.greg@gmail.com>
2024-12-20 11:19:54 +01:00
spastorelli 98245e5f20 Adapt code to pull token from customer backend generated custom cookies (#2650)
Co-authored-by: Steven Hall <steven@gitbook.io>
2024-12-19 18:29:32 +01:00
Zeno Kapitein 0b6ddca981 Fix variant selector for non-default themes (#2649) 2024-12-19 12:28:13 +01:00
spastorelli ea1468c892 Send redirectOnError param to getPublishedContent when token is pulled from cookie (#2626) 2024-12-19 11:16:06 +01:00
Greg Bergé e8e64bf510 Fix bullet list display on full size blocks (#2646) 2024-12-18 13:55:18 +01:00
Greg Bergé aaf8daf0d7 Improve search UI (#2643) 2024-12-18 13:42:47 +01:00
Zeno Kapitein 8af1abc4e1 Improve contrast of search box placeholder (#2639) 2024-12-18 12:14:06 +01:00
Zeno Kapitein 48ab59feb3 Improve contrast of list decoration (#2638) 2024-12-18 11:49:01 +01:00
100 changed files with 3439 additions and 856 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"ignore": [
"node_modules",
"dist",
"public"
]
}
+1
View File
@@ -0,0 +1 @@
1.1.40
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Adapt code to pull token from customer backend generated custom cookies
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Add an optional client context to get a callback called when the Scalar client is opened for a block.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve contrast of search box placeholder
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Track events for site insights using the new dedicated API.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve colour contrast of list item decoration
+6
View File
@@ -0,0 +1,6 @@
---
'@gitbook/react-contentkit': minor
'gitbook': minor
---
Send redirectOnError param to getPublishedContent when token is pulled from cookie
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Track clicks on links (header, footer, content) for site insights.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix emojis display
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Prevent codemirror from loading multiple versions in scalar
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix variant selector contrast for non-default themes
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Updated scalar depdenency
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix bullet list display on full size blocks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Track an event into site insights when visitor is opening the Scalar API client.
+18
View File
@@ -0,0 +1,18 @@
name: 'Setup Bun'
description: 'Install Bun and cache dependencies'
runs:
using: 'composite'
steps:
# We cache dependencies even if Bun is fast to avoid downloading fontawesome too many times
# and impacting bandwidth there.
- name: Cache bun
uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Setup bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: '.bun-version'
+19 -35
View File
@@ -5,7 +5,7 @@ on:
branches: branches:
- main - main
env: env:
NPMRC_FONT_AWESOME_TOKEN: ${{ secrets.NPMRC_FONT_AWESOME_TOKEN }} NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
jobs: jobs:
deploy: deploy:
name: Deploy to Cloudflare Pages name: Deploy to Cloudflare Pages
@@ -22,10 +22,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -102,10 +100,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
- name: Setup Playwright - name: Setup Playwright
@@ -128,10 +124,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -147,10 +141,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -162,10 +154,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -177,10 +167,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -191,16 +179,14 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Build (Open Source) name: Build (Open Source)
env: env:
NPMRC_FONT_AWESOME_TOKEN: '' NPM_TOKEN_READONLY: ''
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install
env: env:
PUPPETEER_SKIP_DOWNLOAD: 1 PUPPETEER_SKIP_DOWNLOAD: 1
- run: bun run build - run: bun run build
@@ -210,10 +196,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
+5 -9
View File
@@ -17,10 +17,8 @@ jobs:
with: with:
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
fetch-depth: 0 fetch-depth: 0
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
@@ -34,7 +32,7 @@ jobs:
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created # Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761 # https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }} GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }} NPM_TOKEN_READONLY: ${{ secrets.NPM_TOKEN_READONLY }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
release-preview: release-preview:
@@ -45,10 +43,8 @@ jobs:
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Setup bun - name: Setup Bun
uses: oven-sh/setup-bun@v1 uses: ./.github/composite/setup-bun
with:
bun-version: 1.1.18
- name: Install dependencies - name: Install dependencies
run: bun install --frozen-lockfile run: bun install --frozen-lockfile
env: env:
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -1,2 +1,2 @@
[install.scopes] [install.scopes]
"awesome.me" = { token = "$NPMRC_FONT_AWESOME_TOKEN", url = "https://npm.fontawesome.com/" } "gitbook" = { token = "$NPM_TOKEN_READONLY", url = "https://registry.npmjs.org" }
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
+43 -33
View File
@@ -1,35 +1,45 @@
{ {
"name": "gitbook", "name": "gitbook",
"version": "0.1.0", "version": "0.1.0",
"devDependencies": { "type": "module",
"@changesets/cli": "^2.27.7", "devDependencies": {
"prettier": "^3.0.3", "@changesets/cli": "^2.27.7",
"turbo": "^2.1.2" "prettier": "^3.0.3",
}, "turbo": "^2.1.2"
"packageManager": "bun@1.1.18", },
"patchedDependencies": { "packageManager": "bun@1.1.18",
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch", "patchedDependencies": {
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch" "@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
}, "@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
"private": true, },
"scripts": { "overrides": {
"dev": "turbo run dev", "@codemirror/state": "6.4.1"
"build": "turbo run build", },
"build:cloudflare": "turbo run build:cloudflare", "private": true,
"lint": "turbo run lint", "scripts": {
"lint:fix": "turbo run lint -- --fix", "dev": "turbo run dev",
"typecheck": "turbo run typecheck", "build": "turbo run build",
"format": "prettier ./ --ignore-unknown --write", "build:cloudflare": "turbo run build:cloudflare",
"format:check": "prettier ./ --ignore-unknown --list-different", "lint": "turbo run lint",
"unit": "turbo run unit", "lint:fix": "turbo run lint -- --fix",
"e2e": "turbo run e2e", "typecheck": "turbo run typecheck",
"changeset": "changeset", "format": "prettier ./ --ignore-unknown --write",
"release": "turbo run release && changeset publish", "format:check": "prettier ./ --ignore-unknown --list-different",
"release:preview": "turbo run release:preview", "unit": "turbo run unit",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local", "e2e": "turbo run e2e",
"clean": "turbo run clean" "changeset": "changeset",
}, "release": "turbo run release && changeset publish",
"workspaces": [ "release:preview": "turbo run release:preview",
"packages/*" "download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
] "clean": "turbo run clean"
},
"workspaces": [
"packages/*"
],
"dependencies": {
"@babel/cli": "^7.26.4",
"@babel/preset-env": "^7.26.0",
"@babel/preset-react": "^7.26.3",
"tsconfig-paths": "^4.2.0"
}
} }
File diff suppressed because it is too large Load Diff
+221 -2
View File
@@ -6,20 +6,29 @@ import {
CustomizationHeaderPreset, CustomizationHeaderPreset,
CustomizationIconsStyle, CustomizationIconsStyle,
CustomizationLocale, CustomizationLocale,
CustomizationSidebarBackgroundStyle,
CustomizationSidebarListStyle,
CustomizationThemeMode, CustomizationThemeMode,
SiteCustomizationSettings, SiteCustomizationSettings,
} from '@gitbook/api'; } from '@gitbook/api';
import { test, expect, Page } from '@playwright/test'; import { test, expect, Page, BrowserContext } from '@playwright/test';
import deepMerge from 'deepmerge'; import deepMerge from 'deepmerge';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import rison from 'rison'; import rison from 'rison';
import { DeepPartial } from 'ts-essentials'; import { DeepPartial } from 'ts-essentials';
import {
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
VISITOR_TOKEN_COOKIE,
} from '@/lib/visitor-token';
import { getContentTestURL } from '../tests/utils'; import { getContentTestURL } from '../tests/utils';
interface Test { interface Test {
name: string; name: string;
url: string; // URL to visit for testing url: string; // URL to visit for testing
cookies?: Parameters<BrowserContext['addCookies']>[0];
run?: (page: Page) => Promise<unknown>; // The test to run run?: (page: Page) => Promise<unknown>; // The test to run
fullPage?: boolean; // Whether the test should be fullscreened during testing fullPage?: boolean; // Whether the test should be fullscreened during testing
screenshot?: false; // Should a screenshot be stored screenshot?: false; // Should a screenshot be stored
@@ -867,6 +876,60 @@ const testCases: TestsCase[] = [
}, },
], ],
}, },
{
name: 'Visitor Auth - Site (redirects to fallback/auth URL)',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/va-site-redirects-fallback/`,
tests: [
{
name: 'Redirect to fallback on invalid token pulled from cookie',
url: '',
screenshot: false,
cookies: (() => {
const basePath = '/va-site-redirects-fallback/';
const invalidToken = jwt.sign(
{
name: 'gitbook-open-tests',
},
'invalidKey',
{
expiresIn: '24h',
},
);
return [
{
name: getVisitorAuthCookieName(basePath),
value: getVisitorAuthCookieValue(basePath, invalidToken),
httpOnly: true,
},
];
})(),
run: async (page) => {
await expect(page).toHaveURL(/https:\/\/www.google.com/);
},
},
{
name: 'Show error message when invalid token is passed to url',
screenshot: false,
url: (() => {
const token = jwt.sign(
{
name: 'gitbook-open-tests',
},
'invalidKey',
{
expiresIn: '24h',
},
);
return `?jwt_token=${token}`;
})(),
run: async (page) => {
await expect(page.locator('pre')).toContainText(
'Error while validating the JWT token. Reason: The token signature is invalid.',
);
},
},
],
},
{ {
name: 'Languages', name: 'Languages',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
@@ -1022,6 +1085,149 @@ const testCases: TestsCase[] = [
}, },
], ],
}, },
{
name: 'Adaptive Content - Public',
baseUrl: `https://gitbook-open-e2e-sites.gitbook.io/adaptive-content-public/`,
tests: [
{
name: 'No custom cookie',
url: '',
run: async (page) => {
const welcomePage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Welcome Page' });
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Alpha User' });
const betaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Beta User' });
await expect(welcomePage).toBeVisible();
await expect(alphaUserPage).toHaveCount(0);
await expect(betaUserPage).toHaveCount(0);
},
},
{
name: 'Custom cookie with isAlphaUser claim',
cookies: (() => {
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
const token = jwt.sign(
{
name: 'gitbook-open-tests',
isAlphaUser: true,
},
privateKey,
{
expiresIn: '24h',
},
);
return [
{
name: VISITOR_TOKEN_COOKIE,
value: token,
httpOnly: true,
},
];
})(),
url: '',
run: async (page) => {
const welcomePage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Welcome Page' });
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Alpha User' });
const betaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Beta User' });
await expect(welcomePage).toBeVisible();
await expect(alphaUserPage).toBeVisible();
await expect(betaUserPage).toHaveCount(0);
},
},
{
name: 'Custom cookie with isBetaUser claim',
cookies: (() => {
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
const token = jwt.sign(
{
name: 'gitbook-open-tests',
isBetaUser: true,
},
privateKey,
{
expiresIn: '24h',
},
);
return [
{
name: VISITOR_TOKEN_COOKIE,
value: token,
httpOnly: true,
},
];
})(),
url: '',
run: async (page) => {
const welcomePage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Welcome Page' });
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Alpha User' });
const betaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Beta User' });
await expect(welcomePage).toBeVisible();
await expect(betaUserPage).toBeVisible();
await expect(alphaUserPage).toHaveCount(0);
},
},
{
name: 'Custom cookie with isAlphaUser & isBetaUser claims',
cookies: (() => {
const privateKey = '4ddd3c2f-e4b7-4e73-840b-526c3be19746';
const token = jwt.sign(
{
name: 'gitbook-open-tests',
isAlphaUser: true,
isBetaUser: true,
},
privateKey,
{
expiresIn: '24h',
},
);
return [
{
name: VISITOR_TOKEN_COOKIE,
value: token,
httpOnly: true,
},
];
})(),
url: '',
run: async (page) => {
const welcomePage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Welcome Page' });
const alphaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Alpha User' });
const betaUserPage = page
.locator('a[class*="group\\/toclink"]')
.filter({ hasText: 'Beta User' });
await expect(welcomePage).toBeVisible();
await expect(betaUserPage).toBeVisible();
await expect(alphaUserPage).toBeVisible();
},
},
],
},
{ {
name: 'Tables', name: 'Tables',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/', baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
@@ -1112,9 +1318,18 @@ for (const testCase of testCases) {
test.describe(testCase.name, () => { test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) { for (const testEntry of testCase.tests) {
const testFn = testEntry.only ? test.only : test; const testFn = testEntry.only ? test.only : test;
testFn(testEntry.name, async ({ page, baseURL }) => { testFn(testEntry.name, async ({ page, baseURL, context }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl); const contentUrl = new URL(testEntry.url, testCase.baseUrl);
const url = getContentTestURL(contentUrl.toString(), baseURL); const url = getContentTestURL(contentUrl.toString(), baseURL);
if (testEntry.cookies) {
await context.addCookies(
testEntry.cookies.map((cookie) => ({
...cookie,
domain: new URL(url).host,
path: '/',
})),
);
}
await page.goto(url); await page.goto(url);
if (testEntry.run) { if (testEntry.run) {
await testEntry.run(page); await testEntry.run(page);
@@ -1152,6 +1367,10 @@ function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): s
font: CustomizationFont.Inter, font: CustomizationFont.Inter,
background: CustomizationBackground.Plain, background: CustomizationBackground.Plain,
icons: CustomizationIconsStyle.Regular, icons: CustomizationIconsStyle.Regular,
sidebar: {
background: CustomizationSidebarBackgroundStyle.Default,
list: CustomizationSidebarListStyle.Default,
},
}, },
internationalization: { internationalization: {
locale: CustomizationLocale.En, locale: CustomizationLocale.En,
+4 -3
View File
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static" "clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
}, },
"dependencies": { "dependencies": {
"@gitbook/api": "^0.81.0", "@gitbook/api": "^0.85.0",
"@gitbook/cache-do": "workspace:*", "@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*", "@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*", "@gitbook/icons": "workspace:*",
@@ -43,7 +43,7 @@
"memoizee": "^0.4.15", "memoizee": "^0.4.15",
"next": "14.2.15", "next": "14.2.15",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"nuqs": "^1.17.4", "nuqs": "^2.2.3",
"object-hash": "^3.0.0", "object-hash": "^3.0.0",
"openapi-types": "^12.1.3", "openapi-types": "^12.1.3",
"p-map": "^7.0.0", "p-map": "^7.0.0",
@@ -64,7 +64,8 @@
"tailwind-merge": "^2.2.0", "tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2", "tailwind-shades": "^1.1.2",
"unified": "^11.0.4", "unified": "^11.0.4",
"url-join": "^5.0.0" "url-join": "^5.0.0",
"usehooks-ts": "^3.1.0"
}, },
"devDependencies": { "devDependencies": {
"@argos-ci/playwright": "^2.0.0", "@argos-ci/playwright": "^2.0.0",
@@ -1,11 +1,15 @@
import { TrackPageViewEvent } from '@/components/Insights';
import { getSpaceLanguage, t } from '@/intl/server'; import { getSpaceLanguage, t } from '@/intl/server';
import { getSiteData } from '@/lib/api'; import { getSiteData, getSpaceContentData } from '@/lib/api';
import { getSiteContentPointer } from '@/lib/pointer'; import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
export default async function NotFound() { export default async function NotFound() {
const pointer = getSiteContentPointer(); const pointer = getSiteContentPointer();
const { customization } = await getSiteData(pointer); const [{ space }, { customization }] = await Promise.all([
getSpaceContentData(pointer, pointer.siteShareKey),
getSiteData(pointer),
]);
const language = getSpaceLanguage(customization); const language = getSpaceLanguage(customization);
@@ -19,6 +23,9 @@ export default async function NotFound() {
</h2> </h2>
<p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p> <p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p>
</div> </div>
{/* Track the page not found as a page view */}
<TrackPageViewEvent pageId={null} revisionId={space.revision} />
</div> </div>
); );
} }
@@ -9,7 +9,6 @@ import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
import { getPagePath, resolveFirstDocument } from '@/lib/pages'; import { getPagePath, resolveFirstDocument } from '@/lib/pages';
import { ContentRefContext } from '@/lib/references'; import { ContentRefContext } from '@/lib/references';
import { isSpaceIndexable, isPageIndexable } from '@/lib/seo'; import { isSpaceIndexable, isPageIndexable } from '@/lib/seo';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils'; import { getContentTitle } from '@/lib/utils';
import { PageClientLayout } from './PageClientLayout'; import { PageClientLayout } from './PageClientLayout';
@@ -1,6 +1,7 @@
import { CustomizationThemeMode } from '@gitbook/api'; import { CustomizationThemeMode } from '@gitbook/api';
import { Metadata, Viewport } from 'next'; import { Metadata, Viewport } from 'next';
import { headers } from 'next/headers'; import { headers } from 'next/headers';
import { NuqsAdapter } from 'nuqs/adapters/next/app';
import React from 'react'; import React from 'react';
import * as ReactDOM from 'react-dom'; import * as ReactDOM from 'react-dom';
@@ -55,46 +56,48 @@ export default async function ContentLayout(props: { children: React.ReactNode }
}); });
return ( return (
<ClientContexts <NuqsAdapter>
nonce={nonce} <ClientContexts
forcedTheme={ nonce={nonce}
getQueryStringTheme() ?? forcedTheme={
(customization.themes.toggeable ? undefined : customization.themes.default) getQueryStringTheme() ??
} (customization.themes.toggeable ? undefined : customization.themes.default)
> }
<SpaceLayout
space={space}
contentTarget={contentTarget}
site={site}
spaces={spaces}
sections={sections}
customization={customization}
pages={pages}
ancestors={ancestors}
content={content}
> >
{children} <SpaceLayout
</SpaceLayout> space={space}
contentTarget={contentTarget}
site={site}
spaces={spaces}
sections={sections}
customization={customization}
pages={pages}
ancestors={ancestors}
content={content}
>
{children}
</SpaceLayout>
{scripts.length > 0 ? ( {scripts.length > 0 ? (
<> <>
<LoadIntegrations /> <LoadIntegrations />
{scripts.map(({ script }) => ( {scripts.map(({ script }) => (
<script key={script} async src={script} nonce={nonce} /> <script key={script} async src={script} nonce={nonce} />
))} ))}
</> </>
) : null} ) : null}
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? ( {scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
<React.Suspense fallback={null}> <React.Suspense fallback={null}>
<CookiesToast privacyPolicy={customization.privacyPolicy.url} /> <CookiesToast privacyPolicy={customization.privacyPolicy.url} />
</React.Suspense> </React.Suspense>
) : null} ) : null}
<RocketLoaderDetector nonce={nonce} /> <RocketLoaderDetector nonce={nonce} />
<AdminToolbar space={space} content={content} /> <AdminToolbar space={space} content={content} />
</ClientContexts> </ClientContexts>
</NuqsAdapter>
); );
} }
@@ -11,23 +11,24 @@ import { Metadata } from 'next';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import * as React from 'react'; import * as React from 'react';
import { DocumentView } from '@/components/DocumentView'; import { DocumentView } from '../../../../components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark'; import { TrademarkLink } from '../../../../components/TableOfContents/Trademark';
import { PolymorphicComponentProp } from '@/components/utils/types'; import { PolymorphicComponentProp } from '../../../../components/utils/types';
import { getSpaceLanguage } from '@/intl/server'; import { getSpaceLanguage } from '../../../../intl/server';
import { tString } from '@/intl/translate'; import { tString } from '../../../../intl/translate';
import { import {
getDocument, getDocument,
getSpace, getSpace,
getSpaceCustomization, getSpaceCustomization,
getSpaceContentData, getSpaceContentData,
getSiteData, getSiteData,
} from '@/lib/api'; } from '../../../../lib/api';
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links'; import { pagePDFContainerId, PageHrefContext, absoluteHref } from '../../../../lib/links';
import { resolvePageId } from '@/lib/pages'; import { resolvePageId } from '../../../../lib/pages';
import { ContentRefContext, resolveContentRef } from '@/lib/references'; import { ContentRefContext, resolveContentRef } from '../../../../lib/references';
import { tcls } from '@/lib/tailwind'; import { tcls } from '../../../../lib/tailwind';
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls'; import { SiteContentPointer, SpaceContentPointer } from '../../../../lib/api';
import { PDFSearchParams, getPDFSearchParams } from '../../../../lib/urls';
import './pdf.css'; import './pdf.css';
import { PageControlButtons } from './PageControlButtons'; import { PageControlButtons } from './PageControlButtons';
@@ -55,7 +56,9 @@ export async function generateMetadata(): Promise<Metadata> {
* Render a space as a standalone HTML page that can be printed as a PDF. * Render a space as a standalone HTML page that can be printed as a PDF.
*/ */
export default async function PDFHTMLOutput(props: { searchParams: { [key: string]: string } }) { export default async function PDFHTMLOutput(props: { searchParams: { [key: string]: string } }) {
const pointer = getSiteOrSpacePointerForPDF(); const pointer = {"siteId": "site_dIY9z", "spaceId": "-MdwVZ6HOZriajCf5nXH", "siteSpaceId": "sitesp_mX2p5", "organizationId": "-M4tdxG8qotLgGZnLpFR"} as SiteContentPointer | SpaceContentPointer;
console.log('vib pointer', JSON.stringify(pointer));
const searchParams = new URLSearchParams(props.searchParams); const searchParams = new URLSearchParams(props.searchParams);
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams)); const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
@@ -0,0 +1,27 @@
const { renderToPipeableStream } = require('react-dom/server');
const PDFHTMLOutput = require('./page');
//import { renderToPipeableStream, renderToStaticNodeStream } from 'react-dom/server';
//import PDFHTMLOutput from './page';
//import fs from 'fs';
//import React from 'react';
const fs = require('fs');
const React = require('react');
// Create a writable stream to save the HTML to a file
const writeStream = fs.createWriteStream('output.html');
// Start the server-side rendering with renderToPipeableStream
const { pipe } = renderToPipeableStream(React.createElement(PDFHTMLOutput, {searchParams : {'a': 'b'}}) as any);
// Pipe the render stream to the writable file stream
pipe(writeStream);
// Optionally, you can handle errors and closure
writeStream.on('finish', () => {
console.log('HTML has been written to output.html');
});
writeStream.on('error', (err: any) => {
console.error('Error writinsg to file:', err);
});
@@ -6,9 +6,10 @@ import * as React from 'react';
import { Button } from '@/components/primitives'; import { Button } from '@/components/primitives';
import { useLanguage } from '@/intl/client'; import { useLanguage } from '@/intl/client';
import { t, tString } from '@/intl/translate'; import { t, tString } from '@/intl/translate';
import { isCookiesTrackingDisabled, setCookiesTracking } from '@/lib/analytics';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { isCookiesTrackingDisabled, setCookiesTracking } from '../Insights';
/** /**
* Toast to accept or reject the use of cookies. * Toast to accept or reject the use of cookies.
*/ */
@@ -34,6 +34,10 @@ export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>
href={resolved.href} href={resolved.href}
title={resolved.text} title={resolved.text}
style={style} style={style}
insights={{
target: block.data.ref,
position: 'content',
}}
/> />
); );
} }
@@ -283,9 +283,9 @@ function CodeHighlightToken(props: {
return <>{token.content}</>; return <>{token.content}</>;
} }
if (!token.token.color) { // if (!token.token.color) {
return <>{token.token.content}</>; // return <>{token.token.content}</>;
} // }
return <span style={{ color: token.token.color }}>{token.token.content}</span>; // return <span style={{ color: token.token.color }}>{token.token.content}</span>;
} }
@@ -1,18 +1,21 @@
import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api'; import { DocumentBlockCode, DocumentBlockCodeLine, DocumentInlineAnnotation } from '@gitbook/api';
import { // // @ts-ignore - onigWasm is a Wasm module
createdBundledHighlighter, // import {
ThemedToken, // createdBundledHighlighter,
createCssVariablesTheme, // ThemedToken,
HighlighterGeneric, // createCssVariablesTheme,
} from 'shiki/core'; // HighlighterGeneric,
import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma'; // } from 'shiki/core';
import { bundledLanguages } from 'shiki/langs'; // // @ts-ignore - onigWasm is a Wasm module
// @ts-ignore - onigWasm is a Wasm module // import { loadWasm, createOnigurumaEngine } from 'shiki/engine/oniguruma';
import onigWasm from 'shiki/onig.wasm?module'; // // @ts-ignore - onigWasm is a Wasm module
// import { bundledLanguages } from 'shiki/langs';
// // @ts-ignore - onigWasm is a Wasm module
// import onigWasm from 'shiki/onig.wasm?module';
import { asyncMutexFunction, singleton } from '@/lib/async'; // import { asyncMutexFunction, singleton } from '@/lib/async';
import { getNodeText } from '@/lib/document'; import { getNodeText } from '@/lib/document';
import { trace } from '@/lib/tracing'; // import { trace } from '@/lib/tracing';
export type HighlightLine = { export type HighlightLine = {
highlighted: boolean; highlighted: boolean;
@@ -20,86 +23,88 @@ export type HighlightLine = {
}; };
export type HighlightToken = export type HighlightToken =
| { type: 'plain'; content: string } | { type: 'plain'; content: string }
| { type: 'shiki'; token: ThemedToken } | { type: 'inline'; inline: DocumentInlineAnnotation; children: HighlightToken[] };
| { type: 'inline'; inline: DocumentInlineAnnotation; children: HighlightToken[] };
type InlineIndexed = { inline: any; start: number; end: number }; // | { type: 'shiki'; token: ThemedToken }
type PositionedToken = ThemedToken & { start: number; end: number }; // type InlineIndexed = { inline: any; start: number; end: number };
/** // type PositionedToken = ThemedToken & { start: number; end: number };
* Highlight a code block while preserving inline elements.
*/ // /**
// * Highlight a code block while preserving inline elements.
// */
export async function highlight(block: DocumentBlockCode): Promise<HighlightLine[]> { export async function highlight(block: DocumentBlockCode): Promise<HighlightLine[]> {
const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null; return plainHighlighting(block);
if (!langName) { // const langName = block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
// Language not found, fallback to plain highlighting // if (!langName) {
return plainHighlighting(block); // // Language not found, fallback to plain highlighting
} // return plainHighlighting(block);
// }
const inlines: InlineIndexed[] = []; // const inlines: InlineIndexed[] = [];
const code = getPlainCodeBlock(block, inlines); // const code = getPlainCodeBlock(block, inlines);
inlines.sort((a, b) => { // inlines.sort((a, b) => {
return a.start - b.start; // return a.start - b.start;
}); // });
const highlighter = await loadHighlighter(); // const highlighter = await loadHighlighter();
await loadHighlighterLanguage(highlighter, langName); // await loadHighlighterLanguage(highlighter, langName);
const lines = highlighter.codeToTokensBase(code, { // const lines = highlighter.codeToTokensBase(code, {
lang: langName, // lang: langName,
tokenizeMaxLineLength: 400, // tokenizeMaxLineLength: 400,
}); // });
let currentIndex = 0; // let currentIndex = 0;
return lines.map((tokens, index) => { // return lines.map((tokens, index) => {
const lineBlock = block.nodes[index]; // const lineBlock = block.nodes[index];
const result: HighlightToken[] = []; // const result: HighlightToken[] = [];
const eatToken = (): PositionedToken | null => { // const eatToken = (): PositionedToken | null => {
const token = tokens.shift(); // const token = tokens.shift();
if (token) { // if (token) {
currentIndex += token.content.length; // currentIndex += token.content.length;
} // }
return token // return token
? { ...token, start: currentIndex - token.content.length, end: currentIndex } // ? { ...token, start: currentIndex - token.content.length, end: currentIndex }
: null; // : null;
}; // };
while (tokens.length > 0) { // while (tokens.length > 0) {
result.push(...matchTokenAndInlines(eatToken, inlines)); // result.push(...matchTokenAndInlines(eatToken, inlines));
} // }
currentIndex += 1; // for the \n // currentIndex += 1; // for the \n
return { // return {
highlighted: !!lineBlock.data.highlighted, // highlighted: !!lineBlock.data.highlighted,
tokens: result, // tokens: result,
}; // };
}); // });
} }
/** // /**
* Validate a language name. // * Validate a language name.
*/ // */
function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null { // function getLanguageForSyntax(syntax: string): keyof typeof bundledLanguages | null {
// @ts-ignore // // @ts-ignore
const lang = bundledLanguages[syntax]; // const lang = bundledLanguages[syntax];
if (!lang) { // if (!lang) {
return null; // return null;
} // }
// @ts-ignore // // @ts-ignore
return syntax; // return syntax;
} // }
/** // /**
* Parse a code block without highlighting it. // * Parse a code block without highlighting it.
*/ // */
export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] { export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
return block.nodes.map((lineBlock) => { return block.nodes.map((lineBlock: any) => {
const tokens: HighlightToken[] = []; const tokens: HighlightToken[] = [];
for (const node of lineBlock.nodes) { for (const node of lineBlock.nodes) {
@@ -108,17 +113,6 @@ export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
type: 'plain', type: 'plain',
content: getNodeText(node), content: getNodeText(node),
}); });
} else {
tokens.push({
type: 'inline',
inline: node,
children: [
{
type: 'plain',
content: getNodeText(node),
},
],
});
} }
} }
@@ -129,214 +123,214 @@ export function plainHighlighting(block: DocumentBlockCode): HighlightLine[] {
}); });
} }
function matchTokenAndInlines( // function matchTokenAndInlines(
eat: () => PositionedToken | null, // eat: () => PositionedToken | null,
allInlines: InlineIndexed[], // allInlines: InlineIndexed[],
): HighlightToken[] { // ): HighlightToken[] {
const initialToken = eat(); // const initialToken = eat();
if (!initialToken) { // if (!initialToken) {
return []; // return [];
} // }
const inlines = allInlines.filter( // const inlines = allInlines.filter(
(inline) => inline.start >= initialToken.start && inline.start < initialToken.end, // (inline) => inline.start >= initialToken.start && inline.start < initialToken.end,
); // );
let token = initialToken; // let token = initialToken;
const result: HighlightToken[] = []; // const result: HighlightToken[] = [];
const matchAgainstInline = () => { // const matchAgainstInline = () => {
const inline = inlines.shift(); // const inline = inlines.shift();
if (!inline) { // if (!inline) {
result.push({ // result.push({
type: 'shiki', // type: 'shiki',
token, // token,
}); // });
return; // return;
} // }
const [before, afterBefore] = splitPositionedTokenAt(token, inline.start); // const [before, afterBefore] = splitPositionedTokenAt(token, inline.start);
if (before) { // if (before) {
result.push({ // result.push({
type: 'shiki', // type: 'shiki',
token: before, // token: before,
}); // });
} // }
if (!afterBefore) { // if (!afterBefore) {
throw new Error(`expect afterBefore to not be empty`); // throw new Error(`expect afterBefore to not be empty`);
} // }
token = afterBefore; // token = afterBefore;
const children: HighlightToken[] = []; // const children: HighlightToken[] = [];
// If shiki token finished before the end of the annotation or the annotation contains multiple tokens // // If shiki token finished before the end of the annotation or the annotation contains multiple tokens
while (token.end < inline.end) { // while (token.end < inline.end) {
children.push({ // children.push({
type: 'shiki', // type: 'shiki',
token: token, // token: token,
}); // });
const next = eat(); // const next = eat();
if (!next) { // if (!next) {
throw new Error(`expect token to not be empty`); // throw new Error(`expect token to not be empty`);
} // }
token = next; // token = next;
} // }
const [inside, after] = splitPositionedTokenAt(token, inline.end); // const [inside, after] = splitPositionedTokenAt(token, inline.end);
if (!inside) { // if (!inside) {
throw new Error(`expect inside to not be empty`); // throw new Error(`expect inside to not be empty`);
} // }
children.push({ // children.push({
type: 'shiki', // type: 'shiki',
token: inside, // token: inside,
}); // });
result.push({ // result.push({
type: 'inline', // type: 'inline',
inline: inline.inline, // inline: inline.inline,
children, // children,
}); // });
if (after) { // if (after) {
token = after; // token = after;
matchAgainstInline(); // matchAgainstInline();
} // }
}; // };
matchAgainstInline(); // matchAgainstInline();
return result; // return result;
} // }
function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string { // function getPlainCodeBlock(code: DocumentBlockCode, inlines: InlineIndexed[]): string {
let content = ''; // let content = '';
code.nodes.forEach((node, index) => { // code.nodes.forEach((node, index) => {
const lineContent = getPlainCodeBlockLine(node, inlines, content.length); // const lineContent = getPlainCodeBlockLine(node, inlines, content.length);
content += lineContent; // content += lineContent;
if (index < code.nodes.length - 1) { // if (index < code.nodes.length - 1) {
content += '\n'; // content += '\n';
} // }
}); // });
return content; // return content;
} // }
function getPlainCodeBlockLine( // function getPlainCodeBlockLine(
parent: DocumentBlockCodeLine | DocumentInlineAnnotation, // parent: DocumentBlockCodeLine | DocumentInlineAnnotation,
inlines: InlineIndexed[], // inlines: InlineIndexed[],
index: number, // index: number,
): string { // ): string {
let content = ''; // let content = '';
for (const node of parent.nodes) { // for (const node of parent.nodes) {
if (node.object === 'text') { // if (node.object === 'text') {
content += cleanupLine(node.leaves.map((leaf) => leaf.text).join('')); // content += cleanupLine(node.leaves.map((leaf) => leaf.text).join(''));
} else { // } else {
const start = index + content.length; // const start = index + content.length;
content += getPlainCodeBlockLine(node, inlines, index + content.length); // content += getPlainCodeBlockLine(node, inlines, index + content.length);
const end = index + content.length; // const end = index + content.length;
inlines.push({ // inlines.push({
inline: node, // inline: node,
start, // start,
end, // end,
}); // });
} // }
} // }
return content; // return content;
} // }
function slicePositionedToken( // function slicePositionedToken(
token: PositionedToken, // token: PositionedToken,
relativeStart: number, // relativeStart: number,
relativeLength: number, // relativeLength: number,
): PositionedToken { // ): PositionedToken {
return { // return {
...token, // ...token,
start: token.start + relativeStart, // start: token.start + relativeStart,
end: token.start + relativeStart + relativeLength, // end: token.start + relativeStart + relativeLength,
content: token.content.slice(relativeStart, relativeStart + relativeLength), // content: token.content.slice(relativeStart, relativeStart + relativeLength),
}; // };
} // }
function splitPositionedTokenAt( // function splitPositionedTokenAt(
token: PositionedToken, // token: PositionedToken,
absoluteIndex: number, // absoluteIndex: number,
): [PositionedToken | null, PositionedToken | null] { // ): [PositionedToken | null, PositionedToken | null] {
if (absoluteIndex < token.start || absoluteIndex > token.end) { // if (absoluteIndex < token.start || absoluteIndex > token.end) {
throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`); // throw new Error(`index (${absoluteIndex}) out of bound (${token.start}:${token.end})`);
} // }
const before = slicePositionedToken(token, 0, absoluteIndex - token.start); // const before = slicePositionedToken(token, 0, absoluteIndex - token.start);
const after = slicePositionedToken( // const after = slicePositionedToken(
token, // token,
absoluteIndex - token.start, // absoluteIndex - token.start,
token.end - absoluteIndex, // token.end - absoluteIndex,
); // );
return [ // return [
isEmptyPositionedToken(before) ? null : before, // isEmptyPositionedToken(before) ? null : before,
isEmptyPositionedToken(after) ? null : after, // isEmptyPositionedToken(after) ? null : after,
]; // ];
} // }
function isEmptyPositionedToken(token: PositionedToken): boolean { // function isEmptyPositionedToken(token: PositionedToken): boolean {
return token.start === token.end; // return token.start === token.end;
} // }
/** // /**
* Currently it's possible for some lines to contain \r characters, we need to remove them // * Currently it's possible for some lines to contain \r characters, we need to remove them
* as they are considered as new lines by shikijs. // * as they are considered as new lines by shikijs.
*/ // */
function cleanupLine(line: string): string { // function cleanupLine(line: string): string {
return line.replace(/\r/g, ''); // return line.replace(/\r/g, '');
} // }
const createHighlighter = createdBundledHighlighter<any, any>({ // const createHighlighter = createdBundledHighlighter<any, any>({
langs: bundledLanguages, // langs: bundledLanguages,
themes: {}, // themes: {},
engine: () => createOnigurumaEngine(import('shiki/wasm')), // engine: () => createOnigurumaEngine(import('shiki/wasm')),
}); // });
/** // /**
* Load the highlighter, only once, and reuse it. // * Load the highlighter, only once, and reuse it.
* It makes sure to handle concurrent calls. // * It makes sure to handle concurrent calls.
*/ // */
const loadHighlighter = singleton(async () => { // const loadHighlighter = singleton(async () => {
return await trace('highlighting.loadHighlighter', async () => { // return await trace('highlighting.loadHighlighter', async () => {
if (typeof onigWasm !== 'string') { // if (typeof onigWasm !== 'string') {
// When running bun test, the import is a string, we ignore it and let the module // // When running bun test, the import is a string, we ignore it and let the module
// loads it on its own. // // loads it on its own.
// // //
// Otherwise for Vercel/Cloudflare, we need to load it ourselves. // // Otherwise for Vercel/Cloudflare, we need to load it ourselves.
await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj)); // await loadWasm((obj) => WebAssembly.instantiate(onigWasm, obj));
} // }
const highlighter = await createHighlighter({ // const highlighter = await createHighlighter({
themes: [createCssVariablesTheme()], // themes: [createCssVariablesTheme()],
langs: [], // langs: [],
}); // });
return highlighter; // return highlighter;
}); // });
}); // });
const loadLanguagesMutex = asyncMutexFunction(); // const loadLanguagesMutex = asyncMutexFunction();
async function loadHighlighterLanguage( // async function loadHighlighterLanguage(
highlighter: HighlighterGeneric<any, any>, // highlighter: HighlighterGeneric<any, any>,
lang: keyof typeof bundledLanguages, // lang: keyof typeof bundledLanguages,
) { // ) {
await loadLanguagesMutex.runBlocking(async () => { // await loadLanguagesMutex.runBlocking(async () => {
if (highlighter.getLoadedLanguages().includes(lang)) { // if (highlighter.getLoadedLanguages().includes(lang)) {
return; // return;
} // }
await trace( // await trace(
`highlighting.loadLanguage(${lang})`, // `highlighting.loadLanguage(${lang})`,
async () => await highlighter.loadLanguage(lang), // async () => await highlighter.loadLanguage(lang),
); // );
}); // });
} // }
@@ -6,6 +6,7 @@ import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block'; import { BlockProps } from './Block';
import { Caption } from './Caption'; import { Caption } from './Caption';
import { FileIcon } from './FileIcon'; import { FileIcon } from './FileIcon';
import { Link } from '../primitives';
export async function File(props: BlockProps<DocumentBlockFile>) { export async function File(props: BlockProps<DocumentBlockFile>) {
const { block, context } = props; const { block, context } = props;
@@ -21,9 +22,13 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
return ( return (
<Caption {...props} wrapperStyle={[]}> <Caption {...props} wrapperStyle={[]}>
<a <Link
href={file.downloadURL} href={file.downloadURL}
download={file.name} download={file.name}
insights={{
target: block.data.ref,
position: 'content',
}}
className={tcls( className={tcls(
'group/file', 'group/file',
'flex', 'flex',
@@ -77,7 +82,7 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
{contentType} {contentType}
</div> </div>
</div> </div>
</a> </Link>
</Caption> </Caption>
); );
} }
@@ -25,7 +25,11 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
return ( return (
<Link <Link
href={resolved.href} href={resolved.href}
className="underline underline-offset-2 text-primary hover:text-primary-700 transition-colors " className="underline underline-offset-2 text-primary hover:text-primary-700 transition-colors"
insights={{
target: inline.data.ref,
position: 'content',
}}
> >
<Inlines <Inlines
context={context} context={context}
@@ -38,6 +38,8 @@ export function ListItem(props: BlockProps<DocumentBlockListItem>) {
'[&:is(h2)>div]:mt-0', '[&:is(h2)>div]:mt-0',
'[&:is(h3)>div]:mt-0', '[&:is(h3)>div]:mt-0',
'[&:is(h4)>div]:mt-0', '[&:is(h4)>div]:mt-0',
// Override the "mx-auto" class from UnwrappedBlocks
'mx-0',
)} )}
style="space-y-2 flex flex-col flex-1" style="space-y-2 flex flex-col flex-1"
/> />
@@ -135,7 +137,7 @@ function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.R
className={tcls( className={tcls(
textStyle.textSize, textStyle.textSize,
textStyle.lineHeight, textStyle.lineHeight,
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark/6 dark:text-light/5', 'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark-4 dark:text-light-4',
)} )}
> >
{props.children} {props.children}
@@ -15,5 +15,15 @@ export async function Mention(props: InlineProps<DocumentInlineMention>) {
return null; return null;
} }
return <StyledLink href={resolved.href}>{resolved.text}</StyledLink>; return (
<StyledLink
href={resolved.href}
insights={{
target: inline.data.ref,
position: 'content',
}}
>
{resolved.text}
</StyledLink>
);
} }
@@ -1,4 +1,4 @@
import { DocumentBlockSwagger } from '@gitbook/api'; import { DocumentBlockOpenAPI } from '@gitbook/api';
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import { OpenAPIOperation } from '@gitbook/react-openapi'; import { OpenAPIOperation } from '@gitbook/react-openapi';
import React from 'react'; import React from 'react';
@@ -16,7 +16,7 @@ import './scalar.css';
/** /**
* Render an OpenAPI block. * Render an OpenAPI block.
*/ */
export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) { export async function OpenAPI(props: BlockProps<DocumentBlockOpenAPI>) {
const { block, style } = props; const { block, style } = props;
return ( return (
<div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}> <div className={tcls('w-full', 'flex', 'flex-row', style, 'max-w-full')}>
@@ -27,7 +27,7 @@ export async function OpenAPI(props: BlockProps<DocumentBlockSwagger>) {
); );
} }
async function OpenAPIBody(props: BlockProps<DocumentBlockSwagger>) { async function OpenAPIBody(props: BlockProps<DocumentBlockOpenAPI>) {
const { block, context } = props; const { block, context } = props;
const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef); const { data, specUrl, error } = await fetchOpenAPIBlock(block, context.resolveContentRef);
@@ -1,6 +1,7 @@
import { ContentRef, DocumentTableViewCards } from '@gitbook/api'; import { ContentRef, DocumentTableViewCards } from '@gitbook/api';
import React from 'react'; import React from 'react';
import { Link } from '@/components/primitives';
import { Image } from '@/components/utils'; import { Image } from '@/components/utils';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
@@ -153,17 +154,21 @@ export async function RecordCard(
'before:dark:ring-light/2', 'before:dark:ring-light/2',
] as ClassValue; ] as ClassValue;
if (target) { if (target && targetRef) {
return ( return (
<a <Link
href={target.href} href={target.href}
className={tcls(style, [ className={tcls(style, [
'hover:before:ring-dark/4', 'hover:before:ring-dark/4',
'dark:hover:before:ring-light/4', 'dark:hover:before:ring-light/4',
])} ])}
insights={{
target: targetRef,
position: 'content',
}}
> >
{body} {body}
</a> </Link>
); );
} }
@@ -1,4 +1,4 @@
import { ContentRef, DocumentBlockTable } from '@gitbook/api'; import { ContentRef, ContentRefUser, DocumentBlockTable } from '@gitbook/api';
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
@@ -148,6 +148,17 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
href={ref.href} href={ref.href}
target="_blank" target="_blank"
style={['flex', 'flex-row', 'items-center', 'gap-2']} style={['flex', 'flex-row', 'items-center', 'gap-2']}
insights={
ref.file
? {
target: {
kind: 'file',
file: ref.file.id,
},
position: 'content',
}
: undefined
}
> >
{contentType === 'image' ? ( {contentType === 'image' ? (
<Image <Image
@@ -178,8 +189,9 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
</Tag> </Tag>
); );
case 'content-ref': { case 'content-ref': {
const resolved = value const contentRef = value ? (value as ContentRef) : null;
? await context.resolveContentRef(value as ContentRef, { const resolved = contentRef
? await context.resolveContentRef(contentRef, {
resolveAnchorText: true, resolveAnchorText: true,
iconStyle: ['mr-2', 'text-dark/6', 'dark:text-light/6'], iconStyle: ['mr-2', 'text-dark/6', 'dark:text-light/6'],
}) })
@@ -191,26 +203,51 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
> >
{resolved?.icon ?? null} {resolved?.icon ?? null}
{resolved ? ( {resolved ? (
<StyledLink href={resolved.href}>{resolved.text}</StyledLink> <StyledLink
href={resolved.href}
insights={
contentRef
? {
target: contentRef,
position: 'content',
}
: undefined
}
>
{resolved.text}
</StyledLink>
) : null} ) : null}
</Tag> </Tag>
); );
} }
case 'users': { case 'users': {
const resolved = await Promise.all( const resolved = await Promise.all(
(value as string[]).map((userId) => (value as string[]).map(async (userId) => {
context.resolveContentRef({ const contentRef: ContentRefUser = {
kind: 'user', kind: 'user',
user: userId, user: userId,
}), };
), const resolved = await context.resolveContentRef(contentRef);
if (!resolved) {
return null;
}
return [contentRef, resolved] as const;
}),
); );
return ( return (
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}> <Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
{resolved.filter(filterOutNullable).map((file, index) => ( {resolved.filter(filterOutNullable).map(([contentRef, resolved], index) => (
<StyledLink key={index} href={file.href}> <StyledLink
{file.text} key={index}
href={resolved.href}
insights={{
target: contentRef,
position: 'content',
}}
>
{resolved.text}
</StyledLink> </StyledLink>
))} ))}
</Tag> </Tag>
@@ -40,6 +40,10 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
'dark:text-light/8', 'dark:text-light/8',
'dark:hover:text-light/9', 'dark:hover:text-light/9',
)} )}
insights={{
target: link.to,
position: 'footer',
}}
> >
{link.title} {link.title}
</Link> </Link>
@@ -3,7 +3,7 @@ import { DetailedHTMLProps, HTMLAttributes, useId } from 'react';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
import { Link } from '../primitives'; import { Link, LinkInsightsProps } from '../primitives';
export type DropdownButtonProps<E extends HTMLElement = HTMLElement> = Omit< export type DropdownButtonProps<E extends HTMLElement = HTMLElement> = Omit<
Partial<DetailedHTMLProps<HTMLAttributes<E>, E>>, Partial<DetailedHTMLProps<HTMLAttributes<E>, E>>,
@@ -110,19 +110,22 @@ export function DropdownMenu(props: { children: React.ReactNode }) {
/** /**
* Menu item in a dropdown. * Menu item in a dropdown.
*/ */
export function DropdownMenuItem(props: { export function DropdownMenuItem(
href: string | null; props: {
active?: boolean; href: string | null;
className?: ClassValue; active?: boolean;
children: React.ReactNode; className?: ClassValue;
}) { children: React.ReactNode;
const { children, active = false, href, className } = props; } & LinkInsightsProps,
) {
const { children, active = false, href, className, insights } = props;
if (href) { if (href) {
return ( return (
<Link <Link
href={href} href={href}
prefetch={false} prefetch={false}
insights={insights}
className={tcls( className={tcls(
'px-3 py-1 text-sm rounded straight-corners:rounded-sm', 'px-3 py-1 text-sm rounded straight-corners:rounded-sm',
active ? 'bg-primary/3 dark:bg-light/2 text-primary-600' : null, active ? 'bg-primary/3 dark:bg-light/2 text-primary-600' : null,
@@ -95,7 +95,25 @@ export function Header(props: {
<HeaderLogo site={site} space={space} customization={customization} /> <HeaderLogo site={site} space={space} customization={customization} />
{!hasSiteSections && isMultiVariants ? ( {!hasSiteSections && isMultiVariants ? (
<div className="z-20 shrink hidden sm:block"> <div className="z-20 shrink hidden sm:block">
<SpacesDropdown space={space} spaces={spaces} /> <SpacesDropdown
className={tcls(
!isCustomizationDefault &&
withTopHeader && [
'bg-header-link/2',
'dark:bg-header-link/2',
'text-header-link/8',
'dark:text-header-link/8',
'ring-1',
'ring-header-link/4',
'dark:ring-header-link/4',
'contrast-more:bg-header-background',
'contrast-more:text-header-link',
'contrast-more:ring-header-link',
],
)}
space={space}
spaces={spaces}
/>
</div> </div>
) : null} ) : null}
</div> </div>
@@ -4,6 +4,7 @@ import {
CustomizationHeaderPreset, CustomizationHeaderPreset,
SiteCustomizationSettings, SiteCustomizationSettings,
CustomizationHeaderItem, CustomizationHeaderItem,
ContentRef,
} from '@gitbook/api'; } from '@gitbook/api';
import assertNever from 'assert-never'; import assertNever from 'assert-never';
@@ -35,7 +36,7 @@ export async function HeaderLink(props: {
<Dropdown <Dropdown
className="shrink" className="shrink"
button={(buttonProps) => { button={(buttonProps) => {
if (!target) { if (!target || !link.to) {
return ( return (
<HeaderItemDropdown <HeaderItemDropdown
{...buttonProps} {...buttonProps}
@@ -47,6 +48,7 @@ export async function HeaderLink(props: {
return ( return (
<HeaderLinkNavItem <HeaderLinkNavItem
{...buttonProps} {...buttonProps}
linkTarget={link.to}
linkStyle={linkStyle} linkStyle={linkStyle}
headerPreset={headerPreset} headerPreset={headerPreset}
title={link.title} title={link.title}
@@ -65,12 +67,13 @@ export async function HeaderLink(props: {
); );
} }
if (!target) { if (!target || !link.to) {
return null; return null;
} }
return ( return (
<HeaderLinkNavItem <HeaderLinkNavItem
linkTarget={link.to}
linkStyle={linkStyle} linkStyle={linkStyle}
headerPreset={headerPreset} headerPreset={headerPreset}
title={link.title} title={link.title}
@@ -81,6 +84,7 @@ export async function HeaderLink(props: {
} }
export type HeaderLinkNavItemProps = { export type HeaderLinkNavItemProps = {
linkTarget: ContentRef;
linkStyle: NonNullable<CustomizationHeaderItem['style']>; linkStyle: NonNullable<CustomizationHeaderItem['style']>;
headerPreset: CustomizationHeaderPreset; headerPreset: CustomizationHeaderPreset;
title: string; title: string;
@@ -89,14 +93,15 @@ export type HeaderLinkNavItemProps = {
} & DropdownButtonProps<HTMLElement>; } & DropdownButtonProps<HTMLElement>;
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) { function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
switch (props.linkStyle) { const { linkStyle, ...rest } = props;
switch (linkStyle) {
case 'button-secondary': case 'button-secondary':
case 'button-primary': case 'button-primary':
return <HeaderItemButton {...props} linkStyle={props.linkStyle} />; return <HeaderItemButton {...rest} linkStyle={linkStyle} />;
case 'link': case 'link':
return <HeaderItemLink {...props} />; return <HeaderItemLink {...rest} />;
default: default:
assertNever(props.linkStyle); assertNever(linkStyle);
} }
} }
@@ -105,7 +110,7 @@ function HeaderItemButton(
linkStyle: 'button-secondary' | 'button-primary'; linkStyle: 'button-secondary' | 'button-primary';
}, },
) { ) {
const { linkStyle, headerPreset, title, href, isDropdown, ...rest } = props; const { linkTarget, linkStyle, headerPreset, title, href, isDropdown, ...rest } = props;
const variant = (() => { const variant = (() => {
switch (linkStyle) { switch (linkStyle) {
case 'button-secondary': case 'button-secondary':
@@ -139,6 +144,10 @@ function HeaderItemButton(
), ),
}[linkStyle], }[linkStyle],
)} )}
insights={{
target: linkTarget,
position: 'header',
}}
{...rest} {...rest}
> >
{title} {title}
@@ -158,10 +167,18 @@ function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset
); );
} }
function HeaderItemLink(props: HeaderLinkNavItemProps) { function HeaderItemLink(props: Omit<HeaderLinkNavItemProps, 'linkStyle'>) {
const { headerPreset, title, isDropdown, href, ...rest } = props; const { linkTarget, headerPreset, title, isDropdown, href, ...rest } = props;
return ( return (
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}> <Link
href={href}
className={getHeaderLinkClassName({ headerPreset })}
insights={{
target: linkTarget,
position: 'header',
}}
{...rest}
>
<span className="truncate min-w-0">{title}</span> <span className="truncate min-w-0">{title}</span>
{isDropdown ? <DropdownChevron /> : null} {isDropdown ? <DropdownChevron /> : null}
</Link> </Link>
@@ -198,5 +215,9 @@ async function SubHeaderLink(props: {
return null; return null;
} }
return <DropdownMenuItem href={target.href}>{link.title}</DropdownMenuItem>; return (
<DropdownMenuItem href={target.href} insights={{ target: link.to, position: 'header' }}>
{link.title}
</DropdownMenuItem>
);
} }
@@ -76,7 +76,19 @@ async function MoreMenuLink(props: {
{'links' in link && link.links.length > 0 && ( {'links' in link && link.links.length > 0 && (
<hr className="first:hidden border-t border-light-3 dark:border-dark-3 my-1 -mx-2" /> <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> <DropdownMenuItem
href={target?.href ?? null}
insights={
link.to
? {
target: link.to,
position: 'header',
}
: undefined
}
>
{link.title}
</DropdownMenuItem>
{'links' in link {'links' in link
? link.links.map((subLink, index) => ( ? link.links.map((subLink, index) => (
<MoreMenuLink key={index} {...props} link={subLink} /> <MoreMenuLink key={index} {...props} link={subLink} />
@@ -0,0 +1,293 @@
'use client';
import type * as api from '@gitbook/api';
import { OpenAPIOperationContextProvider } from '@gitbook/react-openapi';
import cookies from 'js-cookie';
import * as React from 'react';
import { useEventCallback, useDebounceCallback } from 'usehooks-ts';
import { getSession } from './sessions';
import { getVisitorId } from './visitorId';
type SiteEventName = api.SiteInsightsEvent['type'];
/**
* Global context for all events in the session.
*/
interface InsightsEventContext {
organizationId: string;
siteId: string;
siteSectionId: string | undefined;
siteSpaceId: string | undefined;
spaceId: string;
siteShareKey: string | undefined;
}
/**
* Context for an event on a page.
*/
interface InsightsEventPageContext {
pageId: string | null;
revisionId: string;
}
/**
* Options when tracking an event.
*/
interface InsightsEventOptions {
/**
* If true, the event will be sent immediately.
* Passes true for events that could cause a page unload.
*/
immediate?: boolean;
}
/**
* Input data for an event.
*/
type TrackEventInput<EventName extends SiteEventName> = { type: EventName } & Omit<
Extract<api.SiteInsightsEvent, { type: EventName }>,
'location' | 'session'
>;
/**
* Callback to track an event.
*/
type TrackEventCallback = <EventName extends SiteEventName>(
event: TrackEventInput<EventName>,
ctx?: InsightsEventPageContext,
options?: InsightsEventOptions,
) => void;
const InsightsContext = React.createContext<TrackEventCallback | null>(null);
interface InsightsProviderProps extends InsightsEventContext {
enabled: boolean;
apiHost: string;
children: React.ReactNode;
}
/**
* Wrap the content of the app with the InsightsProvider to track events.
*/
export function InsightsProvider(props: InsightsProviderProps) {
const { enabled, apiHost, children, ...context } = props;
const visitorIdRef = React.useRef<string | null>(null);
const eventsRef = React.useRef<{
[pathname: string]:
| {
url: string;
events: TrackEventInput<SiteEventName>[];
context: InsightsEventContext;
pageContext?: InsightsEventPageContext;
}
| undefined;
}>({});
/**
* Get the visitor ID and store it in a ref.
*/
React.useEffect(() => {
getVisitorId().then((visitorId) => {
visitorIdRef.current = visitorId;
});
}, []);
/**
* Synchronously flush all the pending events.
*/
const flushEventsSync = useEventCallback(() => {
const session = getSession();
const visitorId = visitorIdRef.current;
if (!visitorId) {
throw new Error('Visitor ID should be set before flushing events');
}
const allEvents: api.SiteInsightsEvent[] = [];
for (const pathname in eventsRef.current) {
const eventsForPathname = eventsRef.current[pathname];
if (!eventsForPathname || !eventsForPathname.events.length) {
continue;
}
if (!eventsForPathname.pageContext) {
console.warn('No page context for flushing events of', pathname, eventsForPathname);
continue;
}
allEvents.push(
...transformEvents({
url: eventsForPathname.url,
events: eventsForPathname.events,
context,
pageContext: eventsForPathname.pageContext,
visitorId,
sessionId: session.id,
}),
);
// Reset the events for the next flush
eventsRef.current[pathname] = {
...eventsForPathname,
events: [],
};
}
if (allEvents.length > 0) {
if (enabled) {
console.log('Sending events', allEvents);
sendEvents({
apiHost,
organizationId: context.organizationId,
siteId: context.siteId,
events: allEvents,
});
} else {
console.log('Skipping sending events', allEvents);
}
}
});
const flushBatchedEvents = useDebounceCallback(async () => {
const visitorId = visitorIdRef.current ?? (await getVisitorId());
visitorIdRef.current = visitorId;
flushEventsSync();
}, 1500);
const trackEvent: TrackEventCallback = useEventCallback(
(
event: TrackEventInput<SiteEventName>,
ctx?: InsightsEventPageContext,
options?: InsightsEventOptions,
) => {
console.log('Logging event', event, ctx);
const pathname = window.location.pathname;
const previous = eventsRef.current[pathname];
eventsRef.current[pathname] = {
pageContext: previous?.pageContext ?? ctx,
url: previous?.url ?? window.location.href,
events: [
...(previous?.events ?? []),
{
...event,
timestamp: new Date().toISOString(),
},
],
context,
};
if (eventsRef.current[pathname].pageContext !== undefined) {
// If the pageId is set, we know that the page_view event has been tracked
// and we can flush the events
if (options?.immediate && visitorIdRef.current) {
flushBatchedEvents.cancel();
flushEventsSync();
} else {
flushBatchedEvents();
}
}
},
);
// When the page is unloaded, flush all events
React.useEffect(() => {
window.addEventListener('beforeunload', flushEventsSync);
return () => {
window.removeEventListener('beforeunload', flushEventsSync);
};
}, [flushEventsSync]);
return (
<InsightsContext.Provider value={trackEvent}>
<OpenAPIOperationContextProvider
onOpenClient={(operation) => {
trackEvent({ type: 'api_client_open', operation });
}}
>
{props.children}
</OpenAPIOperationContextProvider>
</InsightsContext.Provider>
);
}
/**
* Get a callback to track an event.
*/
export function useTrackEvent(): TrackEventCallback {
const trackEvent = React.useContext(InsightsContext);
if (!trackEvent) {
throw new Error('useTrackEvent must be used within an InsightsProvider');
}
return trackEvent;
}
/**
* Post the events to the server.
*/
function sendEvents(args: {
apiHost: string;
organizationId: string;
siteId: string;
events: api.SiteInsightsEvent[];
}) {
const { apiHost, organizationId, siteId, events } = args;
const url = new URL(apiHost);
url.pathname = `/v1/orgs/${organizationId}/sites/${siteId}/insights/events`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
keepalive: true,
body: JSON.stringify({
events,
}),
});
}
/**
* Transform the events to the format expected by the API.
*/
function transformEvents(input: {
url: string;
events: TrackEventInput<SiteEventName>[];
context: InsightsEventContext;
pageContext: InsightsEventPageContext;
visitorId: string;
sessionId: string;
}): api.SiteInsightsEvent[] {
const session: api.SiteInsightsEventSession = {
sessionId: input.sessionId,
visitorId: input.visitorId,
userAgent: window.navigator.userAgent,
language: window.navigator.language,
cookies: cookies.get(),
referrer: document.referrer || null,
};
const location: api.SiteInsightsEventLocation = {
url: input.url,
siteSection: input.context.siteSectionId ?? null,
siteSpace: input.context.siteSpaceId ?? null,
space: input.context.spaceId,
siteShareKey: input.context.siteShareKey ?? null,
page: input.pageContext.pageId,
revision: input.pageContext.revisionId,
};
return input.events.map((partialEvent) => {
// @ts-expect-error: Partial event
const event: api.SiteInsightsEvent = {
...partialEvent,
session,
location,
};
return event;
});
}
@@ -0,0 +1,27 @@
'use client';
import * as React from 'react';
import { useTrackEvent } from './InsightsProvider';
/**
* Track a page view event.
*/
export function TrackPageViewEvent(props: { pageId: string | null; revisionId: string }) {
const { pageId, revisionId } = props;
//const trackEvent = useTrackEvent();
// React.useEffect(() => {
// trackEvent(
// {
// type: 'page_view',
// },
// {
// pageId,
// revisionId,
// },
// );
// }, [pageId, revisionId, trackEvent]);
return null;
}
@@ -0,0 +1,32 @@
'use client';
import cookies from 'js-cookie';
const GRANTED_COOKIE = '__gitbook_cookie_granted';
/**
* Accept or reject cookies.
*/
export function setCookiesTracking(enabled: boolean) {
cookies.set(GRANTED_COOKIE, enabled ? 'yes' : 'no', {
expires: 365,
sameSite: 'none',
secure: true,
});
}
/**
* Return true if cookies are accepted or not.
* Return `undefined` if state is not known.
*/
export function isCookiesTrackingDisabled() {
const state = cookies.get(GRANTED_COOKIE);
if (state === 'yes') {
return false;
} else if (state === 'no') {
return true;
}
return undefined;
}
@@ -0,0 +1,4 @@
export * from './InsightsProvider';
export * from './visitorId';
export * from './cookies';
export * from './TrackPageViewEvent';
@@ -0,0 +1,71 @@
'use client';
import { generateRandomId } from './utils';
const SESSION_TTL = 1000 * 60 * 30; // 30 minutes
interface Session {
id: string;
lastActiveAt: number;
}
let currentSession: Session | null = null;
const SESSION_KEY = '__gitbook_session';
/**
* Get the current session.
*/
export function getSession(): Session {
if (currentSession) {
return currentSession;
}
try {
const rawSession =
typeof localStorage !== 'undefined' ? localStorage.getItem(SESSION_KEY) : null;
if (rawSession) {
const storedSession = JSON.parse(rawSession);
if (
typeof storedSession === 'object' &&
typeof storedSession.lastActiveAt === 'number' &&
typeof storedSession.id === 'string' &&
storedSession.lastActiveAt + SESSION_TTL > Date.now()
) {
currentSession = storedSession as Session;
touchSession();
return currentSession;
}
}
} catch (error) {
console.error('Error parsing session', error);
}
currentSession = {
id: generateRandomId(),
lastActiveAt: Date.now(),
};
saveSession();
return currentSession;
}
/**
* Update the session.
*/
export function touchSession() {
if (currentSession) {
currentSession.lastActiveAt = Date.now();
saveSession();
}
}
/**
* Save the session to the local storage.
*/
export function saveSession() {
if (typeof localStorage !== 'undefined' && currentSession) {
localStorage.setItem(SESSION_KEY, JSON.stringify(currentSession));
}
}
@@ -0,0 +1,11 @@
/**
* Generate a random ID.
*/
export function generateRandomId(): string {
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return `${crypto.randomUUID()}R`;
}
// Fallback for old browsers
return `${Math.random().toString(36).substring(2)}R`;
}
@@ -0,0 +1,68 @@
'use client';
import cookies from 'js-cookie';
import { isCookiesTrackingDisabled } from './cookies';
import { generateRandomId } from './utils';
const VISITORID_COOKIE = '__session';
let visitorId: string | null = null;
let pendingVisitorId: Promise<string> | null = null;
/**
* Return the current visitor identifier.
*/
export async function getVisitorId(): Promise<string> {
if (!visitorId) {
if (!pendingVisitorId) {
pendingVisitorId = fetchVisitorID().finally(() => {
pendingVisitorId = null;
});
}
visitorId = await pendingVisitorId;
}
return visitorId;
}
/**
* Propose a visitor identifier to the GitBook.com server and get the devideId back.
*/
async function fetchVisitorID(): Promise<string> {
const withoutCookies = isCookiesTrackingDisabled();
if (withoutCookies) {
return generateRandomId();
}
const existingTrackingCookie = cookies.get(VISITORID_COOKIE);
if (existingTrackingCookie) {
// If the cookie already exists, we'll just use that. Avoids a server request.
return existingTrackingCookie;
} else {
// No tracking deviceId set, we'll need to consolidate with the server.
const proposed = generateRandomId();
const url = new URL(process.env.NEXT_PUBLIC_GITBOOK_APP_URL ?? `https://app.gitbook.com`);
url.pathname = '/__session';
url.searchParams.set('proposed', proposed);
try {
const resp = await fetch(url, {
method: 'GET', // Use GET to play nicely with SameSite cookies.
credentials: 'include', // Make sure to send/receive cookies.
cache: 'no-cache',
mode: 'cors', // Need to use cors as we are on a different domain.
});
const { deviceId } = (await resp.json()) as { deviceId: string };
return deviceId;
} catch (error) {
console.error('Failed to fetch visitor session ID', error);
return proposed;
}
}
}
@@ -14,15 +14,14 @@ import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
import { AncestorRevisionPage } from '@/lib/pages'; import { AncestorRevisionPage } from '@/lib/pages';
import { ContentRefContext, resolveContentRef } from '@/lib/references'; import { ContentRefContext, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { shouldTrackPageViews } from '@/lib/tracking';
import { PageBodyBlankslate } from './PageBodyBlankslate'; import { PageBodyBlankslate } from './PageBodyBlankslate';
import { PageCover } from './PageCover'; import { PageCover } from './PageCover';
import { PageFooterNavigation } from './PageFooterNavigation'; import { PageFooterNavigation } from './PageFooterNavigation';
import { PageHeader } from './PageHeader'; import { PageHeader } from './PageHeader';
import { PreservePageLayout } from './PreservePageLayout'; import { PreservePageLayout } from './PreservePageLayout';
import { TrackPageView } from './TrackPageView';
import { DocumentView, DocumentViewSkeleton } from '../DocumentView'; import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { TrackPageViewEvent } from '../Insights';
import { PageFeedbackForm } from '../PageFeedback'; import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative } from '../primitives'; import { DateRelative } from '../primitives';
@@ -39,7 +38,6 @@ export function PageBody(props: {
}) { }) {
const { const {
space, space,
pointer,
contentTarget, contentTarget,
customization, customization,
context, context,
@@ -146,14 +144,8 @@ export function PageBody(props: {
) : null} ) : null}
</div> </div>
</main> </main>
{shouldTrackPageViews() ? (
<TrackPageView <TrackPageViewEvent pageId={page.id} revisionId={space.revision} />
sitePointer={pointer}
spaceId={space.id}
pageId={page.id}
apiHost={api().client.endpoint}
/>
) : null}
</> </>
); );
} }
@@ -61,6 +61,10 @@ export async function PageBodyBlankslate(props: {
leadingIcon={icon} leadingIcon={icon}
title={child.title} title={child.title}
href={resolved.href} href={resolved.href}
insights={{
target: child.target,
position: 'content',
}}
/> />
); );
} else { } else {
@@ -13,7 +13,7 @@ import { pageHref } from '@/lib/links';
import { resolvePrevNextPages } from '@/lib/pages'; import { resolvePrevNextPages } from '@/lib/pages';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { Link } from '../primitives'; import { Link, LinkInsightsProps } from '../primitives';
/** /**
* Show cards to go to previous/next pages at the bottom. * Show cards to go to previous/next pages at the bottom.
@@ -47,6 +47,13 @@ export function PageFooterNavigation(props: {
label={t(language, 'previous_page')} label={t(language, 'previous_page')}
title={previous.title} title={previous.title}
href={pageHref(pages, previous)} href={pageHref(pages, previous)}
insights={{
target: {
kind: 'page',
page: previous.id,
},
position: 'content',
}}
reversed reversed
/> />
) : null} ) : null}
@@ -56,24 +63,34 @@ export function PageFooterNavigation(props: {
label={t(language, 'next_page')} label={t(language, 'next_page')}
title={next.title} title={next.title}
href={pageHref(pages, next)} href={pageHref(pages, next)}
insights={{
target: {
kind: 'page',
page: next.id,
},
position: 'content',
}}
/> />
) : null} ) : null}
</div> </div>
); );
} }
function NavigationCard(props: { function NavigationCard(
icon: IconName; props: {
label: React.ReactNode; icon: IconName;
title: string; label: React.ReactNode;
href: string; title: string;
reversed?: boolean; href: string;
}) { reversed?: boolean;
const { icon, label, title, href, reversed } = props; } & LinkInsightsProps,
) {
const { icon, label, title, href, reversed, insights } = props;
return ( return (
<Link <Link
href={href} href={href}
insights={insights}
className={tcls( className={tcls(
'group', 'group',
'text-sm', 'text-sm',
@@ -1,112 +0,0 @@
'use client';
import type { RequestSiteTrackPageView, RequestSpaceTrackPageView } from '@gitbook/api';
import cookies from 'js-cookie';
import * as React from 'react';
import { getVisitorId } from '@/lib/analytics';
import { SiteContentPointer } from '@/lib/api';
/**
* Track the page view for the current page to integrations.
*/
export function TrackPageView(props: {
apiHost: string;
sitePointer: SiteContentPointer;
spaceId: string;
pageId: string | undefined;
}) {
const { apiHost, sitePointer, spaceId, pageId } = props;
React.useEffect(() => {
trackPageView({ apiHost, sitePointer, spaceId, pageId });
}, [apiHost, spaceId, pageId, sitePointer]);
return null;
}
async function sendSpaceTrackPageViewRequest(args: {
apiHost: string;
spaceId: string;
body: RequestSpaceTrackPageView;
}) {
const { apiHost, spaceId, body } = args;
const url = new URL(apiHost);
url.pathname = `/v1/spaces/${spaceId}/insights/track_view`;
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
async function sendSiteTrackPageViewRequest(args: {
apiHost: string;
sitePointer: SiteContentPointer;
body: RequestSiteTrackPageView;
}) {
const { apiHost, sitePointer, body } = args;
const url = new URL(apiHost);
url.pathname = `/v1/orgs/${sitePointer.organizationId}/sites/${sitePointer.siteId}/insights/track_view`;
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
let latestPageId: string | undefined | null = null;
/**
* Track the page view for the current page to GitBook.
* We don't use the API client to avoid shipping 80kb of JS to the client.
* And instead use a simple fetch.
*/
async function trackPageView(args: {
apiHost: string;
sitePointer: SiteContentPointer;
spaceId: string;
pageId: string | undefined;
}) {
const { apiHost, sitePointer, pageId, spaceId } = args;
if (pageId === latestPageId) {
// The hook can be called multiple times, we only want to track once.
return;
}
latestPageId = pageId;
const visitorId = await getVisitorId();
const sharedTrackedProps = {
url: window.location.href,
pageId,
visitor: {
anonymousId: visitorId,
userAgent: window.navigator.userAgent,
language: window.navigator.language,
cookies: cookies.get(),
},
referrer: document.referrer,
};
try {
sitePointer
? await sendSiteTrackPageViewRequest({
apiHost,
sitePointer,
body: {
...sharedTrackedProps,
spaceId,
},
})
: await sendSpaceTrackPageViewRequest({ apiHost, spaceId, body: sharedTrackedProps });
} catch (error) {
console.error('Failed to track page view', error);
}
}
@@ -5,9 +5,9 @@ import React from 'react';
import { useLanguage } from '@/intl/client'; import { useLanguage } from '@/intl/client';
import { t, tString } from '@/intl/translate'; import { t, tString } from '@/intl/translate';
import { getVisitorId } from '@/lib/analytics';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { getVisitorId, useTrackEvent } from '../Insights';
import { postPageFeedback } from './server-actions'; import { postPageFeedback } from './server-actions';
/** /**
@@ -20,12 +20,20 @@ export function PageFeedbackForm(props: {
}) { }) {
const { orientation = 'vertical', pageId, className } = props; const { orientation = 'vertical', pageId, className } = props;
const languages = useLanguage(); const languages = useLanguage();
// const trackEvent = useTrackEvent();
const [submitted, setSubmitted] = React.useState(false); const [submitted, setSubmitted] = React.useState(false);
const onSubmit = async (rating: PageFeedbackRating) => { const onSubmit = async (rating: PageFeedbackRating) => {
setSubmitted(true); setSubmitted(true);
const visitorId = await getVisitorId(); const visitorId = await getVisitorId();
await postPageFeedback({ pageId, visitorId, rating }); await postPageFeedback({ pageId, visitorId, rating });
// trackEvent({
// type: 'page_post_feedback',
// feedback: {
// rating,
// },
// });
}; };
return ( return (
@@ -11,13 +11,12 @@ import assertNever from 'assert-never';
import colorContrast from 'postcss-color-contrast/js'; import colorContrast from 'postcss-color-contrast/js';
import colors from 'tailwindcss/colors'; import colors from 'tailwindcss/colors';
import { fonts, ibmPlexMono } from '@/fonts'; import { fontNotoColorEmoji, fonts, ibmPlexMono } from '@/fonts';
import { getSpaceLanguage } from '@/intl/server'; import { getSpaceLanguage } from '@/intl/server';
import { getStaticFileURL } from '@/lib/assets'; import { getStaticFileURL } from '@/lib/assets';
import { hexToRgb, shadesOfColor } from '@/lib/colors'; import { hexToRgb, shadesOfColor } from '@/lib/colors';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { emojiFontClassName } from '../primitives';
import { ClientContexts } from './ClientContexts'; import { ClientContexts } from './ClientContexts';
import '@gitbook/icons/style.css'; import '@gitbook/icons/style.css';
@@ -154,7 +153,7 @@ export async function CustomizationRootLayout(props: {
</head> </head>
<body <body
className={tcls( className={tcls(
emojiFontClassName, fontNotoColorEmoji.className,
`${fonts[customization.styling.font].className}`, `${fonts[customization.styling.font].className}`,
`${ibmPlexMono.variable}`, `${ibmPlexMono.variable}`,
'bg-light', 'bg-light',
@@ -4,6 +4,8 @@
@layer base { @layer base {
:root { :root {
/* See packages/gitbook/src/fonts/index.ts */
--font-emoji: 'Apple Color Emoji', var(--font-noto-color-emoji);
--scrollbar-width: calc(100vw - 100%); --scrollbar-width: calc(100vw - 100%);
--dark-base: 20 20 20; --dark-base: 20 20 20;
@@ -196,26 +198,5 @@ html.dark {
/* Emojis */ /* Emojis */
[class*='emoji'] { [class*='emoji'] {
font-family: var(--font-emojis-sbix); font-family: var(--font-emoji);
}
/* 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);
}
} }
@@ -14,6 +14,7 @@ import { tcls } from '@/lib/tailwind';
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions'; import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
import { useSearch, useSearchLink } from './useSearch'; import { useSearch, useSearchLink } from './useSearch';
import { useTrackEvent } from '../Insights';
import { Link } from '../primitives'; import { Link } from '../primitives';
type SearchState = type SearchState =
@@ -44,6 +45,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
const { pointer, query } = props; const { pointer, query } = props;
const language = useLanguage(); const language = useLanguage();
// const trackEvent = useTrackEvent();
const [, setSearchState] = useSearch(); const [, setSearchState] = useSearch();
const [state, setState] = useRecoilState(searchAskState); const [state, setState] = useRecoilState(searchAskState);
const { organizationId, siteId, siteSpaceId } = pointer; const { organizationId, siteId, siteSpaceId } = pointer;
@@ -51,42 +53,34 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
React.useEffect(() => { React.useEffect(() => {
let cancelled = false; let cancelled = false;
setState({ setState({ type: 'loading' });
type: 'loading',
});
(async () => { (async () => {
const stream = iterateStreamResponse( // trackEvent({
streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query), // type: 'ask_question',
); // query,
// });
setSearchState((prev) => const response = streamAskQuestion(organizationId, siteId, siteSpaceId ?? null, query);
prev const stream = iterateStreamResponse(response);
? {
...prev, // When we pass in "ask" mode, the query could still be updated by the client
ask: true, // we ensure that the query is up-to-date before starting the stream.
query, setSearchState((prev) => (prev ? { ...prev, query, ask: true } : null));
}
: null,
);
for await (const chunk of stream) { for await (const chunk of stream) {
if (cancelled) { if (cancelled) {
return; return;
} }
setState({
type: 'answer', setState({ type: 'answer', answer: chunk });
answer: chunk,
});
} }
})().catch((error) => { })().catch(() => {
if (cancelled) { if (cancelled) {
return; return;
} }
setState({ setState({ type: 'error' });
type: 'error',
});
}); });
return () => { return () => {
@@ -96,7 +90,7 @@ export function SearchAskAnswer(props: { pointer: SiteContentPointer; query: str
cancelled = true; cancelled = true;
} }
}; };
}, [organizationId, siteId, siteSpaceId, query]); }, [organizationId, siteId, siteSpaceId, query, setState, setSearchState]);
React.useEffect(() => { React.useEffect(() => {
return () => { return () => {
@@ -8,6 +8,7 @@ import { useLanguage, tString } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
import { useSearch } from './useSearch'; import { useSearch } from './useSearch';
import { useTrackEvent } from '../Insights';
/** /**
* Button to open the search modal. * Button to open the search modal.
@@ -17,6 +18,7 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
const language = useLanguage(); const language = useLanguage();
const [, setSearchState] = useSearch(); const [, setSearchState] = useSearch();
// const trackEvent = useTrackEvent();
const onClick = () => { const onClick = () => {
setSearchState({ setSearchState({
@@ -24,6 +26,10 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
global: false, global: false,
query: '', query: '',
}); });
// trackEvent({
// type: 'search_open',
// });
}; };
return ( return (
@@ -52,8 +58,8 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
'shadow-dark/4', 'shadow-dark/4',
'dark:shadow-none', 'dark:shadow-none',
'text-dark/6', 'text-dark/7',
'dark:text-light/6', 'dark:text-light-4/7',
'rounded-lg', 'rounded-lg',
'straight-corners:rounded-sm', 'straight-corners:rounded-sm',
@@ -128,11 +134,11 @@ const Shortcut = () => {
'md:inline', 'md:inline',
'justify-end', 'justify-end',
'text-xs', 'text-xs',
'text-dark/6', 'text-dark/7',
'contrast-more:text-dark', 'contrast-more:text-dark',
'dark:text-light/6', 'dark:text-light-4/7',
'whitespace-nowrap',
'contrast-more:dark:text-light', 'contrast-more:dark:text-light',
'whitespace-nowrap',
`[font-feature-settings:"calt",_"case"]`, `[font-feature-settings:"calt",_"case"]`,
)} )}
> >
@@ -14,7 +14,7 @@ import { tcls } from '@/lib/tailwind';
import { SearchAskAnswer, searchAskState } from './SearchAskAnswer'; import { SearchAskAnswer, searchAskState } from './SearchAskAnswer';
import { SearchResults, SearchResultsRef } from './SearchResults'; import { SearchResults, SearchResultsRef } from './SearchResults';
import { SearchScopeToggle } from './SearchScopeToggle'; import { SearchScopeToggle } from './SearchScopeToggle';
import { SearchState, useSearch } from './useSearch'; import { SearchState, UpdateSearchState, useSearch } from './useSearch';
import { LoadingPane } from '../primitives/LoadingPane'; import { LoadingPane } from '../primitives/LoadingPane';
interface SearchModalProps { interface SearchModalProps {
@@ -55,10 +55,6 @@ export function SearchModal(props: SearchModalProps) {
}; };
}, [isSearchOpened]); }, [isSearchOpened]);
const onChangeQuery = (newQuery: SearchState) => {
setSearchState(newQuery);
};
const onClose = async (to?: string) => { const onClose = async (to?: string) => {
await setSearchState(null); await setSearchState(null);
if (to) { if (to) {
@@ -129,7 +125,7 @@ export function SearchModal(props: SearchModalProps) {
<SearchModalBody <SearchModalBody
{...props} {...props}
state={state} state={state}
onChangeQuery={onChangeQuery} setSearchState={setSearchState}
onClose={onClose} onClose={onClose}
/> />
</div> </div>
@@ -142,7 +138,7 @@ export function SearchModal(props: SearchModalProps) {
function SearchModalBody( function SearchModalBody(
props: SearchModalProps & { props: SearchModalProps & {
state: SearchState; state: SearchState;
onChangeQuery: (newQuery: SearchState) => void; setSearchState: UpdateSearchState;
onClose: (to?: string) => void; onClose: (to?: string) => void;
}, },
) { ) {
@@ -154,7 +150,7 @@ function SearchModalBody(
withAsk, withAsk,
isMultiVariants, isMultiVariants,
state, state,
onChangeQuery, setSearchState,
onClose, onClose,
} = props; } = props;
@@ -193,13 +189,17 @@ function SearchModalBody(
}; };
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => { const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onChangeQuery({ setSearchState({
ask: false, // When typing, we go back to the default search mode ask: false, // When typing, we go back to the default search mode
query: event.target.value, query: event.target.value,
global: state.global, global: state.global,
}); });
}; };
const onSwitchToAsk = () => {
setSearchState((state) => (state ? { ...state, ask: true } : null));
};
return ( return (
<motion.div <motion.div
transition={{ transition={{
@@ -311,13 +311,7 @@ function SearchModalBody(
global={isMultiVariants && state.global} global={isMultiVariants && state.global}
query={state.query} query={state.query}
withAsk={withAsk} withAsk={withAsk}
onSwitchToAsk={() => { onSwitchToAsk={onSwitchToAsk}
onChangeQuery({
ask: true,
query: state.query,
global: state.global,
});
}}
></SearchResults> ></SearchResults>
) : null} ) : null}
{state.query && state.ask && withAsk ? ( {state.query && state.ask && withAsk ? (
@@ -14,6 +14,7 @@ import {
searchSiteSpaceContent, searchSiteSpaceContent,
searchAllSiteContent, searchAllSiteContent,
} from './server-actions'; } from './server-actions';
import { useTrackEvent } from '../Insights';
import { Loading } from '../primitives'; import { Loading } from '../primitives';
export interface SearchResultsRef { export interface SearchResultsRef {
@@ -49,6 +50,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
const { children, query, pointer, spaceId, revisionId, global, withAsk, onSwitchToAsk } = props; const { children, query, pointer, spaceId, revisionId, global, withAsk, onSwitchToAsk } = props;
const language = useLanguage(); const language = useLanguage();
// const trackEvent = useTrackEvent();
const debounceTimeout = React.useRef<Timer | null>(null); const debounceTimeout = React.useRef<Timer | null>(null);
const [results, setResults] = React.useState<ResultType[] | null>(null); const [results, setResults] = React.useState<ResultType[] | null>(null);
const [cursor, setCursor] = React.useState<number | null>(null); const [cursor, setCursor] = React.useState<number | null>(null);
@@ -96,6 +98,11 @@ export const SearchResults = React.forwardRef(function SearchResults(
: searchSiteSpaceContent(query, pointer, revisionId)); : searchSiteSpaceContent(query, pointer, revisionId));
setResults(withAsk ? withQuestionResult(fetchedResults, query) : fetchedResults); setResults(withAsk ? withQuestionResult(fetchedResults, query) : fetchedResults);
// trackEvent({
// type: 'search_type_query',
// query,
// });
}, 350); }, 350);
return () => { return () => {
@@ -16,18 +16,17 @@ const keyMap = {
global: parseAsBoolean, global: parseAsBoolean,
}; };
const options: UseQueryStatesOptions = { export type UpdateSearchState = (
history: 'replace', update: React.SetStateAction<SearchState | null>,
}; ) => Promise<URLSearchParams>;
/** /**
* Hook to access the current search query and update it. * Hook to access the current search query and update it.
*/ */
export function useSearch(): [ export function useSearch(): [SearchState | null, UpdateSearchState] {
SearchState | null, const [rawState, setRawState] = useQueryStates(keyMap, {
(update: React.SetStateAction<SearchState | null>) => Promise<URLSearchParams>, history: 'replace',
] { });
const [rawState, setRawState] = useQueryStates(keyMap, options);
const state = React.useMemo<SearchState | null>(() => { const state = React.useMemo<SearchState | null>(() => {
if (rawState === null || rawState.q === null) { if (rawState === null || rawState.q === null) {
@@ -1,4 +1,5 @@
import { CustomizationThemedURL } from '@gitbook/api'; import { CustomizationThemedURL } from '@gitbook/api';
import React from 'react';
import { Image } from '@/components/utils'; import { Image } from '@/components/utils';
import { absoluteHref } from '@/lib/links'; import { absoluteHref } from '@/lib/links';
@@ -47,6 +48,7 @@ export function SpaceIcon(
} }
} }
{...imageProps} {...imageProps}
sizes={[]}
/> />
); );
} }
@@ -16,11 +16,13 @@ import { CONTAINER_STYLE } from '@/components/layout';
import { ColorDebugger } from '@/components/primitives/ColorDebugger'; import { ColorDebugger } from '@/components/primitives/ColorDebugger';
import { SearchModal } from '@/components/Search'; import { SearchModal } from '@/components/Search';
import { TableOfContents } from '@/components/TableOfContents'; import { TableOfContents } from '@/components/TableOfContents';
import { ContentTarget, type SectionsList, SiteContentPointer } from '@/lib/api'; import { api, ContentTarget, type SectionsList, SiteContentPointer } from '@/lib/api';
import { ContentRefContext } from '@/lib/references'; import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind'; import { tcls } from '@/lib/tailwind';
import { shouldTrackEvents } from '@/lib/tracking';
import { SpacesDropdown } from '../Header/SpacesDropdown'; import { SpacesDropdown } from '../Header/SpacesDropdown';
import { InsightsProvider } from '../Insights';
/** /**
* Render the entire content of the space (header, table of contents, footer, and page content). * Render the entire content of the space (header, table of contents, footer, and page content).
@@ -64,7 +66,11 @@ export function SpaceLayout(props: {
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader }; const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
return ( return (
<> <InsightsProvider
enabled={shouldTrackEvents()}
apiHost={api().client.endpoint}
{...content}
>
{/* <ColorDebugger /> */} {/* <ColorDebugger /> */}
<Header <Header
withTopHeader={withTopHeader} withTopHeader={withTopHeader}
@@ -137,6 +143,6 @@ export function SpaceLayout(props: {
pointer={content} pointer={content}
/> />
</React.Suspense> </React.Suspense>
</> </InsightsProvider>
); );
} }
@@ -22,6 +22,13 @@ export function PageDocumentItem(props: {
<ToggleableLinkItem <ToggleableLinkItem
href={pageHref(rootPages, page)} href={pageHref(rootPages, page)}
pathname={getPagePath(rootPages, page)} pathname={getPagePath(rootPages, page)}
insights={{
target: {
kind: 'page',
page: page.id,
},
position: 'sidebar',
}}
descendants={ descendants={
page.pages && page.pages.length ? ( page.pages && page.pages.length ? (
<PagesList <PagesList
@@ -35,6 +35,10 @@ export async function PageLinkItem(props: { page: RevisionPageLink; context: Con
'hover:bg-dark/1', 'hover:bg-dark/1',
'dark:hover:bg-light/2', 'dark:hover:bg-light/2',
)} )}
insights={{
target: page.target,
position: 'sidebar',
}}
> >
<TOCPageIcon page={page} /> <TOCPageIcon page={page} />
{page.title} {page.title}
@@ -9,7 +9,7 @@ import { tcls } from '@/lib/tailwind';
import { useScrollToActiveTOCItem } from './TOCScroller'; import { useScrollToActiveTOCItem } from './TOCScroller';
import { useIsMounted } from '../hooks'; import { useIsMounted } from '../hooks';
import { Link } from '../primitives'; import { Link, LinkInsightsProps } from '../primitives';
const show = { const show = {
opacity: 1, opacity: 1,
@@ -30,13 +30,15 @@ const staggerMenuItems = stagger(0.02, { ease: (p) => Math.pow(p, 2) });
/** /**
* Client component for a page document to toggle its children and be marked as active. * Client component for a page document to toggle its children and be marked as active.
*/ */
export function ToggleableLinkItem(props: { export function ToggleableLinkItem(
href: string; props: {
pathname: string; href: string;
children: React.ReactNode; pathname: string;
descendants: React.ReactNode; children: React.ReactNode;
}) { descendants: React.ReactNode;
const { href, children, descendants, pathname } = props; } & LinkInsightsProps,
) {
const { href, children, descendants, pathname, insights } = props;
const rawActiveSegment = useSelectedLayoutSegment() ?? ''; const rawActiveSegment = useSelectedLayoutSegment() ?? '';
const activeSegment = decodeURIComponent(rawActiveSegment); const activeSegment = decodeURIComponent(rawActiveSegment);
@@ -96,6 +98,7 @@ export function ToggleableLinkItem(props: {
<Link <Link
ref={linkRef} ref={linkRef}
href={href} href={href}
insights={insights}
{...(isActive ? { 'aria-current': 'page' } : {})} {...(isActive ? { 'aria-current': 'page' } : {})}
className={tcls( className={tcls(
'group/toclink', 'group/toclink',
@@ -4,14 +4,15 @@ import type { ComponentPropsWithoutRef, HTMLAttributes } from 'react';
import { tcls, ClassValue } from '@/lib/tailwind'; import { tcls, ClassValue } from '@/lib/tailwind';
import { Link } from './Link'; import { Link, LinkInsightsProps } from './Link';
type ButtonProps = { type ButtonProps = {
href?: string; href?: string;
variant?: 'primary' | 'secondary'; variant?: 'primary' | 'secondary';
size?: 'default' | 'medium' | 'small'; size?: 'default' | 'medium' | 'small';
className?: ClassValue; className?: ClassValue;
} & HTMLAttributes<HTMLElement>; } & LinkInsightsProps &
HTMLAttributes<HTMLElement>;
export function Button({ export function Button({
href, href,
@@ -19,6 +20,7 @@ export function Button({
variant = 'primary', variant = 'primary',
size = 'default', size = 'default',
className, className,
insights,
...rest ...rest
}: ButtonProps) { }: ButtonProps) {
const variantClasses = const variantClasses =
@@ -69,7 +71,7 @@ export function Button({
if (href) { if (href) {
return ( return (
<Link href={href} className={domClassName} {...rest}> <Link href={href} className={domClassName} insights={insights} {...rest}>
{children} {children}
</Link> </Link>
); );
@@ -1,18 +1,21 @@
import { Icon } from '@gitbook/icons'; import { Icon } from '@gitbook/icons';
import React from 'react';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
import { Link } from './Link'; import { Link, LinkInsightsProps } from './Link';
export async function Card(props: { export async function Card(
href: string; props: {
leadingIcon?: React.ReactNode; href: string;
preTitle?: string; leadingIcon?: React.ReactNode;
title: string; preTitle?: string;
postTitle?: string; title: string;
style?: ClassValue; postTitle?: string;
}) { style?: ClassValue;
const { title, leadingIcon, href, preTitle, postTitle, style } = props; } & LinkInsightsProps,
) {
const { title, leadingIcon, href, preTitle, postTitle, style, insights } = props;
return ( return (
<Link <Link
@@ -38,6 +41,7 @@ export async function Card(props: {
'dark:hover:ring-primary-300/4', 'dark:hover:ring-primary-300/4',
style, style,
)} )}
insights={insights}
> >
{leadingIcon} {leadingIcon}
<span className={tcls('flex', 'flex-col', 'flex-1')}> <span className={tcls('flex', 'flex-col', 'flex-1')}>
@@ -1,51 +1,6 @@
import localFont from 'next/font/local';
import { getEmojiForCode } from '@/lib/emojis'; import { getEmojiForCode } from '@/lib/emojis';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
/**
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-colrv1',
});
/**
SBIX font.
- narrowly supported
- currently required for Safari (or iOS)
- provide alternative font-family name (see below)
*/
const sbixFont = localFont({
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: './joypixels-cbdt.woff2',
preload: false,
variable: '--font-emojis-cbdt',
});
/**
* Class name to set on the <html> tag to use the emoji font.
*/
export const emojiFontClassName = [colrv1Font.variable, sbixFont.variable, cbdtFont.variable].join(
' ',
);
/** /**
* Render an emoji by its codepoint. * Render an emoji by its codepoint.
* It renders the UTF-8 character and use the emojione font to display it (fallbacking to default browser font). * It renders the UTF-8 character and use the emojione font to display it (fallbacking to default browser font).
@@ -1,16 +1,27 @@
'use client'; 'use client';
import * as api from '@gitbook/api';
import NextLink, { LinkProps as NextLinkProps } from 'next/link'; import NextLink, { LinkProps as NextLinkProps } from 'next/link';
import React from 'react'; import React from 'react';
import { useTrackEvent } from '../Insights';
// Props from Next, which includes NextLinkProps and all the things anchor elements support. // Props from Next, which includes NextLinkProps and all the things anchor elements support.
type BaseLinkProps = Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof NextLinkProps> & type BaseLinkProps = Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof NextLinkProps> &
NextLinkProps & { NextLinkProps & {
children?: React.ReactNode; children?: React.ReactNode;
} & React.RefAttributes<HTMLAnchorElement>; } & React.RefAttributes<HTMLAnchorElement>;
// Enforce href is passed as a string (not a URL). export type LinkInsightsProps = {
export type LinkProps = Omit<BaseLinkProps, 'href'> & { href: string }; /** Target of the link, for insights. */
insights?: api.SiteInsightsEventLinkClick['link'];
};
export type LinkProps = Omit<BaseLinkProps, 'href'> &
LinkInsightsProps & {
/** Enforce href is passed as a string (not a URL). */
href: string;
};
/** /**
* Low-level Link component that handles navigation to external urls. * Low-level Link component that handles navigation to external urls.
@@ -20,21 +31,33 @@ export const Link = React.forwardRef(function Link(
props: LinkProps, props: LinkProps,
ref: React.Ref<HTMLAnchorElement>, ref: React.Ref<HTMLAnchorElement>,
) { ) {
const { href, prefetch, children, ...domProps } = props; const { href, prefetch, children, insights, ...domProps } = props;
// const trackEvent = useTrackEvent();
// Use a real anchor tag for external links,s and a Next.js Link for internal links. // Use a real anchor tag for external links,s and a Next.js Link for internal links.
// If we use a NextLink for external links, Nextjs won't rerender the top-level layouts. // If we use a NextLink for external links, Nextjs won't rerender the top-level layouts.
const isExternal = URL.canParse ? URL.canParse(props.href) : props.href.startsWith('http'); const isExternal = URL.canParse ? URL.canParse(props.href) : props.href.startsWith('http');
const onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
if (insights) {
// trackEvent({ type: 'link_click', link: insights }, undefined, {
// immediate: isExternal,
// });
}
domProps.onClick?.(event);
};
if (isExternal) { if (isExternal) {
return ( return (
<a ref={ref} {...domProps} href={href}> <a ref={ref} {...domProps} href={href} onClick={onClick}>
{children} {children}
</a> </a>
); );
} }
return ( return (
<NextLink ref={ref} {...props}> <NextLink ref={ref} {...props} onClick={onClick}>
{children} {children}
</NextLink> </NextLink>
); );
@@ -1,5 +1,6 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import React from 'react';
import { checkIsHttpURL, getImageSize, getResizedImageURLFactory } from '@/lib/images'; import { checkIsHttpURL, getImageSize, getResizedImageURLFactory } from '@/lib/images';
import { ClassValue, tcls } from '@/lib/tailwind'; import { ClassValue, tcls } from '@/lib/tailwind';
@@ -228,7 +229,6 @@ function ImagePictureSized(
} }
const imgProps: ImgDOMPropsWithSrc = { const imgProps: ImgDOMPropsWithSrc = {
alt,
style, style,
loading, loading,
fetchPriority, fetchPriority,
@@ -236,7 +236,7 @@ function ImagePictureSized(
...attrs, ...attrs,
}; };
return zoom ? <ZoomImage {...imgProps} /> : <img {...imgProps} alt={imgProps.alt ?? ''} />; return zoom ? <ZoomImage {...imgProps} /> : <img {...imgProps} />;
} }
/** /**
@@ -1,19 +1 @@
html:has(.zoomModal) {
overflow: hidden;
}
.zoomImg {
cursor: zoom-in;
}
.zoomImageActive {
view-transition-name: zoom-image;
}
.zoomModal {
}
.zoomModal img {
view-transition-name: zoom-image;
cursor: zoom-out;
}
+8
View File
@@ -15,9 +15,17 @@ import {
Roboto_Slab, Roboto_Slab,
Source_Sans_3, Source_Sans_3,
Ubuntu, Ubuntu,
Noto_Color_Emoji,
} from 'next/font/google'; } from 'next/font/google';
import localFont from 'next/font/local'; import localFont from 'next/font/local';
export const fontNotoColorEmoji = Noto_Color_Emoji({
variable: '--font-noto-color-emoji',
weight: ['400'],
preload: false,
display: 'swap',
});
/* /*
Fonts are downloaded and loaded by next/font. Fonts are downloaded and loaded by next/font.
+4 -1
View File
@@ -1,4 +1,4 @@
import 'server-only'; // import 'server-only';
import { AsyncLocalStorage } from 'node:async_hooks'; import { AsyncLocalStorage } from 'node:async_hooks';
import { import {
@@ -214,6 +214,8 @@ export const getPublishedContentByUrl = cache({
get: async ( get: async (
url: string, url: string,
visitorAuthToken: string | undefined, visitorAuthToken: string | undefined,
// Prefer undefined for a better cache key.
redirectOnError: true | undefined,
options: CacheFunctionOptions, options: CacheFunctionOptions,
) => { ) => {
try { try {
@@ -221,6 +223,7 @@ export const getPublishedContentByUrl = cache({
{ {
url, url,
visitorAuthToken, visitorAuthToken,
redirectOnError,
}, },
{ {
signal: options.signal, signal: options.signal,
+1 -1
View File
@@ -76,7 +76,7 @@ export function cache<Args extends any[], Result>(
cacheDef: CacheDefinition<Args, Result>, cacheDef: CacheDefinition<Args, Result>,
): CacheFunction<Args, Result> { ): CacheFunction<Args, Result> {
// We stop everything after 10s to avoid pending requests // We stop everything after 10s to avoid pending requests
const timeout = cacheDef.timeout ?? 1000 * 10; const timeout = 1000 * 1000000;
const defaultTtl = cacheDef.defaultTtl ?? 60 * 60 * 24; const defaultTtl = cacheDef.defaultTtl ?? 60 * 60 * 24;
const revalidate = singletonMap( const revalidate = singletonMap(
+17 -16
View File
@@ -78,24 +78,25 @@ export const cloudflareDOCache: CacheBackend = {
const globalStubs = new WeakMap<object, Map<string, CacheObjectStub>>(); const globalStubs = new WeakMap<object, Map<string, CacheObjectStub>>();
async function getStub(tag: string): Promise<CacheObjectStub | null> { async function getStub(tag: string): Promise<CacheObjectStub | null> {
if (process.env.NODE_ENV === 'test') { return null;
return null; // if (process.env.NODE_ENV === 'test') {
} // return null;
// }
// We lazy-load the next-on-pages package to avoid errors when running tests because of 'server-only'. // // We lazy-load the next-on-pages package to avoid errors when running tests because of 'server-only'.
const { getOptionalRequestContext } = await import('@cloudflare/next-on-pages'); // const { getOptionalRequestContext } = await import('@cloudflare/next-on-pages');
const cloudflare = getOptionalRequestContext(); // const cloudflare = getOptionalRequestContext();
if (!cloudflare || !cloudflare.env.CACHE) { // if (!cloudflare || !cloudflare.env.CACHE) {
return null; // return null;
} // }
const requestStubs = globalStubs.get(cloudflare.cf) ?? new Map(); // const requestStubs = globalStubs.get(cloudflare.cf) ?? new Map();
globalStubs.set(cloudflare.cf, requestStubs); // globalStubs.set(cloudflare.cf, requestStubs);
const locationId: CacheLocationId = cloudflare.cf.continent ?? 'NA'; // const locationId: CacheLocationId = cloudflare.cf.continent ?? 'NA';
const stub = // const stub =
requestStubs.get(tag) ?? new CacheObjectStub(cloudflare.env.CACHE, locationId, tag); // requestStubs.get(tag) ?? new CacheObjectStub(cloudflare.env.CACHE, locationId, tag);
requestStubs.set(tag, stub); // requestStubs.set(tag, stub);
return stub; // return stub;
} }
+4 -3
View File
@@ -1,6 +1,6 @@
import 'server-only'; //import 'server-only';
import fnv1a from '@sindresorhus/fnv1a'; // import fnv1a from '@sindresorhus/fnv1a';
import { noCacheFetchOptions } from '@/lib/cache/http'; import { noCacheFetchOptions } from '@/lib/cache/http';
@@ -250,5 +250,6 @@ function generateSignature(input: string) {
] ]
.filter(Boolean) .filter(Boolean)
.join(':'); .join(':');
return fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16); return 'aaaa';
//return fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16);
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import 'server-only'; // import 'server-only';
import { import {
RevisionPage, RevisionPage,
+2 -2
View File
@@ -1,4 +1,4 @@
import { ContentRef, DocumentBlockSwagger } from '@gitbook/api'; import { ContentRef, DocumentBlockOpenAPI } from '@gitbook/api';
import { import {
OpenAPIOperationData, OpenAPIOperationData,
fetchOpenAPIOperation, fetchOpenAPIOperation,
@@ -16,7 +16,7 @@ import { ResolvedContentRef } from './references';
* Fetch an OpenAPI specification for an operation. * Fetch an OpenAPI specification for an operation.
*/ */
export async function fetchOpenAPIBlock( export async function fetchOpenAPIBlock(
block: DocumentBlockSwagger, block: DocumentBlockOpenAPI,
resolveContentRef: (ref: ContentRef) => Promise<ResolvedContentRef | null>, resolveContentRef: (ref: ContentRef) => Promise<ResolvedContentRef | null>,
): Promise< ): Promise<
| { data: OpenAPIOperationData | null; specUrl: string | null; error?: undefined } | { data: OpenAPIOperationData | null; specUrl: string | null; error?: undefined }
+5 -4
View File
@@ -1,14 +1,15 @@
import { headers } from 'next/headers'; import { headers } from 'next/headers';
/** /**
* Return true if a space track page views. * Return true if events should be tracked on the site.
*/ */
export function shouldTrackPageViews(): boolean { export function shouldTrackEvents(): boolean {
const headerSet = headers(); const headerSet = headers();
if ( if (
process.env.GITBOOK_BLOCK_PAGE_VIEWS_TRACKING && process.env.NODE_ENV === 'development' ||
!headerSet.has('x-gitbook-track-page-views') (process.env.GITBOOK_BLOCK_PAGE_VIEWS_TRACKING &&
!headerSet.has('x-gitbook-track-page-views'))
) { ) {
return false; return false;
} }
@@ -2,23 +2,22 @@ import { it, describe, expect } from 'bun:test';
import { NextRequest } from 'next/server'; import { NextRequest } from 'next/server';
import { import {
VisitorAuthCookieValue,
getVisitorAuthCookieName, getVisitorAuthCookieName,
getVisitorAuthCookieValue, getVisitorAuthCookieValue,
getVisitorAuthToken, getVisitorToken,
} from './visitor-auth'; } from './visitor-token';
describe('getVisitorAuthToken', () => { describe('getVisitorAuthToken', () => {
it('should return the token from the query parameters', () => { it('should return the token from the query parameters', () => {
const request = nextRequest('https://example.com?jwt_token=123'); const request = nextRequest('https://example.com?jwt_token=123');
expect(getVisitorAuthToken(request, request.nextUrl)).toEqual('123'); expect(getVisitorToken(request, request.nextUrl)).toEqual({ source: 'url', token: '123' });
}); });
it('should return the token from the cookie root basepath', () => { it('should return the token from the cookie root basepath', () => {
const request = nextRequest('https://example.com', { const request = nextRequest('https://example.com', {
[getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') }, [getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') },
}); });
const visitorAuth = getVisitorAuthToken(request, request.nextUrl); const visitorAuth = getVisitorToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth); assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123'); expect(visitorAuth.token).toEqual('123');
}); });
@@ -27,7 +26,7 @@ describe('getVisitorAuthToken', () => {
const request = nextRequest('https://example.com/hello/world', { const request = nextRequest('https://example.com/hello/world', {
[getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') }, [getVisitorAuthCookieName('/')]: { value: getVisitorAuthCookieValue('/', '123') },
}); });
const visitorAuth = getVisitorAuthToken(request, request.nextUrl); const visitorAuth = getVisitorToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth); assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123'); expect(visitorAuth.token).toEqual('123');
}); });
@@ -39,7 +38,7 @@ describe('getVisitorAuthToken', () => {
value: getVisitorAuthCookieValue('/hello/', '123'), value: getVisitorAuthCookieValue('/hello/', '123'),
}, },
}); });
const visitorAuth = getVisitorAuthToken(request, request.nextUrl); const visitorAuth = getVisitorToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth); assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123'); expect(visitorAuth.token).toEqual('123');
}); });
@@ -50,14 +49,14 @@ describe('getVisitorAuthToken', () => {
value: getVisitorAuthCookieValue('/hello/v/space1/', '123'), value: getVisitorAuthCookieValue('/hello/v/space1/', '123'),
}, },
}); });
const visitorAuth = getVisitorAuthToken(request, request.nextUrl); const visitorAuth = getVisitorToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth); assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('123'); expect(visitorAuth.token).toEqual('123');
}); });
it('should return undefined if no cookie and no query param', () => { it('should return undefined if no cookie and no query param', () => {
const request = nextRequest('https://example.com'); const request = nextRequest('https://example.com');
expect(getVisitorAuthToken(request, request.nextUrl)).toBeUndefined(); expect(getVisitorToken(request, request.nextUrl)).toBeUndefined();
}); });
// For backwards compatibility // For backwards compatibility
@@ -69,14 +68,21 @@ describe('getVisitorAuthToken', () => {
}, },
}); });
const visitorAuth = getVisitorAuthToken(request, request.nextUrl); const visitorAuth = getVisitorToken(request, request.nextUrl);
assertVisitorAuthCookieValue(visitorAuth); assertVisitorAuthCookieValue(visitorAuth);
expect(visitorAuth.token).toEqual('gotcha'); expect(visitorAuth.token).toEqual('gotcha');
}); });
}); });
function assertVisitorAuthCookieValue(value: unknown): asserts value is VisitorAuthCookieValue { function assertVisitorAuthCookieValue(
if (value && typeof value === 'object' && 'token' in value) { value: unknown,
): asserts value is { source: 'visitor-auth-cookie'; basePath: string; token: string } {
if (
value &&
typeof value === 'object' &&
'source' in value &&
value.source === 'visitor-auth-cookie'
) {
return; return;
} }
@@ -2,25 +2,64 @@ import type { NextRequest } from 'next/server';
import hash from 'object-hash'; import hash from 'object-hash';
const VISITOR_AUTH_PARAM = 'jwt_token'; const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_AUTH_COOKIE_ROOT = 'gitbook-visitor-token'; const VISITOR_AUTH_COOKIE_ROOT = 'gitbook-visitor-token~';
export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token';
/** /**
* The contents of the visitor authentication cookie. * The contents of the visitor authentication cookie.
*/ */
export type VisitorAuthCookieValue = { type VisitorAuthCookieValue = {
basePath: string; basePath: string;
token: string; token: string;
}; };
/** /**
* Get the visitor authentication token for the request. This token can either be in the * The result of a visitor token lookup.
*/
export type VisitorTokenLookup =
| {
/** A visitor token was found in the URL. */
source: 'url';
token: string;
}
| {
/** A visitor auth token was found in a VA cookie */
source: 'visitor-auth-cookie';
basePath: string;
token: string;
}
| {
/** A visitor token (not auth) was found in a cookie. */
source: 'gitbook-visitor-cookie';
token: string;
}
/** Not visitor token was found */
| undefined;
/**
* Get the visitor token for the request. This token can either be in the
* query parameters or stored as a cookie. * query parameters or stored as a cookie.
*/ */
export function getVisitorAuthToken( export function getVisitorToken(
request: NextRequest, request: NextRequest,
url: URL | NextRequest['nextUrl'], url: URL | NextRequest['nextUrl'],
): string | VisitorAuthCookieValue | undefined { ): VisitorTokenLookup {
return url.searchParams.get(VISITOR_AUTH_PARAM) ?? getVisitorAuthTokenFromCookies(request, url); const fromUrl = url.searchParams.get(VISITOR_AUTH_PARAM);
// Allow the empty string to come through
if (fromUrl !== null && fromUrl !== undefined) {
return { source: 'url', token: fromUrl };
}
const visitorAuthToken = getVisitorAuthTokenFromCookies(request, url);
if (visitorAuthToken) {
return { source: 'visitor-auth-cookie', ...visitorAuthToken };
}
const visitorCustomToken = getVisitorCustomTokenFromCookies(request);
if (visitorCustomToken) {
return { source: 'gitbook-visitor-cookie', token: visitorCustomToken };
}
} }
/** /**
@@ -30,7 +69,7 @@ export function getVisitorAuthToken(
* different content hosted on the same subdomain. * different content hosted on the same subdomain.
*/ */
export function getVisitorAuthCookieName(basePath: string): string { export function getVisitorAuthCookieName(basePath: string): string {
return `${VISITOR_AUTH_COOKIE_ROOT}~${hash(basePath)}`; return `${VISITOR_AUTH_COOKIE_ROOT}${hash(basePath)}`;
} }
/** /**
@@ -96,6 +135,20 @@ function getVisitorAuthTokenFromCookies(
return undefined; return undefined;
} }
/**
* Return the value of a custom visitor cookie that can be set by third party backends
* when they authenticate their users off flow to relay information in the form of claims
* about the visitor.
*
* The cookie should contain as value a JWT encoded token that contains the claims of the visitor.
*/
function getVisitorCustomTokenFromCookies(request: NextRequest): string | undefined {
const visitorCustomCookie = Array.from(request.cookies).find(
([, cookie]) => cookie.name === VISITOR_TOKEN_COOKIE,
);
return visitorCustomCookie ? visitorCustomCookie[1].value : undefined;
}
/** /**
* Loop through all cookies and find the visitor authentication token for a given base path. * Loop through all cookies and find the visitor authentication token for a given base path.
*/ */
+22 -22
View File
@@ -23,12 +23,12 @@ import { buildVersion } from '@/lib/build';
import { createContentSecurityPolicyNonce, getContentSecurityPolicy } from '@/lib/csp'; import { createContentSecurityPolicyNonce, getContentSecurityPolicy } from '@/lib/csp';
import { getURLLookupAlternatives, normalizeURL, setMiddlewareHeader } from '@/lib/middleware'; import { getURLLookupAlternatives, normalizeURL, setMiddlewareHeader } from '@/lib/middleware';
import { import {
VisitorAuthCookieValue, VisitorTokenLookup,
getVisitorAuthCookieName, getVisitorAuthCookieName,
getVisitorAuthCookieValue, getVisitorAuthCookieValue,
getVisitorAuthToken, getVisitorToken,
normalizeVisitorAuthURL, normalizeVisitorAuthURL,
} from '@/lib/visitor-auth'; } from '@/lib/visitor-token';
import { waitUntil } from './lib/waitUntil'; import { waitUntil } from './lib/waitUntil';
@@ -433,7 +433,7 @@ async function lookupSiteInProxy(request: NextRequest, url: URL): Promise<Lookup
* When serving multi spaces based on the current URL. * When serving multi spaces based on the current URL.
*/ */
async function lookupSiteInMultiMode(request: NextRequest, url: URL): Promise<LookupResult> { async function lookupSiteInMultiMode(request: NextRequest, url: URL): Promise<LookupResult> {
const visitorAuthToken = getVisitorAuthToken(request, url); const visitorAuthToken = getVisitorToken(request, url);
const lookup = await lookupSiteByAPI(url, visitorAuthToken); const lookup = await lookupSiteByAPI(url, visitorAuthToken);
return { return {
...lookup, ...lookup,
@@ -636,7 +636,7 @@ async function lookupSiteInMultiPathMode(request: NextRequest, url: URL): Promis
const target = new URL(targetStr); const target = new URL(targetStr);
target.search = url.search; target.search = url.search;
const visitorAuthToken = getVisitorAuthToken(request, target); const visitorAuthToken = getVisitorToken(request, target);
const lookup = await lookupSiteByAPI(target, visitorAuthToken); const lookup = await lookupSiteByAPI(target, visitorAuthToken);
if ('error' in lookup) { if ('error' in lookup) {
@@ -676,7 +676,7 @@ async function lookupSiteInMultiPathMode(request: NextRequest, url: URL): Promis
*/ */
async function lookupSiteByAPI( async function lookupSiteByAPI(
lookupURL: URL, lookupURL: URL,
visitorAuthToken: ReturnType<typeof getVisitorAuthToken>, visitorTokenLookup: VisitorTokenLookup,
): Promise<LookupResult> { ): Promise<LookupResult> {
const url = stripURLSearch(lookupURL); const url = stripURLSearch(lookupURL);
const lookup = getURLLookupAlternatives(url); const lookup = getURLLookupAlternatives(url);
@@ -685,14 +685,16 @@ async function lookupSiteByAPI(
`lookup content for url "${url.toString()}", with ${lookup.urls.length} alternatives`, `lookup content for url "${url.toString()}", with ${lookup.urls.length} alternatives`,
); );
// When the visitor auth token is pulled from the cookie, set redirectOnError when calling getPublishedContentByUrl to allow
// redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
// For example when the VA backend signature has changed but the token stored in the cookie is not yet expired.
const redirectOnError = visitorTokenLookup?.source === 'visitor-auth-cookie';
const result = await race(lookup.urls, async (alternative, { signal }) => { const result = await race(lookup.urls, async (alternative, { signal }) => {
const data = await getPublishedContentByUrl( const data = await getPublishedContentByUrl(
alternative.url, alternative.url,
typeof visitorAuthToken === 'undefined' visitorTokenLookup?.token,
? undefined redirectOnError || undefined,
: typeof visitorAuthToken === 'string'
? visitorAuthToken
: visitorAuthToken.token,
{ {
signal, signal,
}, },
@@ -789,7 +791,7 @@ async function lookupSiteByAPI(
*/ */
function getLookupResultForVisitorAuth( function getLookupResultForVisitorAuth(
basePath: string, basePath: string,
visitorAuthToken: string | VisitorAuthCookieValue, visitorTokenLookup: VisitorTokenLookup,
): Partial<LookupResult> { ): Partial<LookupResult> {
return { return {
// No caching for content served with visitor auth // No caching for content served with visitor auth
@@ -797,19 +799,17 @@ function getLookupResultForVisitorAuth(
cacheTags: [], cacheTags: [],
cookies: { cookies: {
/** /**
* If the visitorAuthToken has been retrieved from a cookie, we set it back only * If the visitor token has been retrieve from the URL, or if its a VA cookie and the basePath is the same, set it
* if the basePath matches the current one. This is to avoid setting cookie for * as a cookie on the response.
* different base paths. *
* Note that we do not re-store the gitbook-visitor-cookie in another cookie, to maintain a single source of truth.
*/ */
...(typeof visitorAuthToken === 'string' || visitorAuthToken.basePath === basePath ...(visitorTokenLookup?.source === 'url' ||
(visitorTokenLookup?.source === 'visitor-auth-cookie' &&
visitorTokenLookup.basePath === basePath)
? { ? {
[getVisitorAuthCookieName(basePath)]: { [getVisitorAuthCookieName(basePath)]: {
value: getVisitorAuthCookieValue( value: getVisitorAuthCookieValue(basePath, visitorTokenLookup.token),
basePath,
typeof visitorAuthToken === 'string'
? visitorAuthToken
: visitorAuthToken.token,
),
options: { options: {
httpOnly: true, httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined, sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
+50 -26
View File
@@ -1,30 +1,54 @@
{ {
"ts-node": {
// these options are overrides used only by ts-node
// same as the --compilerOptions flag and the TS_NODE_COMPILER_OPTIONS environment variable
"compilerOptions": { "compilerOptions": {
"target": "esnext", "module": "commonjs"
"lib": ["dom", "dom.iterable", "esnext"], }
"allowJs": true, },
"skipLibCheck": true, "compilerOptions": {
"strict": true, "target": "esnext",
"noEmit": true, "lib": [
"esModuleInterop": true, "dom",
"module": "esnext", "dom.iterable",
"moduleResolution": "bundler", "esnext"
"resolveJsonModule": true, ],
"isolatedModules": true, "allowJs": true,
"jsx": "preserve", "skipLibCheck": true,
"incremental": true, "strict": true,
"plugins": [ "noEmit": true,
{ "esModuleInterop": true,
"name": "next" "module": "esnext",
} "moduleResolution": "bundler",
], "resolveJsonModule": true,
"paths": { "isolatedModules": true,
"@/*": ["./src/*"] "jsx": "react",
}, "incremental": true,
"types": [ "plugins": [
"bun-types" // add Bun global {
] "name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
}, },
"include": ["next-env.d.ts", "cf-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "types": [
"exclude": ["node_modules", "packages/react-openapi", "packages/react-math"] "bun-types" // add Bun global
]
},
"include": [
"next-env.d.ts",
"cf-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"src/app/(space)/~gitbook/pdf/script.tss"
],
"exclude": [
"node_modules",
"packages/react-openapi",
"packages/react-math"
]
} }
+1 -1
View File
@@ -11,7 +11,7 @@ export function getKitPath() {
try { try {
source = path.resolve( source = path.resolve(
path.dirname( path.dirname(
url.fileURLToPath(import.meta.resolve('@awesome.me/kit-a463935e93/package.json')), url.fileURLToPath(import.meta.resolve('@gitbook/fontawesome-pro/package.json')),
), ),
'icons', 'icons',
); );
+1 -2
View File
@@ -1,6 +1,5 @@
{ {
"name": "@gitbook/icons", "name": "@gitbook/icons",
"type": "module",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
@@ -22,7 +21,7 @@
"@fortawesome/fontawesome-free": "^6.6.0" "@fortawesome/fontawesome-free": "^6.6.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@awesome.me/kit-a463935e93": "1.0.8" "@gitbook/fontawesome-pro": "1.0.8"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5.5.3" "typescript": "^5.5.3"
+1 -1
View File
@@ -10,7 +10,7 @@
}, },
"dependencies": { "dependencies": {
"classnames": "^2.5.1", "classnames": "^2.5.1",
"@gitbook/api": "^0.77.0", "@gitbook/api": "^0.85.0",
"assert-never": "^1.2.1" "assert-never": "^1.2.1"
}, },
"peerDependencies": { "peerDependencies": {
+3 -2
View File
@@ -10,12 +10,13 @@
}, },
"version": "0.7.1", "version": "0.7.1",
"dependencies": { "dependencies": {
"@scalar/api-client-react": "1.0.87", "@scalar/api-client-react": "1.1.2",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"flatted": "^3.2.9", "flatted": "^3.2.9",
"openapi-types": "^12.1.3", "openapi-types": "^12.1.3",
"swagger2openapi": "^7.0.8", "swagger2openapi": "^7.0.8",
"yaml": "1.10.2" "yaml": "1.10.2",
"usehooks-ts": "^3.1.0"
}, },
"devDependencies": { "devDependencies": {
"@types/swagger2openapi": "^7.0.4", "@types/swagger2openapi": "^7.0.4",
@@ -29,7 +29,7 @@ export function OpenAPIOperation(props: {
return ( return (
<ApiClientModalProvider <ApiClientModalProvider
configuration={{ spec: { url: context.specUrl } }} configuration={{ spec: { url: context.specUrl }, showSidebar: false }}
initialRequest={{ path: data.path, method: data.method }} initialRequest={{ path: data.path, method: data.method }}
> >
<div className={classNames('openapi-operation', className)}> <div className={classNames('openapi-operation', className)}>
@@ -0,0 +1,44 @@
'use client';
import * as React from 'react';
import { useEventCallback } from 'usehooks-ts';
interface OpenAPIOperationPointer {
path: string;
method: string;
}
interface OpenAPIOperationContextValue {
onOpenClient: (pointer: OpenAPIOperationPointer) => void;
}
const OpenAPIOperationContext = React.createContext<OpenAPIOperationContextValue>({
onOpenClient: () => {},
});
/**
* Provider for the OpenAPIOperationContext.
*/
export function OpenAPIOperationContextProvider(
props: React.PropsWithChildren<Partial<OpenAPIOperationContextValue>>,
) {
const { children } = props;
const onOpenClient = useEventCallback((pointer: OpenAPIOperationPointer) => {
props.onOpenClient?.(pointer);
});
const value = React.useMemo(() => ({ onOpenClient }), [onOpenClient]);
return (
<OpenAPIOperationContext.Provider value={value}>
{children}
</OpenAPIOperationContext.Provider>
);
}
/**
* Hook to access the OpenAPIOperationContext.
*/
export function useOpenAPIOperationContext() {
return React.useContext(OpenAPIOperationContext);
}
@@ -3,17 +3,22 @@
import { useApiClientModal } from '@scalar/api-client-react'; import { useApiClientModal } from '@scalar/api-client-react';
import React from 'react'; import React from 'react';
import { useOpenAPIOperationContext } from './OpenAPIOperationContext';
/** /**
* Button which launches the Scalar API Client * Button which launches the Scalar API Client
*/ */
export function ScalarApiButton({ method, path }: { method: string; path: string }) { export function ScalarApiButton({ method, path }: { method: string; path: string }) {
const client = useApiClientModal(); const client = useApiClientModal();
const { onOpenClient } = useOpenAPIOperationContext();
return ( return (
<div className="scalar scalar-activate"> <div className="scalar scalar-activate">
<button <button
className="scalar-activate-button" className="scalar-activate-button"
onClick={() => client?.open({ method, path })} onClick={() => {
client?.open({ method, path, _source: 'gitbook' });
onOpenClient({ method, path });
}}
> >
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" fill="none"> <svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" fill="none">
<path <path
+1
View File
@@ -1,3 +1,4 @@
export * from './fetchOpenAPIOperation'; export * from './fetchOpenAPIOperation';
export * from './OpenAPIOperation'; export * from './OpenAPIOperation';
export type { OpenAPIFetcher } from './types'; export type { OpenAPIFetcher } from './types';
export * from './OpenAPIOperationContext';
File diff suppressed because one or more lines are too long