mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-12 14:00:28 +00:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ba2a523722 | |||
| 57adb3e54a | |||
| 7377928c8a | |||
| 5f8a8fe9b1 | |||
| 29a0bf25c4 | |||
| 92bb016576 | |||
| c8810ea002 | |||
| aa8bbaddc4 | |||
| b8c136e9c0 | |||
| 46d54172b0 | |||
| 68dc2de190 | |||
| 81b372f372 | |||
| 966e520640 | |||
| 12702930ec | |||
| 6ce57bcda1 | |||
| d99b453bc4 | |||
| aaf5793cb7 | |||
| 9b1762d2ab | |||
| 8d38d000fd | |||
| 4cf9cdd56d | |||
| 39406bbf54 | |||
| 9c5c1e5b68 | |||
| 6929b0b98b | |||
| 7c26d491b1 | |||
| 97035a054a | |||
| db45c6d773 | |||
| e3f5f81e62 |
@@ -0,0 +1,8 @@
|
||||
# Changesets
|
||||
|
||||
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
|
||||
with multi-package repos, or single-package repos to help you version and publish your code. You can
|
||||
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
|
||||
|
||||
We have a quick list of common questions to get you started engaging with this project in
|
||||
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/config@3.0.2/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "restricted",
|
||||
"baseBranch": "main",
|
||||
"updateInternalDependencies": "patch",
|
||||
"ignore": []
|
||||
}
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Setup Playwright
|
||||
@@ -102,7 +102,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -121,12 +121,12 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||
- run: bun format --check .
|
||||
- run: bun format:check
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
name: Lint
|
||||
@@ -136,7 +136,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -151,7 +151,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
@@ -166,7 +166,7 @@ jobs:
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.0.33
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
|
||||
fetch-depth: 0
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
env:
|
||||
PUPPETEER_SKIP_DOWNLOAD: 1
|
||||
- name: Create Release Pull Request or Publish to npm
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
publish: npm run release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
+4
-1
@@ -1 +1,4 @@
|
||||
.next
|
||||
.next
|
||||
|
||||
# Generated
|
||||
packages/emoji-codepoints/index.ts
|
||||
|
||||
@@ -106,6 +106,93 @@ const testCases: TestsCase[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'GitBook Site (Navigation when switching variant)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (Public)',
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
|
||||
await page.waitForURL(
|
||||
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/v/2.0/reference/api-reference/pets?fallback=true',
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (Share link)',
|
||||
url: 'api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
|
||||
await page.waitForURL(
|
||||
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/v/2.0/reference/api-reference/pets?fallback=true',
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (VA)',
|
||||
screenshot: false,
|
||||
url: (() => {
|
||||
const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
|
||||
await page.waitForURL(
|
||||
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/v/2.0/reference/api-reference/pets?fallback=true',
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'GitBook',
|
||||
baseUrl: 'https://docs.gitbook.com',
|
||||
@@ -276,6 +363,11 @@ const testCases: TestsCase[] = [
|
||||
name: 'Page options',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Hidden',
|
||||
url: 'page-options/page-hidden',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With cover',
|
||||
url: 'page-options/page-with-cover',
|
||||
|
||||
+19
-4
@@ -9,7 +9,7 @@ module.exports = withSentryConfig(
|
||||
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
|
||||
},
|
||||
|
||||
webpack(config) {
|
||||
webpack(config, { dev, webpack }) {
|
||||
config.resolve.fallback = {
|
||||
...config.resolve.fallback,
|
||||
|
||||
@@ -19,6 +19,21 @@ module.exports = withSentryConfig(
|
||||
http: false,
|
||||
};
|
||||
|
||||
// Tree shake debug code for Sentry
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-with-nextjs
|
||||
if (!dev) {
|
||||
config.plugins.push(
|
||||
new webpack.DefinePlugin({
|
||||
__SENTRY_DEBUG__: false,
|
||||
// We always init Sentry with enableTracing: false for now, so this is useless
|
||||
__SENTRY_TRACING__: false,
|
||||
__RRWEB_EXCLUDE_IFRAME__: true,
|
||||
__RRWEB_EXCLUDE_SHADOW_DOM__: true,
|
||||
__SENTRY_EXCLUDE_REPLAY_WORKER__: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
|
||||
@@ -45,9 +60,9 @@ module.exports = withSentryConfig(
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: '*.gitbook.io',
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
silent: true,
|
||||
|
||||
+7
-3
@@ -13,6 +13,8 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"unit": "bun test {src,packages}",
|
||||
"e2e": "playwright test",
|
||||
"changeset": "changeset",
|
||||
"release": "changeset publish",
|
||||
"postinstall": "rm -rf ./public/~gitbook/static/mathjax@3.2.2 && mkdir -p ./public/~gitbook/static/ && cp -R node_modules/mathjax/es5 ./public/~gitbook/static/mathjax@3.2.2"
|
||||
},
|
||||
"workspaces": [
|
||||
@@ -20,10 +22,11 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"@geist-ui/icons": "^1.0.2",
|
||||
"@gitbook/api": "^0.51.0",
|
||||
"@gitbook/api": "^0.56.0",
|
||||
"@radix-ui/react-checkbox": "^1.0.4",
|
||||
"@radix-ui/react-popover": "^1.0.7",
|
||||
"@sentry/nextjs": "^7.94.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.10",
|
||||
"@upstash/redis": "^1.27.1",
|
||||
@@ -38,9 +41,9 @@
|
||||
"katex": "^0.16.9",
|
||||
"mathjax": "^3.2.2",
|
||||
"memoizee": "^0.4.15",
|
||||
"next": "^14.2.4",
|
||||
"next": "^14.1.3",
|
||||
"next-themes": "^0.2.1",
|
||||
"nuqs": "^1.15.4",
|
||||
"nuqs": "^1.17.4",
|
||||
"object-hash": "^3.0.0",
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.0",
|
||||
@@ -64,6 +67,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^2.0.0",
|
||||
"@changesets/cli": "^2.27.7",
|
||||
"@cloudflare/next-on-pages": "^1.11.3",
|
||||
"@cloudflare/workers-types": "^4.20231218.0",
|
||||
"@playwright/test": "^1.42.1",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# @gitbook/emoji-codepoints
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57adb3e: Second release to fix publishing with changeset
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 5f8a8fe: Initial release
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "@gitbook/emoji-codepoints",
|
||||
"description": "Optimized mapping of codepoints to the fully qualified emoji codepoints",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"exports": "./index.ts",
|
||||
"dependencies": {},
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# @gitbook/react-contentkit
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57adb3e: Second release to fix publishing with changeset
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 5f8a8fe: Initial release
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"name": "@gitbook/react-contentkit",
|
||||
"version": "0.2.0",
|
||||
"exports": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"classnames": "^2.5.1",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# @gitbook/react-math
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57adb3e: Second release to fix publishing with changeset
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 5f8a8fe: Initial release
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "@gitbook/react-math",
|
||||
"exports": "./src/index.ts",
|
||||
"version": "0.2.0",
|
||||
"dependencies": {
|
||||
"object-hash": "^3.0.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# @gitbook/react-openapi
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57adb3e: Second release to fix publishing with changeset
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 5f8a8fe: Initial release
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "@gitbook/react-openapi",
|
||||
"exports": "./src/index.ts",
|
||||
"version": "0.2.0",
|
||||
"dependencies": {
|
||||
"@scalar/api-client-react": "^0.3.7",
|
||||
"@scalar/oas-utils": "0.1.6",
|
||||
|
||||
@@ -62,7 +62,10 @@ export function OpenAPIResponseExample(props: {
|
||||
|
||||
return (
|
||||
<InteractiveSection header="Response" className="openapi-response-example">
|
||||
<context.CodeBlock code={JSON.stringify(example, null, 2)} syntax="json" />
|
||||
<context.CodeBlock
|
||||
code={typeof example === 'string' ? example : JSON.stringify(example, null, 2)}
|
||||
syntax="json"
|
||||
/>
|
||||
</InteractiveSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,8 +48,12 @@ export function OpenAPISchemaProperty(
|
||||
: getSchemaAlternatives(schema, new Set(circularRefs.keys()));
|
||||
|
||||
const shouldDisplayExample = (schema: OpenAPIV3.SchemaObject): boolean => {
|
||||
return (typeof schema.example === 'string' || typeof schema.example === 'number' || typeof schema.example === 'boolean')
|
||||
}
|
||||
return (
|
||||
typeof schema.example === 'string' ||
|
||||
typeof schema.example === 'number' ||
|
||||
typeof schema.example === 'boolean'
|
||||
);
|
||||
};
|
||||
return (
|
||||
<InteractiveSection
|
||||
id={id}
|
||||
@@ -96,7 +100,9 @@ export function OpenAPISchemaProperty(
|
||||
/>
|
||||
) : null}
|
||||
{shouldDisplayExample(schema) ? (
|
||||
<span className="openapi-schema-example">Example: <code>{JSON.stringify(schema.example)}</code></span>
|
||||
<span className="openapi-schema-example">
|
||||
Example: <code>{JSON.stringify(schema.example)}</code>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
@@ -176,6 +182,8 @@ export function OpenAPIRootSchema(props: {
|
||||
|
||||
/**
|
||||
* Render a tab for an alternative schema.
|
||||
* It renders directly the properties if relevant;
|
||||
* for primitives, it renders the schema itself.
|
||||
*/
|
||||
function OpenAPISchemaAlternative(props: {
|
||||
schema: OpenAPIV3.SchemaObject;
|
||||
@@ -184,12 +192,13 @@ function OpenAPISchemaAlternative(props: {
|
||||
}) {
|
||||
const { schema, circularRefs, context } = props;
|
||||
const id = useId();
|
||||
const subProperties = getSchemaProperties(schema);
|
||||
|
||||
return (
|
||||
<OpenAPISchemaProperties
|
||||
id={id}
|
||||
properties={getSchemaProperties(schema) ?? []}
|
||||
circularRefs={new Map(circularRefs).set(schema, id)}
|
||||
properties={subProperties ?? [{ schema }]}
|
||||
circularRefs={subProperties ? new Map(circularRefs).set(schema, id) : circularRefs}
|
||||
context={context}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -19,7 +19,7 @@ export function generateSchemaExample(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (schema.example) {
|
||||
if (typeof schema.example !== 'undefined') {
|
||||
return schema.example;
|
||||
}
|
||||
|
||||
|
||||
+14
-2
@@ -1,8 +1,15 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import {
|
||||
BrowserClient,
|
||||
makeFetchTransport,
|
||||
defaultStackParser,
|
||||
getCurrentScope,
|
||||
} from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
Sentry.init({
|
||||
// To tree shake default integrations that we don't use
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-default-integrations
|
||||
const client = new BrowserClient({
|
||||
debug: false,
|
||||
dsn,
|
||||
integrations: [],
|
||||
@@ -11,5 +18,10 @@ if (dsn) {
|
||||
beforeSendTransaction: () => {
|
||||
return null;
|
||||
},
|
||||
transport: makeFetchTransport,
|
||||
stackParser: defaultStackParser,
|
||||
});
|
||||
|
||||
getCurrentScope().setClient(client);
|
||||
client.init();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { init } from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
Sentry.init({
|
||||
init({
|
||||
debug: false,
|
||||
dsn,
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { init } from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
Sentry.init({
|
||||
init({
|
||||
debug: false,
|
||||
dsn,
|
||||
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import { verifyImageSignature, resizeImage, CloudflareImageOptions } from '@/lib/images';
|
||||
import {
|
||||
verifyImageSignature,
|
||||
resizeImage,
|
||||
CloudflareImageOptions,
|
||||
checkIsSizableImageURL,
|
||||
} from '@/lib/images';
|
||||
import { parseImageAPIURL } from '@/lib/urls';
|
||||
|
||||
export const runtime = 'edge';
|
||||
@@ -13,6 +18,9 @@ export const runtime = 'edge';
|
||||
export async function GET(request: NextRequest) {
|
||||
let urlParam = request.nextUrl.searchParams.get('url');
|
||||
const signature = request.nextUrl.searchParams.get('sign');
|
||||
// The current signature algorithm sets version as 1, but we need to support the older version as well
|
||||
// for previously generated content. In this case, we default to version 0.
|
||||
const signatureVersion = (request.nextUrl.searchParams.get('sv') as '1') || '0';
|
||||
if (!urlParam || !signature) {
|
||||
return new Response('Missing url/sign parameters', { status: 400 });
|
||||
}
|
||||
@@ -24,8 +32,14 @@ export async function GET(request: NextRequest) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// Check again if the image can be sized, even though we checked when rendering the Image component
|
||||
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
|
||||
if (!checkIsSizableImageURL(url)) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// Verify the signature
|
||||
const verified = await verifyImageSignature(url, signature);
|
||||
const verified = await verifyImageSignature(url, { signature, version: signatureVersion });
|
||||
if (!verified) {
|
||||
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import { useScrollToHash } from '@/components/hooks';
|
||||
|
||||
/**
|
||||
@@ -9,5 +12,29 @@ export function PageClientLayout(props: {}) {
|
||||
// We use this hook in the page layout to ensure the elements for the blocks
|
||||
// are rendered before we scroll to the hash.
|
||||
useScrollToHash();
|
||||
|
||||
useStripFallbackQueryParam();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip the fallback query parameter from current URL.
|
||||
*
|
||||
* When the user switches variants using the space dropdown, we pass a fallback=true parameter.
|
||||
* This parameter indicates that we should redirect to the root page if the path from the
|
||||
* previous variant doesn't exist in the new variant. If the path does exist, no redirect occurs,
|
||||
* so we need to remove the fallback parameter.
|
||||
*/
|
||||
function useStripFallbackQueryParam() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (searchParams.has('fallback')) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete('fallback');
|
||||
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
|
||||
}
|
||||
}, [router, pathname, searchParams]);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import React from 'react';
|
||||
import { PageAside } from '@/components/PageAside';
|
||||
import { PageBody, PageCover } from '@/components/PageBody';
|
||||
import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
|
||||
import { getPagePath } from '@/lib/pages';
|
||||
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
|
||||
import { ContentRefContext } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getContentTitle } from '@/lib/utils';
|
||||
@@ -19,21 +19,29 @@ export const runtime = 'edge';
|
||||
/**
|
||||
* Fetch and render a page.
|
||||
*/
|
||||
export default async function Page(props: { params: PagePathParams }) {
|
||||
const { params } = props;
|
||||
export default async function Page(props: {
|
||||
params: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
}) {
|
||||
const { params, searchParams } = props;
|
||||
|
||||
const rawPathname = getPathnameParam(params);
|
||||
const {
|
||||
content: contentPointer,
|
||||
contentTarget,
|
||||
space,
|
||||
parent,
|
||||
customization,
|
||||
pages,
|
||||
page,
|
||||
document,
|
||||
} = await fetchPageData(params);
|
||||
const linksContext: PageHrefContext = {};
|
||||
} = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
searchParams,
|
||||
redirectOnFallback: true,
|
||||
});
|
||||
|
||||
const linksContext: PageHrefContext = {};
|
||||
const rawPathname = getPathnameParam(params);
|
||||
if (!page) {
|
||||
const pathname = normalizePathname(rawPathname);
|
||||
if (pathname !== rawPathname) {
|
||||
@@ -84,6 +92,7 @@ export default async function Page(props: { params: PagePathParams }) {
|
||||
{page.layout.outline ? (
|
||||
<PageAside
|
||||
space={space}
|
||||
site={parent?.object === 'site' ? parent : undefined}
|
||||
customization={customization}
|
||||
page={page}
|
||||
document={document}
|
||||
@@ -112,8 +121,18 @@ export async function generateViewport({ params }: { params: PagePathParams }):
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: { params: PagePathParams }): Promise<Metadata> {
|
||||
const { space, pages, page, customization, parent } = await fetchPageData(params);
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
}): Promise<Metadata> {
|
||||
const { space, pages, page, customization, parent } = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
searchParams,
|
||||
});
|
||||
|
||||
if (!page) {
|
||||
notFound();
|
||||
}
|
||||
@@ -134,3 +153,34 @@ export async function generateMetadata({ params }: { params: PagePathParams }):
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the page data matching the requested pathname and fallback to root page when page is not found.
|
||||
*/
|
||||
async function getPageDataWithFallback(args: {
|
||||
pagePathParams: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
redirectOnFallback?: boolean;
|
||||
}) {
|
||||
const { pagePathParams, searchParams, redirectOnFallback = false } = args;
|
||||
|
||||
const { pages, page: targetPage, ...otherPageData } = await fetchPageData(pagePathParams);
|
||||
|
||||
let page = targetPage;
|
||||
const canFallback = !!searchParams.fallback;
|
||||
if (!page && canFallback) {
|
||||
const rootPage = resolveFirstDocument(pages, []);
|
||||
|
||||
if (redirectOnFallback && rootPage?.page) {
|
||||
redirect(pageHref(pages, rootPage?.page));
|
||||
}
|
||||
|
||||
page = rootPage?.page;
|
||||
}
|
||||
|
||||
return {
|
||||
...otherPageData,
|
||||
pages,
|
||||
page,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Revision,
|
||||
RevisionPageDocument,
|
||||
RevisionPageGroup,
|
||||
RevisionPageLink,
|
||||
SiteCustomizationSettings,
|
||||
Space,
|
||||
} from '@gitbook/api';
|
||||
@@ -313,9 +314,17 @@ function selectPages(
|
||||
): FlatPageEntry[] => {
|
||||
return [
|
||||
{ page, depth },
|
||||
...page.pages.flatMap((child) =>
|
||||
child.type === 'link' ? [] : flattenPage(child, depth + 1),
|
||||
),
|
||||
...page.pages.flatMap((child) => {
|
||||
if (child.type === 'link') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (child.hidden) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return flattenPage(child, depth + 1);
|
||||
}),
|
||||
];
|
||||
};
|
||||
|
||||
@@ -340,8 +349,16 @@ function selectPages(
|
||||
return limitTo(flattenPage(found.page, 0));
|
||||
}
|
||||
|
||||
const allPages = rootPages.flatMap((page) =>
|
||||
page.type === 'link' ? [] : flattenPage(page, 0),
|
||||
);
|
||||
const allPages = rootPages.flatMap((page) => {
|
||||
if (page.type === 'link') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (page.hidden) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return flattenPage(page, 0);
|
||||
});
|
||||
return limitTo(allPages);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { captureException } from '@sentry/nextjs';
|
||||
import React from 'react';
|
||||
|
||||
import { Button } from '@/components/primitives/Button';
|
||||
@@ -15,7 +15,7 @@ export default function ErrorPage(props: {
|
||||
const language = useLanguage();
|
||||
|
||||
React.useEffect(() => {
|
||||
Sentry.captureException(error);
|
||||
captureException(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { captureException } from '@sentry/nextjs';
|
||||
import Error from 'next/error';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function GlobalError({ error }: { error: Error }) {
|
||||
useEffect(() => {
|
||||
Sentry.captureException(error);
|
||||
captureException(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import IconHeart from '@geist-ui/icons/heart';
|
||||
import * as React from 'react';
|
||||
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdClassicRendering } from './AdClassicRendering';
|
||||
import { AdCoverRendering } from './AdCoverRendering';
|
||||
import { AdItem, AdsResponse } from './types';
|
||||
|
||||
/**
|
||||
* Fetch and render the Ad placement.
|
||||
* https://docs.buysellads.com/ad-serving-api
|
||||
*/
|
||||
export function Ad({
|
||||
zoneId,
|
||||
spaceId,
|
||||
placement,
|
||||
ignore,
|
||||
style,
|
||||
mode = 'auto',
|
||||
}: {
|
||||
zoneId: string;
|
||||
spaceId: string;
|
||||
placement: string;
|
||||
ignore: boolean;
|
||||
style?: ClassValue;
|
||||
mode?: 'classic' | 'auto' | 'cover';
|
||||
}) {
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
const [visible, setVisible] = React.useState(false);
|
||||
const [failed, setFailed] = React.useState(false);
|
||||
const [ad, setAd] = React.useState<AdItem | undefined>(undefined);
|
||||
|
||||
// Observe the container visibility
|
||||
React.useEffect(() => {
|
||||
if (!containerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setVisible(true);
|
||||
}
|
||||
},
|
||||
{
|
||||
root: null,
|
||||
rootMargin: '0px',
|
||||
threshold: 0.1,
|
||||
},
|
||||
);
|
||||
|
||||
observer.observe(containerRef.current);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// When the container is visible,
|
||||
// track an impression on the ad and fetch it
|
||||
React.useEffect(() => {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
(async () => {
|
||||
const url = new URL(`https://srv.buysellads.com/ads/${zoneId}.json`);
|
||||
url.searchParams.set('segment', `placement:${placement}`);
|
||||
url.searchParams.set('v', 'true');
|
||||
if (ignore) {
|
||||
url.searchParams.set('ignore', 'true');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const json: AdsResponse = await res.json();
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const first = json.ads[0];
|
||||
if (first && 'active' in first) {
|
||||
setAd(first);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Failed to fetch ad, it might have been blocked by a ad-blocker',
|
||||
error,
|
||||
);
|
||||
setFailed(true);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [visible, zoneId, ignore, placement]);
|
||||
|
||||
const viaUrl = new URL('https://www.gitbook.com');
|
||||
viaUrl.searchParams.set('utm_source', 'content');
|
||||
viaUrl.searchParams.set('utm_medium', 'ads');
|
||||
viaUrl.searchParams.set('utm_campaign', spaceId);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={tcls(style)}>
|
||||
{ad && ad.description && ad.statlink ? (
|
||||
<>
|
||||
{mode === 'classic' || !('callToAction' in ad) ? (
|
||||
<AdClassicRendering ad={ad} />
|
||||
) : (
|
||||
<AdCoverRendering ad={ad} />
|
||||
)}
|
||||
{ad.pixel ? <AdPixels rawPixel={ad.pixel} /> : null}
|
||||
<p
|
||||
className={tcls(
|
||||
'mt-2',
|
||||
'mr-2',
|
||||
'text-xs',
|
||||
'text-right',
|
||||
'text-dark/5',
|
||||
'dark:text-light/5',
|
||||
)}
|
||||
>
|
||||
<a
|
||||
target="_blank"
|
||||
href={viaUrl.toString()}
|
||||
className={tcls('hover:underline')}
|
||||
>
|
||||
Ads via GitBook
|
||||
</a>
|
||||
</p>
|
||||
</>
|
||||
) : failed ? (
|
||||
<AdBlockerPlaceholder />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render attribution or verification pixels.
|
||||
* https://docs.buysellads.com/ad-serving-api#pixels
|
||||
*/
|
||||
function AdPixels({ rawPixel }: { rawPixel: string }) {
|
||||
const pixels = rawPixel.split('||');
|
||||
const time = String(Math.round(Date.now() / 1e4) | 0);
|
||||
|
||||
return (
|
||||
<div className={tcls('hidden')}>
|
||||
{pixels.map((pixel, index) => {
|
||||
return (
|
||||
<img
|
||||
key={index}
|
||||
src={pixel.replace('[timestamp]', time)}
|
||||
width="1"
|
||||
height="1"
|
||||
style={{ display: 'none' }}
|
||||
alt="Ads tracking pixel"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder when visitor has an ad-blocker.
|
||||
*/
|
||||
function AdBlockerPlaceholder() {
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-3',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
)}
|
||||
>
|
||||
<div className={tcls('flex', 'flex-row', 'gap-2', 'items-center')}>
|
||||
<IconHeart className={tcls('w-4', 'h-4', 'text-primary-500')} />
|
||||
<p className={tcls('text-xs', 'font-semibold')}>Ad disabled</p>
|
||||
</div>
|
||||
<p className={tcls('text-xs')}>
|
||||
{`It looks like you're using an adblocker. Whitelist this site to help support this
|
||||
project.`}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdItem } from './types';
|
||||
|
||||
/**
|
||||
* Classic rendering for an ad.
|
||||
*/
|
||||
export function AdClassicRendering({ ad }: { ad: AdItem }) {
|
||||
return (
|
||||
<a
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-4',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'hover:text-dark/9',
|
||||
'dark:hover:text-light/9',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
)}
|
||||
href={ad.statlink}
|
||||
rel="sponsored noopener"
|
||||
target="_blank"
|
||||
>
|
||||
{'smallImage' in ad ? (
|
||||
<div>
|
||||
<img alt="Ads logo" className={tcls('rounded-md')} src={ad.smallImage} />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={tcls('px-6', 'py-4', 'rounded-md')}
|
||||
style={{ backgroundColor: ad.backgroundColor }}
|
||||
>
|
||||
<img alt="Ads logo" src={ad.logo} />
|
||||
</div>
|
||||
)}
|
||||
<div className={tcls('flex', 'flex-col')}>
|
||||
<div className={tcls('text-xs')}>{ad.description}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { hexToRgba } from '@/lib/colors';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdCover } from './types';
|
||||
|
||||
/**
|
||||
* Cover rendering for an ad.
|
||||
*/
|
||||
export function AdCoverRendering({ ad }: { ad: AdCover }) {
|
||||
return (
|
||||
<a
|
||||
className={tcls(
|
||||
'group/ad',
|
||||
'relative',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-4',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'hover:text-dark/9',
|
||||
'dark:hover:text-light/9',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
'overflow-hidden',
|
||||
'shadow-sm',
|
||||
)}
|
||||
style={{ backgroundColor: ad.backgroundColor, color: ad.textColor ?? '#ffffff' }}
|
||||
href={ad.statlink}
|
||||
rel="sponsored noopener"
|
||||
target="_blank"
|
||||
>
|
||||
<div
|
||||
className={tcls(
|
||||
'absolute',
|
||||
'inset-0',
|
||||
'bg-center',
|
||||
'bg-cover',
|
||||
'bg-no-repeat',
|
||||
'z-0',
|
||||
)}
|
||||
style={{
|
||||
backgroundImage: `url(${ad.largeImage})`,
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={tcls('z-[2]')}>
|
||||
<img
|
||||
alt="Large image"
|
||||
src={ad.largeImage}
|
||||
className={tcls(
|
||||
'rounded-md',
|
||||
'shadow-md',
|
||||
'max-h-32',
|
||||
'group-hover/ad:max-h-16',
|
||||
'transition-all',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className={tcls('z-[2]')}>
|
||||
<img alt={ad.company} src={ad.logo} className={tcls('max-w-36', 'max-h-12')} />
|
||||
</div>
|
||||
<div className={tcls('flex', 'flex-col', 'z-[2]')}>
|
||||
<div className={tcls('text-sm', 'font-semibold', 'mb-2')}>{ad.companyTagline}</div>
|
||||
<div
|
||||
className={tcls(
|
||||
'text-xs',
|
||||
'h-0',
|
||||
'opacity-0',
|
||||
'group-hover/ad:h-16',
|
||||
'group-hover/ad:opacity-10',
|
||||
'transition-all',
|
||||
)}
|
||||
>
|
||||
{ad.description}
|
||||
</div>
|
||||
</div>
|
||||
<div className={tcls('z-[2]')}>
|
||||
<span
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'font-semibold',
|
||||
'shadow-lg',
|
||||
'rounded-md',
|
||||
'bg-white',
|
||||
'py-2',
|
||||
'px-4',
|
||||
)}
|
||||
style={{
|
||||
backgroundColor: ad.ctaBackgroundColor,
|
||||
color: ad.ctaTextColor ?? ad.backgroundColor,
|
||||
}}
|
||||
>
|
||||
{ad.callToAction}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={tcls('absolute', 'inset-0', 'backdrop-blur', 'z-[1]')}
|
||||
style={{
|
||||
backgroundColor: hexToRgba(ad.backgroundColor, 0.8),
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './Ad';
|
||||
@@ -0,0 +1,51 @@
|
||||
export interface AdGeneric {
|
||||
active: string;
|
||||
ad_via_link: string;
|
||||
bannerid: string;
|
||||
creativeid: string;
|
||||
evenodd: string;
|
||||
external_id: string;
|
||||
height: string;
|
||||
i: string;
|
||||
identifier: string;
|
||||
longimp: string;
|
||||
longlink: string;
|
||||
num_slots: string;
|
||||
statimp: string;
|
||||
statlink: string;
|
||||
timestamp: string;
|
||||
width: string;
|
||||
zoneid: string;
|
||||
zonekey: string;
|
||||
rendering: 'carbon';
|
||||
pixel?: string;
|
||||
}
|
||||
|
||||
export interface AdClassic extends AdGeneric {
|
||||
description: string;
|
||||
smallImage: string;
|
||||
}
|
||||
|
||||
export interface AdCover extends AdGeneric {
|
||||
backgroundColor: string;
|
||||
backgroundHoverColor?: string;
|
||||
textColor?: string;
|
||||
textColorHover?: string;
|
||||
callToAction: string;
|
||||
company: string;
|
||||
companyTagline: string;
|
||||
description: string;
|
||||
largeImage: string;
|
||||
image?: string;
|
||||
logo: string;
|
||||
ctaBackgroundColor?: string;
|
||||
ctaBackgroundHoverColor?: string;
|
||||
ctaTextColor?: string;
|
||||
ctaTextColorHover?: string;
|
||||
}
|
||||
|
||||
export type AdItem = AdClassic | AdCover;
|
||||
|
||||
export interface AdsResponse {
|
||||
ads: Array<AdItem | {}>;
|
||||
}
|
||||
@@ -1,27 +1,72 @@
|
||||
import { DocumentBlockContentRef } from '@gitbook/api';
|
||||
|
||||
import { LogoIcon } from '@/components/icons';
|
||||
import { Card, Emoji } from '@/components/primitives';
|
||||
import { getSpaceCustomization, ignoreAPIError } from '@/lib/api';
|
||||
import { ResolvedContentRef } from '@/lib/references';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
|
||||
export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>) {
|
||||
const { block, context, style } = props;
|
||||
const kind = block?.data?.ref?.kind;
|
||||
|
||||
const resolved = await context.resolveContentRef(block.data.ref, {
|
||||
resolveAnchorText: true,
|
||||
});
|
||||
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isContentInOtherSpace =
|
||||
context.contentRefContext?.space &&
|
||||
'space' in block.data.ref &&
|
||||
context.contentRefContext.space.id !== block.data.ref.space;
|
||||
const kind = block?.data?.ref?.kind;
|
||||
if ((resolved.active && kind === 'space') || isContentInOtherSpace) {
|
||||
return <SpaceRefCard {...props} resolved={resolved} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
leadingIcon={resolved.emoji ? <Emoji code={resolved.emoji} /> : null}
|
||||
leadingIcon={resolved.emoji ? <Emoji code={resolved.emoji} style="text-xl" /> : null}
|
||||
href={resolved.href}
|
||||
preTitle={kind}
|
||||
title={resolved.text}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function SpaceRefCard(
|
||||
props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>,
|
||||
) {
|
||||
const { context, style, resolved } = props;
|
||||
const spaceId = context.contentRefContext?.space.id;
|
||||
|
||||
if (!spaceId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId));
|
||||
const customFavicon = spaceCustomization?.favicon;
|
||||
const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined;
|
||||
const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined;
|
||||
|
||||
return (
|
||||
<Card
|
||||
leadingIcon={
|
||||
<LogoIcon
|
||||
icon={customIcon}
|
||||
emoji={customEmoji}
|
||||
alt=""
|
||||
sizes={[{ width: 24 }]}
|
||||
style={['object-contain', 'size-6']}
|
||||
/>
|
||||
}
|
||||
href={resolved.href}
|
||||
title={resolved.text}
|
||||
postTitle={resolved.subText}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as gitbookAPI from '@gitbook/api';
|
||||
import { headers } from 'next/headers';
|
||||
import Script from 'next/script';
|
||||
import ReactDOM from 'react-dom';
|
||||
|
||||
@@ -12,8 +13,9 @@ import { IntegrationBlock } from './Integration';
|
||||
|
||||
export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
|
||||
const { block, context, ...otherProps } = props;
|
||||
|
||||
ReactDOM.preconnect('https://cdn.iframe.ly');
|
||||
const nonce = headers().get('x-nonce') || undefined;
|
||||
|
||||
ReactDOM.preload('https://cdn.iframe.ly/embed.js', { as: 'script', nonce });
|
||||
|
||||
const { data: embed } = await (context.content
|
||||
? api().spaces.getEmbedByUrlInSpace(context.content.spaceId, { url: block.data.url })
|
||||
@@ -28,8 +30,7 @@ export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
|
||||
__html: embed.html,
|
||||
}}
|
||||
/>
|
||||
{/* We load the iframely script to resize the embed iframes dynamically */}
|
||||
<Script src="https://cdn.iframe.ly/embed.js" defer async />
|
||||
<Script src="https://cdn.iframe.ly/embed.js" nonce={nonce} />
|
||||
</>
|
||||
) : embed.type === 'integration' ? (
|
||||
<IntegrationBlock
|
||||
|
||||
@@ -5,8 +5,16 @@
|
||||
rgb(var(--primary-base-300, 180 180 180)),
|
||||
rgb(var(--dark-base, 23 23 23)) 96%
|
||||
);
|
||||
--scalar-color-2: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.72));
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.72)
|
||||
);
|
||||
--scalar-color-3: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.4)
|
||||
);
|
||||
--scalar-color-accent: #007d9c;
|
||||
|
||||
--scalar-background-1: rgb(var(--light-base, 255 255 255));
|
||||
@@ -50,8 +58,16 @@
|
||||
rgb(var(--primary-base-700, 70 70 70)),
|
||||
rgb(var(--light-base, 255 255 255)) 100%
|
||||
);
|
||||
--scalar-color-2: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.64));
|
||||
--scalar-color-3: color-mix(in srgb, var(--scalar-color-1), transparent calc(100% - 100% * 0.4));
|
||||
--scalar-color-2: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.64)
|
||||
);
|
||||
--scalar-color-3: color-mix(
|
||||
in srgb,
|
||||
var(--scalar-color-1),
|
||||
transparent calc(100% - 100% * 0.4)
|
||||
);
|
||||
--scalar-color-accent: #50b7e0;
|
||||
|
||||
--scalar-background-1: rgb(var(--dark-base, 22 22 22));
|
||||
@@ -330,4 +346,4 @@
|
||||
.scalar .custom-scroll {
|
||||
padding-right: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@gitbook/api';
|
||||
|
||||
import { HeaderMobileMenu } from '@/components/Header/HeaderMobileMenu';
|
||||
import { LogoIcon } from '@/components/icons';
|
||||
import { Image } from '@/components/utils';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
@@ -95,40 +96,18 @@ export function HeaderLogo(props: HeaderLogoProps) {
|
||||
|
||||
function LogoFallback(props: HeaderLogoProps) {
|
||||
const { parent, space, customization } = props;
|
||||
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : null;
|
||||
|
||||
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : undefined;
|
||||
const customEmoji = 'emoji' in customization.favicon ? customization.favicon.emoji : undefined;
|
||||
return (
|
||||
<>
|
||||
<Image
|
||||
alt="Logo"
|
||||
sources={
|
||||
customIcon
|
||||
? {
|
||||
light: { src: customIcon.light, aspectRatio: '1' },
|
||||
dark: customIcon.dark
|
||||
? { src: customIcon.dark, aspectRatio: '1' }
|
||||
: null,
|
||||
}
|
||||
: {
|
||||
light: {
|
||||
src: absoluteHref('~gitbook/icon?size=medium&theme=light', true),
|
||||
size: { width: 256, height: 256 },
|
||||
},
|
||||
dark: {
|
||||
src: absoluteHref('~gitbook/icon?size=medium&theme=dark', true),
|
||||
size: { width: 256, height: 256 },
|
||||
},
|
||||
}
|
||||
}
|
||||
sizes={[
|
||||
{
|
||||
width: 32,
|
||||
},
|
||||
]}
|
||||
<LogoIcon
|
||||
icon={customIcon}
|
||||
emoji={customEmoji}
|
||||
alt=""
|
||||
sizes={[{ width: 32 }]}
|
||||
style={['object-contain', 'size-8']}
|
||||
fetchPriority="high"
|
||||
style={['w-8', 'h-8', 'object-contain']}
|
||||
/>
|
||||
|
||||
<h1
|
||||
className={tcls(
|
||||
'text-pretty',
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Collection, Space } from '@gitbook/api';
|
||||
import { Space } from '@gitbook/api';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { Dropdown, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown';
|
||||
import { Dropdown, DropdownChevron, DropdownMenu } from './Dropdown';
|
||||
import { SpacesDropdownMenuItem } from './SpacesDropdownMenuItem';
|
||||
|
||||
export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
const { space, spaces } = props;
|
||||
@@ -29,14 +30,16 @@ export function SpacesDropdown(props: { space: Space; spaces: Space[] }) {
|
||||
)}
|
||||
>
|
||||
<DropdownMenu>
|
||||
{spaces.map((otherSpace) => (
|
||||
<DropdownMenuItem
|
||||
key={otherSpace.id}
|
||||
href={otherSpace.urls.published ?? otherSpace.urls.app}
|
||||
{spaces.map((otherSpace, index) => (
|
||||
<SpacesDropdownMenuItem
|
||||
key={`${otherSpace.id}-${index}`}
|
||||
variantSpace={{
|
||||
id: otherSpace.id,
|
||||
title: otherSpace.title,
|
||||
url: otherSpace.urls.published ?? otherSpace.urls.app,
|
||||
}}
|
||||
active={otherSpace.id === space.id}
|
||||
>
|
||||
{otherSpace.title}
|
||||
</DropdownMenuItem>
|
||||
/>
|
||||
))}
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
'use client';
|
||||
|
||||
import { Space } from '@gitbook/api';
|
||||
import { useSelectedLayoutSegment } from 'next/navigation';
|
||||
|
||||
import { DropdownMenuItem } from './Dropdown';
|
||||
|
||||
function useVariantSpaceHref(variantSpaceUrl: string) {
|
||||
const currentPathname = useSelectedLayoutSegment() ?? '';
|
||||
const targetUrl = new URL(variantSpaceUrl);
|
||||
targetUrl.pathname += `/${currentPathname}`;
|
||||
targetUrl.pathname = targetUrl.pathname.replace(/\/{2,}/g, '/').replace(/\/$/, '');
|
||||
targetUrl.searchParams.set('fallback', 'true');
|
||||
|
||||
return targetUrl.toString();
|
||||
}
|
||||
|
||||
export function SpacesDropdownMenuItem(props: {
|
||||
variantSpace: { id: Space['id']; title: Space['title']; url: string };
|
||||
active: boolean;
|
||||
}) {
|
||||
const { variantSpace, active } = props;
|
||||
const variantHref = useVariantSpaceHref(variantSpace.url);
|
||||
|
||||
return (
|
||||
<DropdownMenuItem key={variantSpace.id} href={variantHref} active={active}>
|
||||
{variantSpace.title}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
CustomizationSettings,
|
||||
JSONDocument,
|
||||
RevisionPageDocument,
|
||||
Site,
|
||||
SiteCustomizationSettings,
|
||||
Space,
|
||||
} from '@gitbook/api';
|
||||
@@ -17,9 +18,10 @@ import { getDocumentSections } from '@/lib/document';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getPDFUrl, getPDFUrlSearchParams } from '@/lib/urls';
|
||||
import { getPDFUrlSearchParams } from '@/lib/urls';
|
||||
|
||||
import { ScrollSectionsList } from './ScrollSectionsList';
|
||||
import { Ad } from '../Ads';
|
||||
import { PageFeedbackForm } from '../PageFeedback';
|
||||
|
||||
/**
|
||||
@@ -27,6 +29,7 @@ import { PageFeedbackForm } from '../PageFeedback';
|
||||
*/
|
||||
export async function PageAside(props: {
|
||||
space: Space;
|
||||
site: Site | undefined;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
page: RevisionPageDocument;
|
||||
document: JSONDocument | null;
|
||||
@@ -35,8 +38,16 @@ export async function PageAside(props: {
|
||||
withFullPageCover: boolean;
|
||||
withPageFeedback: boolean;
|
||||
}) {
|
||||
const { space, page, document, customization, withHeaderOffset, withPageFeedback, context } =
|
||||
props;
|
||||
const {
|
||||
space,
|
||||
site,
|
||||
page,
|
||||
document,
|
||||
customization,
|
||||
withHeaderOffset,
|
||||
withPageFeedback,
|
||||
context,
|
||||
} = props;
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
return (
|
||||
@@ -172,6 +183,15 @@ export async function PageAside(props: {
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{site?.ads ? (
|
||||
<Ad
|
||||
zoneId={site.ads.zone}
|
||||
placement="page.aside"
|
||||
spaceId={space.id}
|
||||
ignore={process.env.NODE_ENV !== 'production'}
|
||||
style={tcls('mt-4')}
|
||||
/>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,10 +6,11 @@ import { atom, useRecoilState } from 'recoil';
|
||||
import { Loading } from '@/components/primitives';
|
||||
import { useLanguage } from '@/intl/client';
|
||||
import { t } from '@/intl/translate';
|
||||
import { TranslationLanguage } from '@/intl/translations';
|
||||
import { iterateStreamResponse } from '@/lib/actions';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AskAnswerResult, streamAskQuestion } from './server-actions';
|
||||
import { AskAnswerResult, AskAnswerSource, streamAskQuestion } from './server-actions';
|
||||
import { useSearch, useSearchLink } from './useSearch';
|
||||
import { Link } from '../primitives';
|
||||
|
||||
@@ -94,6 +95,11 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
};
|
||||
}, [setState]);
|
||||
|
||||
let hasAnswer = false;
|
||||
if (state && 'answer' in state) {
|
||||
hasAnswer = !!state?.answer?.body;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
@@ -129,108 +135,128 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
|
||||
|
||||
function AnswerBody(props: { answer: AskAnswerResult }) {
|
||||
const { answer } = props;
|
||||
const getSearchLinkProps = useSearchLink();
|
||||
const language = useLanguage();
|
||||
|
||||
const [, setSearchState] = useSearch();
|
||||
const onClose = () => {
|
||||
setSearchState(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-test="search-ask-answer"
|
||||
className={tcls('mt-4', 'px-4', 'text-dark/9', 'dark:text-light/8')}
|
||||
>
|
||||
{answer.body}
|
||||
{answer.hasAnswer ? answer.body : t(language, 'search_ask_no_answer')}
|
||||
</div>
|
||||
{answer.followupQuestions.length > 0 ? (
|
||||
<div className={tcls('mt-7', 'flex', 'flex-col', 'flex-wrap', 'gap-1')}>
|
||||
{answer.followupQuestions.map((question) => (
|
||||
<Link
|
||||
key={question}
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'font-medium',
|
||||
'inline-flex',
|
||||
'items-start',
|
||||
'gap-2',
|
||||
'px-4',
|
||||
'py-1',
|
||||
'text-primary-500',
|
||||
'focus-within:text-primary-700',
|
||||
'hover:bg-primary/2',
|
||||
'dark:text-primary-400',
|
||||
'dark:hover:bg-primary-500/3',
|
||||
)}
|
||||
{...getSearchLinkProps({
|
||||
query: question,
|
||||
ask: true,
|
||||
})}
|
||||
>
|
||||
<IconSearch
|
||||
className={tcls(
|
||||
'w-[15px]',
|
||||
'h-[15px]',
|
||||
'shrink-0',
|
||||
'mt-0.5',
|
||||
'[&>path]:[stroke-opacity:0.64]',
|
||||
)}
|
||||
/>
|
||||
<span>{question}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
|
||||
) : null}
|
||||
{answer.sources.length > 0 ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-wrap',
|
||||
'gap-2',
|
||||
'mt-7',
|
||||
'py-4',
|
||||
'px-4',
|
||||
'border-t',
|
||||
'border-dark/2',
|
||||
'dark:border-light/1',
|
||||
)}
|
||||
>
|
||||
<span className={tcls('text-sm')}>{t(language, 'search_ask_sources')}</span>
|
||||
|
||||
{answer.sources.map((source) => (
|
||||
<span key={source.id} className={tcls()}>
|
||||
<Link
|
||||
onClick={onClose}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'text-sm',
|
||||
'text-dark/7',
|
||||
'hover:underline',
|
||||
'focus-within:text-primary-700',
|
||||
'dark:text-light/8',
|
||||
)}
|
||||
href={source.href}
|
||||
prefetch={false}
|
||||
>
|
||||
<IconBox
|
||||
className={tcls(
|
||||
'stroke-dark/6',
|
||||
'w-[15px]',
|
||||
'h-[15px]',
|
||||
'shrink-0',
|
||||
'mt-0.5',
|
||||
'mr-0.5',
|
||||
'dark:stroke-light/6',
|
||||
)}
|
||||
/>
|
||||
{source.title}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<AnswerSources
|
||||
hasAnswer={answer.hasAnswer}
|
||||
sources={answer.sources}
|
||||
language={language}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
|
||||
const { followupQuestions } = props;
|
||||
const getSearchLinkProps = useSearchLink();
|
||||
|
||||
return (
|
||||
<div className={tcls('mt-7 mb-4', 'flex', 'flex-col', 'flex-wrap', 'gap-1')}>
|
||||
{followupQuestions.map((question) => (
|
||||
<Link
|
||||
key={question}
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'font-medium',
|
||||
'inline-flex',
|
||||
'items-start',
|
||||
'gap-2',
|
||||
'px-4',
|
||||
'py-1',
|
||||
'text-primary-500',
|
||||
'focus-within:text-primary-700',
|
||||
'hover:bg-primary/2',
|
||||
'dark:text-primary-400',
|
||||
'dark:hover:bg-primary-500/3',
|
||||
)}
|
||||
{...getSearchLinkProps({
|
||||
query: question,
|
||||
ask: true,
|
||||
})}
|
||||
>
|
||||
<IconSearch
|
||||
className={tcls(
|
||||
'w-[15px]',
|
||||
'h-[15px]',
|
||||
'shrink-0',
|
||||
'mt-0.5',
|
||||
'[&>path]:[stroke-opacity:0.64]',
|
||||
)}
|
||||
/>
|
||||
<span>{question}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AnswerSources(props: {
|
||||
sources: AskAnswerSource[];
|
||||
language: TranslationLanguage;
|
||||
hasAnswer?: boolean;
|
||||
}) {
|
||||
const { sources, language, hasAnswer } = props;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-wrap',
|
||||
'gap-2',
|
||||
'mt-7',
|
||||
'py-4',
|
||||
'px-4',
|
||||
'border-t',
|
||||
'border-dark/2',
|
||||
'dark:border-light/1',
|
||||
)}
|
||||
>
|
||||
<span className={tcls('text-sm')}>
|
||||
{t(language, hasAnswer ? 'search_ask_sources' : 'search_ask_sources_no_answer')}
|
||||
</span>
|
||||
|
||||
{sources.map((source) => (
|
||||
<span key={source.id} className={tcls()}>
|
||||
<Link
|
||||
className={tcls(
|
||||
'flex',
|
||||
'text-sm',
|
||||
'text-dark/7',
|
||||
'hover:underline',
|
||||
'focus-within:text-primary-700',
|
||||
'dark:text-light/8',
|
||||
)}
|
||||
href={source.href}
|
||||
prefetch={false}
|
||||
>
|
||||
<IconBox
|
||||
className={tcls(
|
||||
'stroke-dark/6',
|
||||
'w-[15px]',
|
||||
'h-[15px]',
|
||||
'shrink-0',
|
||||
'mt-0.5',
|
||||
'mr-0.5',
|
||||
'dark:stroke-light/6',
|
||||
)}
|
||||
/>
|
||||
{source.title}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -232,28 +232,23 @@ function SearchModalBody(
|
||||
</div>
|
||||
</div>
|
||||
{!state.ask || !withAsk ? (
|
||||
<>
|
||||
<SearchResults
|
||||
ref={resultsRef}
|
||||
spaceId={spaceId}
|
||||
revisionId={revisionId}
|
||||
parent={state.global ? parent : null}
|
||||
query={state.query}
|
||||
withAsk={withAsk}
|
||||
onSwitchToAsk={() => {
|
||||
onChangeQuery({
|
||||
ask: true,
|
||||
query: state.query,
|
||||
global: state.global,
|
||||
});
|
||||
}}
|
||||
onClose={onClose}
|
||||
>
|
||||
{parent && state.query ? (
|
||||
<SearchScopeToggle spaceTitle={spaceTitle} />
|
||||
) : null}
|
||||
</SearchResults>
|
||||
</>
|
||||
<SearchResults
|
||||
ref={resultsRef}
|
||||
spaceId={spaceId}
|
||||
revisionId={revisionId}
|
||||
parent={state.global ? parent : null}
|
||||
query={state.query}
|
||||
withAsk={withAsk}
|
||||
onSwitchToAsk={() => {
|
||||
onChangeQuery({
|
||||
ask: true,
|
||||
query: state.query,
|
||||
global: state.global,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{parent && state.query ? <SearchScopeToggle spaceTitle={spaceTitle} /> : null}
|
||||
</SearchResults>
|
||||
) : null}
|
||||
{state.query && state.ask && withAsk ? (
|
||||
<SearchAskAnswer spaceId={spaceId} query={state.query} />
|
||||
|
||||
@@ -11,20 +11,15 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
|
||||
query: string;
|
||||
item: ComputedPageResult;
|
||||
active: boolean;
|
||||
onClick: (to: string) => void;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>,
|
||||
) {
|
||||
const { query, item, active, onClick } = props;
|
||||
const { query, item, active } = props;
|
||||
|
||||
return (
|
||||
<Link
|
||||
ref={ref}
|
||||
href={item.href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
onClick(item.href);
|
||||
}}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
|
||||
@@ -43,11 +43,10 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
parent: Site | Collection | null;
|
||||
withAsk: boolean;
|
||||
onSwitchToAsk: () => void;
|
||||
onClose: (to?: string) => void;
|
||||
},
|
||||
ref: React.Ref<SearchResultsRef>,
|
||||
) {
|
||||
const { children, query, spaceId, revisionId, parent, withAsk, onSwitchToAsk, onClose } = props;
|
||||
const { children, query, spaceId, revisionId, parent, withAsk, onSwitchToAsk } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
const debounceTimeout = React.useRef<NodeJS.Timeout | null>(null);
|
||||
@@ -97,6 +96,7 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
const fetchedResults = await (parent
|
||||
? searchParentContent(parent, query)
|
||||
: searchSpaceContent(spaceId, revisionId, query));
|
||||
|
||||
setResults(withAsk ? withQuestionResult(fetchedResults, query) : fetchedResults);
|
||||
}, 250);
|
||||
|
||||
@@ -211,7 +211,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
query={query}
|
||||
item={item}
|
||||
active={index === cursor}
|
||||
onClick={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -252,7 +251,6 @@ export const SearchResults = React.forwardRef(function SearchResults(
|
||||
query={query}
|
||||
item={item}
|
||||
active={index === cursor}
|
||||
onClick={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,20 +11,15 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
|
||||
query: string;
|
||||
item: ComputedSectionResult;
|
||||
active: boolean;
|
||||
onClick: (to: string) => void;
|
||||
},
|
||||
ref: React.Ref<HTMLAnchorElement>,
|
||||
) {
|
||||
const { query, item, active, onClick } = props;
|
||||
const { query, item, active } = props;
|
||||
|
||||
return (
|
||||
<Link
|
||||
ref={ref}
|
||||
href={item.href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
onClick(item.href);
|
||||
}}
|
||||
className={tcls(
|
||||
'search-section-result-item',
|
||||
'[&:has(+:not(&))]:mb-6',
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
SearchAIAnswer,
|
||||
SearchPageResult,
|
||||
Site,
|
||||
SiteSpace,
|
||||
Space,
|
||||
} from '@gitbook/api';
|
||||
import { headers } from 'next/headers';
|
||||
|
||||
import { getContentPointer } from '@/app/(space)/fetch';
|
||||
import { streamResponse } from '@/lib/actions';
|
||||
@@ -46,9 +46,65 @@ export interface AskAnswerSource {
|
||||
}
|
||||
|
||||
export interface AskAnswerResult {
|
||||
body: React.ReactNode;
|
||||
body?: React.ReactNode;
|
||||
followupQuestions: string[];
|
||||
sources: AskAnswerSource[];
|
||||
hasAnswer: boolean;
|
||||
}
|
||||
|
||||
export async function searchSiteContent(args: {
|
||||
query: string;
|
||||
siteSpaceIds?: string[];
|
||||
cacheBust?: string;
|
||||
}): Promise<OrderedComputedResult[]> {
|
||||
const { siteSpaceIds, query, cacheBust } = args;
|
||||
const pointer = getContentPointer();
|
||||
|
||||
if (siteSpaceIds?.length === 0) {
|
||||
// if we have no siteSpaces to search in then we won't find anything. skip the call.
|
||||
return [];
|
||||
}
|
||||
|
||||
if ('siteId' in pointer && 'organizationId' in pointer) {
|
||||
const [searchResults, allSiteSpaces] = await Promise.all([
|
||||
api.searchSiteContent(
|
||||
pointer.organizationId,
|
||||
pointer.siteId,
|
||||
query,
|
||||
siteSpaceIds,
|
||||
cacheBust,
|
||||
),
|
||||
siteSpaceIds
|
||||
? null
|
||||
: api.getSiteSpaces({
|
||||
organizationId: pointer.organizationId,
|
||||
siteId: pointer.siteId,
|
||||
siteShareKey: pointer.siteShareKey,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!siteSpaceIds) {
|
||||
// We are searching all of this Site's content
|
||||
return searchResults.items
|
||||
.map((spaceItem) => {
|
||||
const siteSpace = allSiteSpaces?.find(
|
||||
(siteSpace) => siteSpace.space.id === spaceItem.id,
|
||||
);
|
||||
|
||||
return spaceItem.pages.map((item) => transformSitePageResult(item, siteSpace));
|
||||
})
|
||||
.flat(2);
|
||||
}
|
||||
|
||||
return searchResults.items
|
||||
.map((spaceItem) => {
|
||||
return spaceItem.pages.map((item) => transformPageResult(item));
|
||||
})
|
||||
.flat(2);
|
||||
}
|
||||
|
||||
// This should never happen
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,6 +115,16 @@ export async function searchSpaceContent(
|
||||
revisionId: string,
|
||||
query: string,
|
||||
): Promise<OrderedComputedResult[]> {
|
||||
const pointer = getContentPointer();
|
||||
|
||||
if ('siteId' in pointer && 'organizationId' in pointer) {
|
||||
const siteSpaceIds = pointer.siteSpaceId ? [pointer.siteSpaceId] : []; // if we don't have a siteSpaceID search all content
|
||||
|
||||
// This is a site so use a different function which we can eventually call directly
|
||||
// We also want to break cache for this specific space if the revisionId is different so use it as a cache busting key
|
||||
return await searchSiteContent({ siteSpaceIds, query, cacheBust: revisionId });
|
||||
}
|
||||
|
||||
const data = await api.searchSpaceContent(spaceId, revisionId, query);
|
||||
return data.items.map((item) => transformPageResult(item, undefined)).flat();
|
||||
}
|
||||
@@ -71,34 +137,18 @@ export async function searchParentContent(
|
||||
query: string,
|
||||
): Promise<OrderedComputedResult[]> {
|
||||
const pointer = getContentPointer();
|
||||
const isSite = 'siteId' in pointer;
|
||||
|
||||
const [data, collectionSpaces, siteSpaces] = await Promise.all([
|
||||
if (isSite) {
|
||||
return searchSiteContent({ query });
|
||||
}
|
||||
|
||||
const [data, collectionSpaces] = await Promise.all([
|
||||
api.searchParentContent(parent.id, query),
|
||||
parent.object === 'collection' ? api.getCollectionSpaces(parent.id) : null,
|
||||
parent.object === 'site' && 'organizationId' in pointer
|
||||
? api.getSiteSpaces({
|
||||
organizationId: pointer.organizationId,
|
||||
siteId: parent.id,
|
||||
siteShareKey: pointer.siteShareKey,
|
||||
})
|
||||
: null,
|
||||
]);
|
||||
|
||||
let spaces: Space[] = [];
|
||||
|
||||
if (collectionSpaces) {
|
||||
spaces = collectionSpaces;
|
||||
} else if (siteSpaces) {
|
||||
spaces = Object.values(
|
||||
siteSpaces.reduce(
|
||||
(acc, siteSpace) => {
|
||||
acc[siteSpace.space.id] = siteSpace.space;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, Space>,
|
||||
),
|
||||
);
|
||||
}
|
||||
let spaces: Space[] = collectionSpaces ? collectionSpaces : [];
|
||||
|
||||
return data.items
|
||||
.map((spaceItem) => {
|
||||
@@ -112,12 +162,15 @@ export async function searchParentContent(
|
||||
* Server action to ask a question in a space.
|
||||
*/
|
||||
export const streamAskQuestion = streamResponse(async function* (spaceId: string, query: string) {
|
||||
const stream = api.api().spaces.streamAskInSpace(spaceId, { query, format: 'document' });
|
||||
const stream = api
|
||||
.api()
|
||||
.spaces.streamAskInSpace(spaceId, { query, format: 'document', details: true });
|
||||
const pagesPromise = api.getSpaceContentData({ spaceId });
|
||||
|
||||
for await (const chunk of stream) {
|
||||
// We run the AI search and fetch the pages in parallel
|
||||
const { pages } = await pagesPromise;
|
||||
|
||||
yield transformAnswer(chunk.answer, pages);
|
||||
}
|
||||
});
|
||||
@@ -134,7 +187,7 @@ function transformAnswer(
|
||||
answer: SearchAIAnswer | undefined,
|
||||
pages: RevisionPage[],
|
||||
): AskAnswerResult | null {
|
||||
if (!answer || !('document' in answer.answer)) {
|
||||
if (!answer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -158,36 +211,43 @@ function transformAnswer(
|
||||
.filter(filterOutNullable);
|
||||
|
||||
return {
|
||||
body: (
|
||||
<DocumentView
|
||||
document={answer.answer.document}
|
||||
context={{
|
||||
mode: 'default',
|
||||
contentRefContext: null,
|
||||
resolveContentRef: async () => null,
|
||||
shouldHighlightCode: () => false,
|
||||
}}
|
||||
style={['space-y-5']}
|
||||
/>
|
||||
),
|
||||
body:
|
||||
answer.answer && 'document' in answer.answer ? (
|
||||
<DocumentView
|
||||
document={answer.answer.document}
|
||||
context={{
|
||||
mode: 'default',
|
||||
contentRefContext: null,
|
||||
resolveContentRef: async () => null,
|
||||
shouldHighlightCode: () => false,
|
||||
}}
|
||||
style={['space-y-5']}
|
||||
/>
|
||||
) : null,
|
||||
followupQuestions: answer.followupQuestions,
|
||||
sources,
|
||||
hasAnswer: !!answer.answer && 'document' in answer.answer,
|
||||
};
|
||||
}
|
||||
|
||||
function transformPageResult(item: SearchPageResult, space?: Space) {
|
||||
function transformSectionsAndPage(args: {
|
||||
item: SearchPageResult;
|
||||
space?: Space;
|
||||
spaceURL?: string;
|
||||
}): [ComputedPageResult, ComputedSectionResult[]] {
|
||||
const { item, space, spaceURL } = args;
|
||||
|
||||
// Resolve a relative path to an absolute URL
|
||||
// if the search result is relative to another space, we use the space URL
|
||||
const getURL = (path: string) => {
|
||||
if (space) {
|
||||
let url = space.urls.published ?? space.urls.app;
|
||||
if (!url.endsWith('/')) {
|
||||
url += '/';
|
||||
const getURL = (path: string, spaceURL?: string) => {
|
||||
if (spaceURL) {
|
||||
if (!spaceURL.endsWith('/')) {
|
||||
spaceURL += '/';
|
||||
}
|
||||
if (path.startsWith('/')) {
|
||||
path = path.slice(1);
|
||||
}
|
||||
return url + path;
|
||||
return spaceURL + path;
|
||||
} else {
|
||||
return absoluteHref(path);
|
||||
}
|
||||
@@ -198,7 +258,7 @@ function transformPageResult(item: SearchPageResult, space?: Space) {
|
||||
type: 'section',
|
||||
id: item.id + '/' + section.id,
|
||||
title: section.title,
|
||||
href: getURL(section.path),
|
||||
href: getURL(section.path, spaceURL),
|
||||
body: section.body,
|
||||
})) ?? [];
|
||||
|
||||
@@ -210,5 +270,25 @@ function transformPageResult(item: SearchPageResult, space?: Space) {
|
||||
spaceTitle: space?.title,
|
||||
};
|
||||
|
||||
return [page, sections];
|
||||
}
|
||||
|
||||
function transformSitePageResult(item: SearchPageResult, siteSpace?: SiteSpace) {
|
||||
const [page, sections] = transformSectionsAndPage({
|
||||
item,
|
||||
space: siteSpace?.space,
|
||||
spaceURL: siteSpace?.urls.published,
|
||||
});
|
||||
|
||||
return [page, ...sections];
|
||||
}
|
||||
|
||||
function transformPageResult(item: SearchPageResult, space?: Space) {
|
||||
const [page, sections] = transformSectionsAndPage({
|
||||
item,
|
||||
space,
|
||||
spaceURL: space?.urls.published ?? space?.urls.app,
|
||||
});
|
||||
|
||||
return [page, ...sections];
|
||||
}
|
||||
|
||||
@@ -19,6 +19,14 @@ export function PagesList(props: {
|
||||
return (
|
||||
<ul className={tcls('flex', 'flex-1', 'flex-col', 'gap-y-0.5', style)}>
|
||||
{pages.map((page) => {
|
||||
if (page.type === 'link') {
|
||||
return <PageLinkItem key={page.id} page={page} context={context} />;
|
||||
}
|
||||
|
||||
if (page.hidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (page.type === 'group') {
|
||||
return (
|
||||
<PageGroupItem
|
||||
@@ -29,8 +37,6 @@ export function PagesList(props: {
|
||||
context={context}
|
||||
/>
|
||||
);
|
||||
} else if (page.type === 'link') {
|
||||
return <PageLinkItem key={page.id} page={page} context={context} />;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { CustomizationThemedURL } from '@gitbook/api';
|
||||
|
||||
import { Image } from '@/components/utils';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
|
||||
import { Emoji } from '../primitives';
|
||||
|
||||
export function LogoIcon(
|
||||
props: { icon?: CustomizationThemedURL; emoji?: string } & Omit<
|
||||
React.ComponentProps<typeof Image>,
|
||||
'sources'
|
||||
>,
|
||||
) {
|
||||
const { icon, emoji, alt, ...imageProps } = props;
|
||||
|
||||
if (emoji && !icon) {
|
||||
return <Emoji code={emoji} style="text-xl" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Image
|
||||
alt={alt ?? ''}
|
||||
sources={
|
||||
icon
|
||||
? {
|
||||
light: {
|
||||
src: icon.light,
|
||||
aspectRatio: '1',
|
||||
},
|
||||
dark: {
|
||||
src: icon.dark,
|
||||
aspectRatio: '1',
|
||||
},
|
||||
}
|
||||
: {
|
||||
light: {
|
||||
src: absoluteHref('~gitbook/icon?size=medium&theme=light', true),
|
||||
size: { width: 256, height: 256 },
|
||||
},
|
||||
dark: {
|
||||
src: absoluteHref('~gitbook/icon?size=medium&theme=dark', true),
|
||||
size: { width: 256, height: 256 },
|
||||
},
|
||||
}
|
||||
}
|
||||
{...imageProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
export * from './types';
|
||||
export * from './LogoIcon';
|
||||
|
||||
@@ -13,7 +13,9 @@ export const de = {
|
||||
search_scope_all: 'Alle Inhalte',
|
||||
search_ask: 'Fragen "${1}"',
|
||||
search_ask_sources: 'Quellen',
|
||||
search_ask_no_answer: 'Es konnte keine Antwort auf Ihre Frage gefunden werden, versuchen Sie es mit einer anderen Frage.',
|
||||
search_ask_sources_no_answer: 'Verwandte Seiten',
|
||||
search_ask_no_answer:
|
||||
'Es konnte keine Antwort auf Ihre Frage gefunden werden. Versuchen Sie, sie umzuformulieren oder genauer zu sein.',
|
||||
search_ask_error: 'Etwas ist schief gelaufen. Bitte versuchen Sie es später noch einmal.',
|
||||
on_this_page: 'Auf dieser Seite',
|
||||
next_page: 'Nächste',
|
||||
@@ -39,7 +41,8 @@ export const de = {
|
||||
notfound_title: 'Seite nicht gefunden',
|
||||
notfound: 'Die gesuchte Seite existiert nicht.',
|
||||
unexpected_error_title: 'Ein Fehler ist aufgetreten',
|
||||
unexpected_error: 'Entschuldigung, ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.',
|
||||
unexpected_error:
|
||||
'Entschuldigung, ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.',
|
||||
unexpected_error_retry: 'Erneut versuchen',
|
||||
pdf_download: 'Als PDF exportieren',
|
||||
pdf_goback: 'Zurück zum Inhalt',
|
||||
@@ -47,6 +50,7 @@ export const de = {
|
||||
pdf_page_of: '${1} von ${2}',
|
||||
pdf_mode_only_page: 'Nur diese Seite',
|
||||
pdf_mode_all: 'Alle Seiten',
|
||||
pdf_limit_reached: 'Das PDF konnte für ${1} Seiten nicht generiert werden, Generierung wurde bei ${2} gestoppt.',
|
||||
pdf_limit_reached:
|
||||
'Das PDF konnte für ${1} Seiten nicht generiert werden, Generierung wurde bei ${2} gestoppt.',
|
||||
pdf_limit_reached_continue: 'Mit ${1} weiteren Seiten erweitern.',
|
||||
};
|
||||
|
||||
@@ -13,7 +13,9 @@ export const en = {
|
||||
search_scope_all: 'All the content',
|
||||
search_ask: 'Ask "${1}"',
|
||||
search_ask_sources: 'Sources',
|
||||
search_ask_no_answer: 'No answer could be found for your question, try with another one.',
|
||||
search_ask_sources_no_answer: 'Related pages',
|
||||
search_ask_no_answer:
|
||||
'An answer could not be found for your question. You could try rephrasing it, or be more specific.',
|
||||
search_ask_error: 'Something went wrong. Please try again later.',
|
||||
on_this_page: 'On this page',
|
||||
next_page: 'Next',
|
||||
|
||||
@@ -15,7 +15,9 @@ export const es: TranslationLanguage = {
|
||||
search_scope_all: 'Todo el contenido',
|
||||
search_ask: 'Preguntar "${1}"',
|
||||
search_ask_sources: 'Fuentes',
|
||||
search_ask_no_answer: 'No se pudo encontrar una respuesta a tu pregunta, intenta con otra.',
|
||||
search_ask_sources_no_answer: 'Páginas relacionadas',
|
||||
search_ask_no_answer:
|
||||
'No se pudo encontrar una respuesta para su pregunta. Puede intentar reformularla o ser más específico.',
|
||||
search_ask_error: 'Algo salió mal. Por favor, inténtalo de nuevo más tarde.',
|
||||
on_this_page: 'En esta página',
|
||||
next_page: 'Siguiente',
|
||||
|
||||
@@ -15,7 +15,9 @@ export const fr: TranslationLanguage = {
|
||||
search_scope_all: 'Tout le contenu',
|
||||
search_ask: 'Demander "${1}"',
|
||||
search_ask_sources: 'Sources',
|
||||
search_ask_no_answer: 'Aucune réponse trouvée à votre question, essayez-en une autre.',
|
||||
search_ask_sources_no_answer: 'Pages connexes',
|
||||
search_ask_no_answer:
|
||||
"Aucune réponse n'a pu être trouvée pour votre question. Essayez de la reformuler ou d'être plus précis",
|
||||
search_ask_error: 'Quelque chose a mal fonctionné. Veuillez réessayer plus tard.',
|
||||
on_this_page: 'Sur cette page',
|
||||
next_page: 'Suivant',
|
||||
|
||||
@@ -15,8 +15,9 @@ export const ja: TranslationLanguage = {
|
||||
search_scope_all: '全てのコンテンツ',
|
||||
search_ask: '"${1}" を質問する',
|
||||
search_ask_sources: '情報源',
|
||||
search_ask_sources_no_answer: '関連ページ',
|
||||
search_ask_no_answer:
|
||||
'ご質問に答えられる答えが見つかりませんでした、他の質問を試してください。',
|
||||
'ご質問への回答が見つかりませんでした。質問を言い換えるか、もう少し具体的にしてください。',
|
||||
search_ask_error: '何らかのエラーが発生しました。後ほど再度お試しください。',
|
||||
on_this_page: 'このページ内',
|
||||
next_page: '次へ',
|
||||
|
||||
@@ -13,8 +13,9 @@ export const pt_br = {
|
||||
search_scope_all: 'Todo o conteúdo',
|
||||
search_ask: 'Perguntar "${1}"',
|
||||
search_ask_sources: 'Fontes',
|
||||
search_ask_sources_no_answer: 'Páginas relacionadas',
|
||||
search_ask_no_answer:
|
||||
'Nenhuma resposta foi encontrada para sua pergunta, tente outra pergunta.',
|
||||
'Não foi possível encontrar uma resposta para sua pergunta. Você pode tentar reformulá-la ou ser mais específico.',
|
||||
search_ask_error: 'Algo deu errado. Por favor tente novamente mais tarde.',
|
||||
on_this_page: 'Nesta página',
|
||||
next_page: 'Próximo',
|
||||
|
||||
@@ -15,7 +15,8 @@ export const zh: TranslationLanguage = {
|
||||
search_scope_all: '所有内容',
|
||||
search_ask: '询问"${1}"',
|
||||
search_ask_sources: '来源',
|
||||
search_ask_no_answer: '找不到您的问题的答案,请尝试另一个问题。',
|
||||
search_ask_sources_no_answer: '相关页面',
|
||||
search_ask_no_answer: '无法找到您的问题的答案。您可以尝试改述问题或提供更具体的信息。',
|
||||
search_ask_error: '出了些问题。请稍后再试。',
|
||||
on_this_page: '在本页',
|
||||
next_page: '下一页',
|
||||
|
||||
@@ -1046,6 +1046,41 @@ export const searchParentContent = cache(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Search content in a Site or specific SiteSpaces.
|
||||
*/
|
||||
export const searchSiteContent = cache(
|
||||
'api.searchSiteContent',
|
||||
async (
|
||||
organizationId: string,
|
||||
siteId: string,
|
||||
query: string,
|
||||
siteSpaceIds?: string[],
|
||||
/** A cache bust param to avoid revalidating lot of cache entries by tags */
|
||||
cacheBust?: string,
|
||||
options?: CacheFunctionOptions,
|
||||
) => {
|
||||
const response = await api().orgs.searchSiteContent(
|
||||
organizationId,
|
||||
siteId,
|
||||
{
|
||||
query,
|
||||
siteSpaceIds,
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
...noCacheFetchOptions,
|
||||
signal: options?.signal,
|
||||
},
|
||||
);
|
||||
|
||||
return cacheResponse(response, {
|
||||
ttl: 60 * 60,
|
||||
tags: [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Get a list of recommended questions in a space.
|
||||
*/
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
import { MaybePromise } from 'p-map';
|
||||
|
||||
import { waitUntil, getGlobalContext } from './waitUntil';
|
||||
import { waitUntil, getRequestContext } from './waitUntil';
|
||||
|
||||
/**
|
||||
* Execute a function for each input in parallel and return the first result.
|
||||
@@ -238,7 +238,7 @@ export function singleton<R>(execute: () => Promise<R>): () => Promise<R> {
|
||||
}
|
||||
|
||||
// Promises are not shared between requests in Cloudflare Workers
|
||||
const ctx = await getGlobalContext();
|
||||
const ctx = await getRequestContext();
|
||||
const current = states.get(ctx);
|
||||
if (current) {
|
||||
return current;
|
||||
@@ -269,7 +269,7 @@ export function singletonMap<Key extends string, Args extends any[], Result>(
|
||||
const states = new WeakMap<object, Map<string, Promise<Result>>>();
|
||||
|
||||
const fn: SingletonFunction<Key, Args, Result> = async (key, ...args) => {
|
||||
const ctx = await getGlobalContext();
|
||||
const ctx = await getRequestContext();
|
||||
let current = states.get(ctx);
|
||||
if (current) {
|
||||
const existing = current.get(key);
|
||||
@@ -292,7 +292,7 @@ export function singletonMap<Key extends string, Args extends any[], Result>(
|
||||
};
|
||||
|
||||
fn.isRunning = async (key: string) => {
|
||||
const ctx = await getGlobalContext();
|
||||
const ctx = await getRequestContext();
|
||||
const current = states.get(ctx);
|
||||
return current?.has(key) ?? false;
|
||||
};
|
||||
|
||||
Vendored
+17
-7
@@ -1,6 +1,6 @@
|
||||
import { CacheBackend } from './types';
|
||||
import { CacheBackend, CacheEntry } from './types';
|
||||
import { NON_IMMUTABLE_LOCAL_CACHE_MAX_AGE_SECONDS, isCacheEntryImmutable } from './utils';
|
||||
import { singleton } from '../async';
|
||||
import { getGlobalContext } from '../waitUntil';
|
||||
|
||||
export const memoryCache: CacheBackend = {
|
||||
name: 'memory',
|
||||
@@ -64,9 +64,19 @@ export const memoryCache: CacheBackend = {
|
||||
};
|
||||
|
||||
/**
|
||||
* With next-on-pages, the code seems to be isolated between the middleware and the handler.
|
||||
* To share the cache between the two, we use a global variable.
|
||||
* By using a singleton, we ensure that the cache is only created once and stored in the
|
||||
* current request context.
|
||||
* In memory cache shared globally.
|
||||
*/
|
||||
const getMemoryCache = singleton(async () => new Map());
|
||||
async function getMemoryCache(): Promise<Map<string, CacheEntry>> {
|
||||
const ctx: Awaited<ReturnType<typeof getGlobalContext>> & {
|
||||
gitbookMemoryCache?: Map<string, CacheEntry>;
|
||||
} = await getGlobalContext();
|
||||
|
||||
if (ctx.gitbookMemoryCache) {
|
||||
return ctx.gitbookMemoryCache;
|
||||
}
|
||||
|
||||
const gitbookMemoryCache = new Map<string, CacheEntry>();
|
||||
ctx.gitbookMemoryCache = gitbookMemoryCache;
|
||||
|
||||
return gitbookMemoryCache;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,15 @@ export function hexToRgb(hex: string): string {
|
||||
return `${r} ${g} ${b}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a hex color to a RGBA color.
|
||||
*/
|
||||
export function hexToRgba(hex: string, alpha: number): string {
|
||||
const [r, g, b] = hexToRgbArray(hex);
|
||||
// Return the RGBA values separated by spaces
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Tailwind-compatible shades from a single color
|
||||
* @param {string} hex The hex code to generate shades from
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ export function getContentSecurityPolicy(scripts: SpaceIntegrationScript[], nonc
|
||||
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' 'unsafe-eval' ${assetsDomain} https://integrations.gitbook.com https://cdn.iframe.ly;
|
||||
style-src 'self' ${assetsDomain} fonts.googleapis.com 'unsafe-inline';
|
||||
img-src * 'self' blob: data: files.gitbook.com ${assetsDomain};
|
||||
connect-src * 'self' integrations.gitbook.com app.gitbook.com api.gitbook.com ${assetsDomain};
|
||||
connect-src * 'self' integrations.gitbook.com app.gitbook.com api.gitbook.com srv.buysellads.com ${assetsDomain};
|
||||
font-src 'self' fonts.gstatic.com ${assetsDomain};
|
||||
frame-src *;
|
||||
object-src 'none';
|
||||
|
||||
+38
-8
@@ -1,5 +1,7 @@
|
||||
import 'server-only';
|
||||
|
||||
import fnv1a from '@sindresorhus/fnv1a';
|
||||
|
||||
import { noCacheFetchOptions } from '@/lib/cache/http';
|
||||
|
||||
import { rootUrl } from './links';
|
||||
@@ -39,7 +41,7 @@ export function isImageResizingEnabled(): boolean {
|
||||
/**
|
||||
* Check if a URL is an HTTP URL.
|
||||
*/
|
||||
export function checkIsHttpURL(input: string): boolean {
|
||||
export function checkIsHttpURL(input: string | URL): boolean {
|
||||
if (!URL.canParse(input)) {
|
||||
return false;
|
||||
}
|
||||
@@ -52,11 +54,16 @@ export function checkIsHttpURL(input: string): boolean {
|
||||
* Skip it for non-http(s) URLs (data, etc).
|
||||
* Skip it for SVGs.
|
||||
*/
|
||||
function checkIsSizableImageURL(input: string): boolean {
|
||||
if (input.endsWith('.svg')) {
|
||||
export function checkIsSizableImageURL(input: string): boolean {
|
||||
if (!URL.canParse(input)) {
|
||||
return false;
|
||||
}
|
||||
return checkIsHttpURL(input);
|
||||
|
||||
const parsed = new URL(input);
|
||||
if (parsed.pathname.endsWith('.svg')) {
|
||||
return false;
|
||||
}
|
||||
return checkIsHttpURL(parsed);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,7 +80,7 @@ export async function getResizedImageURL(
|
||||
return null;
|
||||
}
|
||||
|
||||
const signature = await generateSignature(input);
|
||||
const signature = await generateSignatureV1(input);
|
||||
|
||||
return (options) => {
|
||||
const url = new URL('/~gitbook/image', rootUrl());
|
||||
@@ -93,6 +100,7 @@ export async function getResizedImageURL(
|
||||
}
|
||||
|
||||
url.searchParams.set('sign', signature);
|
||||
url.searchParams.set('sv', '1');
|
||||
|
||||
return url.toString();
|
||||
};
|
||||
@@ -101,8 +109,12 @@ export async function getResizedImageURL(
|
||||
/**
|
||||
* Verify a signature of an image URL
|
||||
*/
|
||||
export async function verifyImageSignature(input: string, signature: string): Promise<boolean> {
|
||||
const expectedSignature = await generateSignature(input);
|
||||
export async function verifyImageSignature(
|
||||
input: string,
|
||||
{ signature, version }: { signature: string; version: '1' | '0' },
|
||||
): Promise<boolean> {
|
||||
const expectedSignature =
|
||||
version === '1' ? await generateSignatureV1(input) : await generateSignatureV0(input);
|
||||
return expectedSignature === signature;
|
||||
}
|
||||
|
||||
@@ -201,7 +213,25 @@ function stringifyOptions(options: CloudflareImageOptions): string {
|
||||
}, '');
|
||||
}
|
||||
|
||||
async function generateSignature(input: string): Promise<string> {
|
||||
// Reused buffer for FNV-1a hashing
|
||||
const fnv1aUtf8Buffer = new Uint8Array(512);
|
||||
|
||||
/**
|
||||
* New and faster algorithm to generate a signature for an image.
|
||||
* When setting it in a URL, we use version '1' for the 'sv' querystring parameneter
|
||||
* to know that it was the algorithm that was used.
|
||||
*/
|
||||
async function generateSignatureV1(input: string): Promise<string> {
|
||||
const all = [input, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
|
||||
return fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initial algorithm used to generate a signature for an image. It didn't use any versioning in the URL.
|
||||
* We still need it to validate older signatures that were generated without versioning
|
||||
* but still exist in previously generated and cached content.
|
||||
*/
|
||||
async function generateSignatureV0(input: string): Promise<string> {
|
||||
const all = [input, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
|
||||
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(all));
|
||||
|
||||
|
||||
+14
-3
@@ -75,12 +75,13 @@ export function resolvePageId(
|
||||
|
||||
/**
|
||||
* Resolve the next/previous page before another one.
|
||||
* It ignores hidden pages as this is used for navigation purpose.
|
||||
*/
|
||||
export function resolvePrevNextPages(
|
||||
rootPages: Revision['pages'],
|
||||
page: RevisionPageDocument,
|
||||
): { previous?: RevisionPageDocument; next?: RevisionPageDocument } {
|
||||
const flat = flattenPages(rootPages);
|
||||
const flat = flattenPages(rootPages, (page) => !page.hidden);
|
||||
|
||||
const currentIndex = flat.findIndex((p) => p.id === page.id);
|
||||
if (currentIndex === -1) {
|
||||
@@ -152,17 +153,27 @@ function resolvePageDocument(
|
||||
return { page, ancestors };
|
||||
}
|
||||
|
||||
function flattenPages(pages: RevisionPage[]): RevisionPageDocument[] {
|
||||
/**
|
||||
* Flatten a list of pages into a list of page documents.
|
||||
*/
|
||||
function flattenPages(
|
||||
pages: RevisionPage[],
|
||||
filter?: (page: RevisionPageDocument | RevisionPageGroup) => boolean,
|
||||
): RevisionPageDocument[] {
|
||||
const result: RevisionPageDocument[] = [];
|
||||
for (const page of pages) {
|
||||
if (page.type === 'link') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (filter && !filter(page)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (page.type === 'document') {
|
||||
result.push(page);
|
||||
}
|
||||
result.push(...flattenPages(page.pages));
|
||||
result.push(...flattenPages(page.pages, filter));
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
+26
-4
@@ -18,6 +18,8 @@ import { getPagePath, resolvePageId } from './pages';
|
||||
export interface ResolvedContentRef {
|
||||
/** Text to render in the content ref */
|
||||
text: string;
|
||||
/** Additional sub text to render in the content ref */
|
||||
subText?: string;
|
||||
/** Emoji associated with the reference */
|
||||
emoji?: string;
|
||||
/** URL to open for the content ref */
|
||||
@@ -103,10 +105,14 @@ export async function resolveContentRef(
|
||||
return resolveContentRefInSpace(contentRef.space, contentRef);
|
||||
}
|
||||
|
||||
const page =
|
||||
const resolvePageResult =
|
||||
!contentRef.page || contentRef.page === activePage?.id
|
||||
? activePage
|
||||
: resolvePageId(pages, contentRef.page)?.page;
|
||||
? { page: activePage, ancestors: [] }
|
||||
: undefined
|
||||
: resolvePageId(pages, contentRef.page);
|
||||
|
||||
const page = resolvePageResult?.page;
|
||||
if (!page) {
|
||||
return null;
|
||||
}
|
||||
@@ -134,7 +140,13 @@ export async function resolveContentRef(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
text = page.title;
|
||||
const parentPage = (resolvePageResult?.ancestors || []).slice(-1).pop();
|
||||
// When the looked up ref was a page group we use the page group title as resolved ref text.
|
||||
// Otherwise use the resolved page title.
|
||||
text =
|
||||
parentPage && contentRef.page === parentPage.id && parentPage.type === 'group'
|
||||
? parentPage.title
|
||||
: page.title;
|
||||
emoji = isCurrentPage ? undefined : page.emoji;
|
||||
}
|
||||
|
||||
@@ -164,6 +176,7 @@ export async function resolveContentRef(
|
||||
contentRef.space === space.id
|
||||
? space
|
||||
: await ignoreAPIError(getSpace(contentRef.space));
|
||||
|
||||
if (!targetSpace) {
|
||||
return {
|
||||
href: gitbookAppHref(`/s/${contentRef.space}`),
|
||||
@@ -244,12 +257,21 @@ async function resolveContentRefInSpace(spaceId: string, contentRef: ContentRef)
|
||||
baseUrl += '/';
|
||||
}
|
||||
|
||||
return resolveContentRef(contentRef, {
|
||||
const resolved = await resolveContentRef(contentRef, {
|
||||
space,
|
||||
revisionId: space.revision,
|
||||
pages,
|
||||
baseUrl,
|
||||
});
|
||||
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...resolved,
|
||||
subText: space.title,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveContentRefWithFiles(
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { startSpan } from '@sentry/nextjs';
|
||||
|
||||
export interface TraceSpan {
|
||||
setAttribute: (label: string, value: boolean | string | number) => void;
|
||||
@@ -22,7 +22,7 @@ export async function trace<T>(
|
||||
typeof name === 'string' ? { operation: name, name: undefined } : name;
|
||||
const completeName = executionName ? `${operation}(${executionName})` : operation;
|
||||
|
||||
return await Sentry.startSpan(
|
||||
return await startSpan(
|
||||
{
|
||||
name: completeName,
|
||||
op: operation,
|
||||
|
||||
+22
-7
@@ -1,10 +1,28 @@
|
||||
import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';
|
||||
|
||||
let pendings: Array<Promise<unknown>> = [];
|
||||
|
||||
/**
|
||||
* Get a global context object for the current execution.
|
||||
* This object can be used to store data that should be shared between the middleware and the handler
|
||||
* and re-used for all requests.
|
||||
*/
|
||||
export async function getGlobalContext(): Promise<ExecutionContext | object> {
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
// Do not try loading the next-on-pages package in tests as it'll fail
|
||||
return globalThis;
|
||||
}
|
||||
|
||||
// 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');
|
||||
return getOptionalRequestContext()?.ctx ?? globalThis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a global context object for the current request.
|
||||
* This object can be used as a key to store request-specific data in a WeakMap.
|
||||
*/
|
||||
export async function getGlobalContext(): Promise<object> {
|
||||
export async function getRequestContext(): Promise<IncomingRequestCfProperties | object> {
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
// Do not try loading the next-on-pages package in tests as it'll fail
|
||||
return globalThis;
|
||||
@@ -29,12 +47,9 @@ export async function waitUntil(promise: Promise<unknown>) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 cloudflare = getOptionalRequestContext();
|
||||
if (cloudflare) {
|
||||
cloudflare.ctx.waitUntil(promise);
|
||||
const cloudflareContext = await getGlobalContext();
|
||||
if ('waitUntil' in cloudflareContext) {
|
||||
cloudflareContext.waitUntil(promise);
|
||||
} else {
|
||||
await promise;
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
import { GitBookAPI } from '@gitbook/api';
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { setTag, setContext } from '@sentry/nextjs';
|
||||
import assertNever from 'assert-never';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import type { ResponseCookie } from 'next/dist/compiled/@edge-runtime/cookies';
|
||||
@@ -94,8 +94,8 @@ interface ContentAPITokenPayload {
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { url, mode } = getInputURL(request);
|
||||
|
||||
Sentry.setTag('url', url.toString());
|
||||
Sentry.setContext('request', {
|
||||
setTag('url', url.toString());
|
||||
setContext('request', {
|
||||
method: request.method,
|
||||
url: url.toString(),
|
||||
rawRequestURL: request.url,
|
||||
@@ -145,8 +145,8 @@ export async function middleware(request: NextRequest) {
|
||||
return writeCookies(NextResponse.redirect(normalizedVA.toString()), resolved.cookies);
|
||||
}
|
||||
|
||||
Sentry.setTag('space', resolved.space);
|
||||
Sentry.setContext('content', {
|
||||
setTag('space', resolved.space);
|
||||
setContext('content', {
|
||||
space: resolved.space,
|
||||
changeRequest: resolved.changeRequest,
|
||||
revision: resolved.revision,
|
||||
|
||||
Reference in New Issue
Block a user